为什么警报管理器不在午夜执行任务,即使代码是对的?

时间:2017-03-22 10:21:07

标签: android alarmmanager

场景:

我的任务将在每个午夜使用AlarmManager执行,让我们在00:00:00说,并且应该每天重复

我使用以下代码:

Calendar setCalendar = Calendar.getInstance();
setCalendar.set(Calendar.HOUR_OF_DAY, 0);
setCalendar.set(Calendar.MINUTE,0);
setCalendar.set(Calendar.SECOND,0);

PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(this, AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC, setCalendar.getTimeInMillis(), 1000 * 60 *60 *24, pi);

我也做了alarmManager.setInexactRepeating(AlarmManager.RTC, setCalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);但结果仍然相同(不是每个午夜都执行)

接收者:

public static class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
       //execute my task
    }
}

Android Manifest:

<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>    
<receiver android:name="com.projectx.activity.MainActivity$AlarmReceiver"/>

即使午夜过去,上面的代码也没有做任何事情。我的代码有什么问题吗?请帮忙。

有时候我在设置闹钟后每隔几秒就会执行一次闹钟(不仅是在午夜)

我不知道是什么原因造成的。

2 个答案:

答案 0 :(得分:0)

试试这个:

AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent intent1 = new Intent(context, TestNotifyService.class);
            PendingIntent alarmIntent = PendingIntent.getService(context, 0, intent1, 0);
long _Nalarm;
            Calendar now = Calendar.getInstance();
            Calendar wakeupcall = Calendar.getInstance();
            wakeupcall.setTimeInMillis(System.currentTimeMillis());
            wakeupcall.set(Calendar.HOUR_OF_DAY, 21);
            wakeupcall.set(Calendar.MINUTE, 59);

            if (wakeupcall.getTimeInMillis() <= now.getTimeInMillis())
                _Nalarm=wakeupcall.getTimeInMillis() + (AlarmManager.INTERVAL_DAY+1);
            else
                _Nalarm=wakeupcall.getTimeInMillis();



           alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, _Nalarm,AlarmManager.INTERVAL_DAY, alarmIntent);
        }

答案 1 :(得分:0)

尝试以下代码

rhqadmin

接收者:

Calendar setCalendar = Calendar.getInstance();
    setCalendar.set(Calendar.HOUR_OF_DAY, 0);
    setCalendar.set(Calendar.MINUTE,0);
    setCalendar.set(Calendar.SECOND,0);
    setCalendar.add(Calendar.DATE, 1);

    PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(this, AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.setInexactRepeating(AlarmManager.RTC, setCalendar.getTimeInMillis(), 1000 * 60 *60 *24 , pi);

如果有任何问题,请告诉我。