Reputation: 1889
I have an activity that send some details to my db, but when I click the back button it stops. Is it possible to make it run on the background?I heared that using a Service could solve that issue but since all of my classes are wrriten as Activities I would like to know if it's possible. It's can't be done with some code on the onStop method?
Upvotes: 0
Views: 99
Reputation: 449
Heey,
Create a new class that extends of Service. Add the necessary overrides.
@Override
public IBinder onBind(Intent intent)
{
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//this service will run until we stop it
// This will execute when the service starts
return START_STICKY; //makes it sticky to keep it on until its destroyd
}
@Override
public void onDestroy()
{
super.onDestroy();
// when the service is destroyd
}
You can start a service with:
stopService(new Intent(getBaseContext(), ServiceClassName.class));
You can stop a service with:
stopService(new Intent(getBaseContext(), ServiceClassName.class));
Hope this helps :)
Upvotes: 2
Reputation: 1433
You will have to override the onBackPressed method to do what you want. If you want to "hide" the activity (so the user sees that it 'closes') you can call the moveTaskToBack method.
Upvotes: 1
Reputation: 448
You should write a Service that the Activity communicates with using intents. Thus it should send the data to the service for it to send to the database, then the service can inform the activity. When the Activity listens to events from the Service, you are implementing the Observer pattern (Listeners in Java and Android and many other event processing systems).
You can also poll the service, but that is not the preferred pattern for getting status updates.
Upvotes: 0
Reputation: 2948
You mentioned that all of your classes are written as Activities, which I am assuming means you have your application logic embedded with your user interface logic. This is generally not a good practice - you should try and migrate application specific code to a separate class. By having this functionality outside your user interface, your application will benefit in numerous ways.
To answer your question, it is possible to have your application perform functions in the background by subclassing Service
. Take a look here for a great explanation.
Upvotes: 1