AlarmManager当前没有开始活动

时间:2017-11-07 02:11:05

标签: android android-alarms

我的AlarmActivitysingleInstance 我用这个意图注册到AlarmManager:

Intent intent = new Intent(context, AlarmActivity.class);
PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

问题:当AlarmActivity当前正在打开闹铃时,它无法启动。

我正在寻找一个干净的简单解决方案,以便在闹钟响起时调用AlarmActivity中的方法(可以onStart()onResume()...)。

我不想使用Service或BroadcastReceiver。这可能吗?

1 个答案:

答案 0 :(得分:0)

我认为您在onResume()中添加了警报代码。

@Override
protected void onResume() {
    super.onResume();
    cancelAlarm();

    Long tsLong = System.currentTimeMillis() + 60*1000; //1 minute After
    String timestamp = tsLong.toString();
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(Long.parseLong(timestamp));

    setAlarm(timestamp);
}

public void cancelAlarm() {
    PendingIntent pIntent = createPendingIntent();
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(pIntent);
    pIntent.cancel();

}

public PendingIntent createPendingIntent() {
    Intent intent = new Intent(this, AlarmActivity.class);

    return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

}

public void setAlarm(Calendar calendar, PendingIntent pIntent) {
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pIntent);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pIntent);
    }
}

然后,AlarmActivity将每分钟创建一次。