how to prevent service to run again if already running android

前端 未结 5 2129
猫巷女王i
猫巷女王i 2021-02-06 21:49

On click of a button I want to start service using method startService(new Intent(currentActivity.this,MyService.class)) but if service is running I don\'t want to

5条回答
  •  别那么骄傲
    2021-02-06 22:13

    A service will only run once, so you can call startService(Intent) multiple times.

    You will receive an onStartCommand() in the service. So keep that in mind.

    Source: Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

    At: http://developer.android.com/reference/android/app/Service.html on topic: Service Lifecycle

提交回复
热议问题