标签:cli tag bre todo ring err blog ret pre
在Service的onStartCommand()中调用stopself()后并不会立马destroy掉service,而是等onStartCommand()运行完才destroy。
public class TestService extends Service { private String TAG = "TestService"; @Override public void onCreate() { // TODO Auto-generated method stub Log.i(TAG, "onCreate"); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub Log.i(TAG, "onStartCommand"); stopSelf(); Log.i(TAG, "我还在运行!"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { // TODO Auto-generated method stub Log.i(TAG, "onDestroy"); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } }
MainActivity用一个button来启动service:
@Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.testBtn: Intent intent = new Intent(this,TestService.class); startService(intent); break; default: break; } }
打印结果:
另外须要注意的是。多次调用stopSelf()不会抛出异常。
【android】在Service的onStartCommand()中调用stopself()应该注意的问题
标签:cli tag bre todo ring err blog ret pre
原文地址:http://www.cnblogs.com/jzssuanfa/p/6758379.html