如何每15分钟运行一次Android功能,特别是每天15分钟? [英] How to run an android function every 15 minutes , and specifically on the 15 minute mark everyday?

查看:165
本文介绍了如何每15分钟运行一次Android功能,特别是每天15分钟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个重复的问题,但我仍然面临着这方面的问题,希望有一个解决方案。在此先感谢。

This maybe a repeated question here but I'm still facing issues on this, hope there's a solution around. Thanks in advance.

如何将警报管理器设置为运行,以便每隔15分钟(例如8:00,8)专门执行该功能:每天15:8:30,8:45,9:00 无论申请开始的时间如何。

How do I set the alarm manager to run so as to execute the function specifically at every 15 minutes clock interval, for example 8:00, 8:15, 8:30, 8:45, 9:00 everyday regardless of the time when the application is started.

举例如果假设我在7:47开始我的应用程序主要活动,我希望闹钟在8:00开始,然后是8:15,8:30等等......我该怎么办?如果有任何建议我真的很感激..

Take an example if let's say I started my application main activity at 7:47, and I would like the alarm to start at 8:00, followed along with 8:15, 8:30 and etc....how should I do? I would really appreciate if any suggestions are given..

推荐答案

你应该设置两个报警管理器。对于第一个设置的触发时间通过计算适当时间的剩余时间(例如上午8:00)。然后你应该在你的第一个警报管理器内创建另一个警报管理器,每个触发15分钟。

you should setup two alarm manager.for the first one set trigger time by calculating the remain time to your appropriate time (for example 8:00 Am). and after that you should create another alarm manager inside of your first alarm manager that will trigger each 15 minutes.

用于设置第一个警报管理器的计算时间使用下面的代码:

for calculate time for set first alarm manager use the code bellow:

Calendar c = Calendar.getInstance(); 
int m = calendar.get(Calendar.MINUTE);
long start = System.currentTimeMillis();
int remain=0;
if (m<15)
{
 remain = 15-m;
}
else if (m<30)
{
 remain = 30-m;
}
else if (m<45)
{
 remain = 45-m;
}
else
{
 remain = 60-m;
}
remain=start + remain*60*1000// convert it to milisecond and plus it to current time;

修改

之后你可以使用下面的代码设置第一个报警管理器:

and after that you can use code bellow to setup first alarm manager:

 AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, FirstReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    am.set(AlarmManager.RTC_WAKEUP,remain, pi);

所以现在在你的FirstReceiver课上做类似下面的事情:

so now in your FirstReceiver class do something like bellow:

public class FirstReceiver extends BroadcastReceiver
{
//do what ever you want + code bellow to setup second alarm manager
 Intent intent = new Intent(this, SecAlarm.class);
 PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
 AlarmManager am=  (AlarmManager)getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME,SystemClock.elapsedRealtime(),
                15*60*60,pendingIntent);
}

这篇关于如何每15分钟运行一次Android功能,特别是每天15分钟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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