1

Im sure this is a very common problem but have not seen any questions asked on how to accomplish the following.

I created a service that runs every 5 minutes and gets called when the device has finished on BOOT_COMPLETE and this works just fine.

The problem I am encountering is when I am debugging on my device I have to re-boot my phone in order to get the service to launch. Is there a way for me to start this background service that runs every 5 mintues on Application Startup.

So what I need is to check if the service is running in the first place and if it is not start it.

Just to elaborate a little bit more, this service fetches data of the web so my ideal situation of having it get kicked off by BOOT_COMPLETE works just great. But in the scenarios that the user downloads the app and launches it this service will not get kicked off so I need a manual way of starting. If the service is not running, which it wouldn't be if the user just installed it I need to start it.

4

3 回答 3

2

我实际上通过使用以下链接中使用的方法解决了我的问题。

如何发送和接收广播消息

从 Manifest 中移除 IntentFilter 并手动调用它。希望这对其他人有帮助。

    if(!isMyServiceRunning()) {
        Intent intent = new Intent(mContext, OnBootReceiver.class);
        sendBroadcast(intent); 
    }
于 2013-06-11T21:14:07.730 回答
1

您可以使用 手动启动服务adb shell。请参阅如何从 adb shell 启动和停止 android 服务?

命令是:

am startservice com.your.package/.ServiceClassName

根据 Android 版本,有效语法可能会略有变化,例如:

am startservice -n com.your.package/.ServiceClassName
am startservice -a com.your.package/.ServiceClassName
am startservice --user 0 -n com.your.package/.ServiceClassName
于 2013-06-11T20:26:41.323 回答
1

听起来你想做一个由 BOOT_COMPLETE 事件启动的粘性服务

http://developer.android.com/reference/android/app/Service.html#START_STICKY

对于开发,您可以在服务中添加另一个意图过滤器来启动它,这样您就可以在每次代码更新后通过命令行中的活动管理器手动触发它,而无需重新启动设备。

于 2013-06-11T20:26:50.637 回答