[Android] when calling stopself () in onStartCommand () of the Service, you should note that androidatcommand
After stopself () is called in onStartCommand () of the Service, destroy does not immediately drop the service, but destroy only after onStartCommand () is executed.
Public class TestService extends Service {private String TAG = "TestService"; @ Overridepublic void onCreate () {// TODO Auto-generated method stubLog. I (TAG, "onCreate"); super. onCreate () ;}@ Overridepublic int onStartCommand (Intent intent, int flags, int startId) {// TODO Auto-generated method stubLog. I (TAG, "onStartCommand"); stopSelf (); Log. I (TAG, "I'm still running! "); Return super. onStartCommand (intent, flags, startId) ;}@ Overridepublic void onDestroy () {// TODO Auto-generated method stubLog. I (TAG, "onDestroy"); super. onDestroy () ;}@ Overridepublic IBinder onBind (Intent intent) {// TODO Auto-generated method stubreturn null ;}}
MainActivity uses a button to start the service:
@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {case R.id.testBtn:Intent intent = new Intent(this,TestService.class);startService(intent);break;default:break;}}
Print result:
Note that,Multiple calls to stopSelf () will not throw an exception.
I wrote an android automatic dialing system. The activity starts the service but calls stopself () in the service and does not stop the service.
Isn't this application implemented by mobile phones now? Why do you still write?
In android, why does startService (intent) not execute onStartCommand () of service? I am a newbie.
You just registered <service android: name = "com. Sevices. mqtt. ReceivingMessageService"/>
The service is not named, so Intent intent = new Intent ("com. Sevices. mqtt. ReceivingMessageService ");
In this way, your service cannot be started. Please change to the following:
Intent intent = new Intent (MainActivity. this, com. Sevices. mqtt. ReceivingMessageService. class );
Or add an alias in manifest:
<Service android: name = "com. Sevices. mqtt. ReceivingMessageService">
<Intent-filter>
<Action android: name = "com. Sevices. mqtt. ReceivingMessageService"/>
</Intent-filter>
</Service>