每 5 分钟启动一次 Android 服务

编程入门 行业动态 更新时间:2024-10-12 03:27:10
本文介绍了每 5 分钟启动一次 Android 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在互联网上搜索了过去 2 天,但找不到任何有用的教程.我创建了一个服务,并且在服务启动时在状态栏中发送通知.我希望该服务在显示通知后停止,并在 5 分钟后重新启动.如果可能,请告诉我,如果有的话,请提供一些有用的教程.我听说过 TimerTask 和 AlarmManager 并且我也尝试使用它们,但我无法获得想要的结果.

I was searching over the internet for last 2 days but I couldn't find any tutorial helpful. I have created a service and I am sending a notification in status bar when the service starts. I want that service to stop after showing the notification and start it again after 5 minutes. Please let me know if it is possible and provide me some helpful tutorials if you have any. I heard of TimerTask and AlarmManager and I tried to use them as well but I wasn't able to get the desired result.

即使我的应用程序没有运行,我也需要每 5 分钟启动一次服务.

I need the service to be started every 5 minutes even if my application is not running.

推荐答案

您不想使用 TimerTask,因为这取决于您的应用程序持续运行.AlarmManager 实现使您的应用程序可以安全地在两次执行之间被终止.

You do not want to use a TimerTask since this depends on your application running continuously. An AlarmManager implementation makes it safe for your application to be killed between executions.

声明您尝试使用 AlarmManager 但没有得到想要的结果并不是一个有用的声明,因为它告诉没有人可以帮助您正确使用它.表达发生的事情会更有用.

Stating that you tried to use AlarmManager but did not get the desired result is not a helpful statement, in that it tells no one how to help you to get it right. It would be much more useful to express what happened.

web.archive/web/20170713001201/code4reference/2012/07/tutorial-on-android-alarmmanager/ 包含似乎是关于 的有用教程警报管理器.以下是重点:

web.archive/web/20170713001201/code4reference/2012/07/tutorial-on-android-alarmmanager/ contains what appears to be a useful tutorial on AlarmManager. Here are the salient points:

1) 您的警报将在到期时触发 Intent.由您决定什么样的 Intent 以及它应该如何实现.我提供的链接有一个基于 BroadcastReceiver 的完整示例.

1) Your alarm will cause an Intent to fire when it expires. It's up to you to decide what kind of Intent and how it should be implemented. The link I provided has a complete example based on a BroadcastReceiver.

2) 您可以使用以下示例安装警报:

2) You can install your alarm with an example such as:

public void setOnetimeTimer(Context context) { AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class); intent.putExtra(ONE_TIME, Boolean.TRUE); PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0); am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 60 * 5), pi); }

更多推荐

每 5 分钟启动一次 Android 服务

本文发布于:2023-11-24 05:55:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1624165.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!