首页 > 代码库 > 【android】在Service的onStartCommand()中调用stopself()应该注意的问题

【android】在Service的onStartCommand()中调用stopself()应该注意的问题

在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()应该注意的问题