Axe*_*OBO 6 java android alarmmanager
我有一个应用程序,需要每分钟执行一次代码.但问题是代码必须在每一分钟的时钟变化时执行.意思是,
如果它的12:34则代码将在12:35执行并继续.但我目前的代码工作,但它包括秒.含义,
如果它的12:34:30并且警报开始,则执行代码.但是代码然后在12:35:30执行.
我希望每分钟根据手机的时钟执行代码.以下是当前代码.
Intent intent2 = new Intent(MainActivity.this, MyABService.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent2, 0);
AlarmManager alarm_manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm_manager.setRepeating(AlarmManager.RTC, c.getTimeInMillis(), 1 * 1000, pintent);
Run Code Online (Sandbox Code Playgroud)
我让它每秒执行一次,以便在确切的时间发生效果.而不是每一秒我都需要它在时钟的每一分钟变化(每分钟)重复一次
我该如何解决这个问题
Sou*_*h86 10
使用Intent.ACTION_TIME_TICK这是Android OS每分钟触发的广播意图.注册到它,因为您将注册到代码中的正常系统广播(不能从清单中工作)
tickReceiver=new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().compareTo(Intent.ACTION_TIME_TICK)==0)
{
//do something
}
};
//Register the broadcast receiver to receive TIME_TICK
registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
Run Code Online (Sandbox Code Playgroud)
该文章描述了整个过程.
使用日历将触发时间设置为下一整分钟,并每分钟重复一次(60*1000ms)
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 1);
calendar.set(Calendar.SECOND, 0);
long triggerAt = calendar.getTimeInMillis();
long repeatAfter = 60 * 1000;
alarm_manager.setRepeating(AlarmManager.RTC, triggerAt, repeatAfter, pintent);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1713 次 |
| 最近记录: |