发现我的服务在 Android 中是否正在运行?
我有一项服务可以联系服务器以定期从我的应用程序传输一些数据。它工作正常。
但是当我重新启动(关闭然后打开)手机时,该服务无法重新启动。所以我的想法是,当用户重新启动手机后打开我的应用程序时再次启动该服务。为此,我必须知道我的服务是否正在运行?怎么办呢?
任何其他处理这种情况的想法也很感激。
提前致谢。
I have a service to contact the server to do some data transfer from my app periodically. Its working fine.
But when i restarted(switch off and on) my phone that service can not be restarted. so my idea is that to start that service again when the user open my app after restarting the phone. For that, i have to know about my service is running or not? how to do it?
Any other idea to handle this scenario also thankful.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要
BroadcastReceiver
的实现,其中用于BOOT_COMPLETED
操作。像这样:另外,您应该添加
receiver
< /a> 使用android:name
标记到清单文件 = OnStartReceiver 的完全限定名称以及嵌套在BOOT_COMPLETED
作为意图名称,如下所示:you need an implementation of
BroadcastReceiver
, which is intended onBOOT_COMPLETED
action. Like this:Also, you should add
receiver
tag to your manifest file withandroid:name
= your fully qualified name of OnStartReceiver and intent-filter tag nested withBOOT_COMPLETED
as intent name, like this:创建一个
BroadcastReceiver
来侦听ACTION_BOOT_COMPLETED
事件。更多详情请点击此处。Create a
BroadcastReceiver
to listen for theACTION_BOOT_COMPLETED
event. More details here.使用
AlarmManager
执行此类计划任务,因此您的服务不需要始终位于内存中。正如 Ribery 先生所指出的,使用BroadcastReceiver
和ACTION_BOOT_COMPLETED
在手机重启后重新安排任务。Use
AlarmManager
for scheduled tasks like this, so your service does not need to be in memory all of the time. As Mr. Ribery indicates, use aBroadcastReceiver
withACTION_BOOT_COMPLETED
to re-schedule your tasks after a phone reboot.