如何始终保持服务运行?

发布于 2024-08-30 01:29:32 字数 105 浏览 2 评论 0原文

我有一些进程想一直在后台运行。

所以我把它变成了一个服务

我的问题是:有什么办法可以防止用户终止该服务吗? (即使他使用第三方应用程序)

I have some process that I would like to run in the background the whole time.

So I made it a Service.

My question is: is there anyway to prevent from the user from killing this service? (even if he uses third party app)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

淡淡绿茶香 2024-09-06 01:29:32

也许这可以帮助您:

final Intent intent = new Intent(context, YourService.class);
final PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
long interval = 30000;//milliseconds
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),interval, pending);

这样您的服务将定期从 AlarmManager 接收 onStart 事件。如果您的服务停止,它将重新启动。所以你可能会说它将无限运行。
可以在 Photostream 示例应用程序 http://code.google.com/ 中找到更完整的示例p/apps-for-android/

Maybe this can help you:

final Intent intent = new Intent(context, YourService.class);
final PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
long interval = 30000;//milliseconds
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),interval, pending);

This way your service will be receiving regular onStart events from AlarmManager. If your service is stopped it will be restarted. So you may say it will be running infinitely.
More complete sample can be found in Photostream sample application http://code.google.com/p/apps-for-android/.

烟酉 2024-09-06 01:29:32

•启动的服务可以使用startForeground(int,Notification) API将服务置于前台状态,系统认为它是用户主动意识到的东西,因此不是候选者内存不足时杀死。 (理论上,在当前前台应用程序的极端内存压力下,该服务仍然有可能被终止,但实际上这不应该是一个问题。)

•A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)

獨角戲 2024-09-06 01:29:32

在服务的onDestory方法中发送广播,在广播接收器的onReceive方法中重新启动服务。
但请确保您的服务的资源处于控制之下

Send a broadcast in the onDestory method of the service, restart the service in the onReceive method the the broadcast receiver.
But make sure the resources your service are under control

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文