How to stop remote service
I have created a service and an activity. In that activity I have two buttons. One is to start service and another to stop service. I can start the remote activity by calling startService()
but unable to stopr service using stopService()
. If i click on start button I found extra remote process strarted running (using eclipse ide). I am expecting if i click on stop button then that additional process shouls stop. but Its not happening. I am able to call start and stop service method successfully. To verify the code I have added a toast message in each start and stop method. How to stop remote service?
My Activity
public class SimpleServiceController extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button start = (Button)findViewById(R.id.serviceButton);
Button stop = (Button)findViewById(R.id.cancelButton);
start.setOnClickListener(startListener);
stop.setOnClickListener(stopListener);
}
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v){
startService(new Intent(SimpleServiceController.this,SimpleService.class));
}
};
private OnClickListener stopListener = new OnClickListener() {
public void onClick(View v){
stopService(new Intent(SimpleServiceController.this,SimpleService.class));
}
};
}
Service
public class SimpleService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method开发者_JAVA百科 stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
}
}
Manifest
<service android:name=".SimpleService" android:process=":remote">
</service>
In Android, there's an important distinction between a running service and a running process.
A service follows a carefully defined lifecycle; it begins when onStartCommand()
is called and ends after onDestroy()
is finished. During that lifetime, the service can be performing tasks or sitting idle, but it is still running.
A process can extend beyond the life of a service. As you've seen, the process can keep running for some time after your service has stopped. Don't worry about it. Android will destroy the process and reclaim any resources exactly when it needs to. It's definitely confusing at first, but once your service has stopped, you don't need to care about the process it was in.
Bottom line: if onDestroy
has been called, your service has stopped. Don't worry about the leftover process.
精彩评论