如何prevent服务运行,如果再已运行Androidprevent、Android

2023-09-06 03:46:04 作者:℅Δ給ηι狗臉

在点击一个按钮,我想用方法 startService(新意图(currentActivity.this,MyService.class))来启动服务但是,如果服务正在运行,我不'吨要调用此方法,以避免运行服务,已经running.How这是possible.I正在同时使用的意图服务和服务在同一个项目,并希望应用相同的条件为。

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 call this method to avoid run service that is already running.How this is possible.I am using both Intent service and Service in same project and want to apply same condition for both.

推荐答案

一个服务将只运行一次,所以你可以调用 startService(意向)多次。

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

您会收到 onStartCommand()的服务。所以记住这一点。

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

来源: 需要注意的是多次调用 Context.startService()不嵌套(尽管他们导致多个相应的调用 onStartCommand()),所以无论多少次启动的服务将被停止,一旦 Context.stopService() stopSelf()被调用;然而,服务可以使用自己的 stopSelf(INT)方法,以确保该服务不会停止,直到开始的意图都被处理。

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.

在http://developer.android.com/reference/android/app/Service.html在题目:服务生命周期

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