无法在Android上启动警报服务

时间:2016-01-02 12:55:27

标签: android alarmmanager

我正在尝试设置重复闹钟

AlarmReceiver.java

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "ALARM START SUCCESSFUL", Toast.LENGTH_SHORT).show();
    }

}

在我的片段中,我称之为

Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
    calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());

    /* Repeating on every 20 minutes interval */
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            1000 * 60 * 20, pendingIntent);

其中pendingIntent设置为

alarmManager = (AlarmManager)(getActivity().getSystemService(Context.ALARM_SERVICE));
Intent intent = new Intent("FIRE_ALARM");
pendingIntent=PendingIntent.getBroadcast(getActivity(), MONDAY, intent, 0);

当我仅在当前时间小于timePicker时间时单击设置警报按钮时出现Toast。

的AndroidManifest.xml

<receiver android:name="AlarmReceiver">
        <intent-filter>
            <action android:name="FIRE_ALARM"/>
        </intent-filter>
    </receiver>

1 个答案:

答案 0 :(得分:0)

自API级别19 setRepeating()将不再在确切时间触发。你可以这样做:

public class AlarmReceiver extends BroadcastReceiver {

    public static synchronized void startAlarm() {

        AlarmManager alarmManager =
            (AlarmManager) ApplicationContext.getContext().getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent("FIRE_ALARM");
        PendingIntent pendingIntent =
            PendingIntent.getBroadcast(ApplicationContext.getContext(), 1, intent, 0);

        // ...

        if (Build.VERSION.SDK_INT >= 19)
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, interval, pendingIntent);
        else
            alarmManager.set(AlarmManager.RTC_WAKEUP, interval, pendingIntent);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("FIRE_ALARM")) {
            // do stuff
            startAlarm();
        }
    }
}

然后从主要活动中调用AlarmReceiver.startAlarm()。