每 5 分钟启动一次 Android 服务 [英] Start Android Service after every 5 minutes

查看:28
本文介绍了每 5 分钟启动一次 Android 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

http://web.archive.org/web/20170713001201/http://code4reference.com/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 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆