Reputation: 169
I write this code in the onDestroy() method.
@Override
public void onDestroy()
{
MessageService.this.stopSelf();
messageThread.isRunning = false;
System.exit(0);
super.onDestroy();
}
And close the service in other Activity.
stopService(new Intent(MainOptionActivity.this,MessageService.class));
I tried many code, it can not close the service when close the background. Could anyone give me some advice? Thanks.
Upvotes: 0
Views: 68
Reputation: 9217
Here is a simple code for service class
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "MSG onCreate SERVICE", Toast.LENGTH_LONG).show();
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "MSG onStartCommand SERVICE", Toast.LENGTH_LONG).show();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Toast.makeText(getApplicationContext(), "MSG STOP SERVICE", Toast.LENGTH_LONG).show();
super.onDestroy();
}
}
and here is the code for testing this service
startService(new Intent(this, MyService.class));
new Timer().schedule(new TimerTask() {
@Override
public void run() {
startService(new Intent(getApplicationContext(), MyService.class));
}
}, 5000);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
stopService(new Intent(getApplicationContext(), MyService.class));
}
}, 10000);
this is working just fine. Also add this code in manifest
<service android:name=".MyService" />
Upvotes: 2
Reputation: 5166
Don't use System.exit(0)
on Android, instead use finish
(in Activity for example).
But there is no need to stop itself onDestroy
method, it is actually gonna be stopped and destroyed (that's what onDestroy
method is for).
You stop the execution of the method with System.exit(0);
and therefore system never reaches super.onDestroy();
point and service is not destroyed.
Try just
@Override
public void onDestroy() {
messageThread.isRunning = false;
super.onDestroy();
}
Upvotes: 1