警报永远不会在Android中被触发

时间:2017-09-02 12:03:29

标签: android alarmmanager

我的警报永远不会被解雇。 以下是我的代码

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.SECOND, 30);

    Intent intent = new Intent(MainActivity.this, MyBroadcastReceiver.class);
    PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent,
            0);
    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),60*1000,
             pintent);

1 个答案:

答案 0 :(得分:0)

不要忘记在 AndroidManifest.xml中添加权限

<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>

尝试使用此代码通过意图设置警报:

    private void setAlarm(int hours_to_add, int minutes_to_add) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTimeInMillis(System.currentTimeMillis());
    int day = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    int minute = cal.get(Calendar.MINUTE);

    Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
    i.putExtra(AlarmClock.EXTRA_HOUR, hour + hours_to_add);
    i.putExtra(AlarmClock.EXTRA_MINUTES, minute + minutes_to_add);
    i.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
    startActivity(i);
}