Where to call stopService() to ensure a service is stopped?
I'm aware many questions regarding how to stop a service have been asked before, but I didn't find one addressing my particular problem.
In my application I have a number of activities that communicate with one central service. For each activity I call bindService() in their onResume() methods and unbindService() in their onPause() methods. The issue I'm having with this is that each time I switch between two activities the service is destroyed and then recreated from scratch.
In order to address this I have considered calling startService() in onCreate(), to ensure the service remains active.
My question is, where should I put the stopService()-Method to ensure it is called when leaving the application? 开发者_高级运维Or alternatively, is there a another way to keep the service running as I switch between two activities, without relying startService()?
See android service startService() and bindService() for a comprehensive answer.
this is how i stop and start the service
check this link for more details.
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
break;
}
}
and in services class:
public class MyService extends Service {
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
HAPPY CODING!
精彩评论