在主要活动警报开始 这是代码 private PendingIntent pendingIntent; 私人AlarmManager经理;
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 10000; // 10 seconds
manager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
如何取消AlarmReceiver.class中的警报
public class AlarmReceiver extends BroadcastReceiver {
static DatabaseHandler dbHandler;
private PendingIntent pendingIntent;
private AlarmManager manager;
public void onReceive(Context context, Intent intent) {
// SHOW NOTIFICATION
Log.e("DAYDAY", "" + "pasok");
int days = 1;
Toast.makeText(context, "DAYDAY", 10).show();
if (days == 5) {
dbHandler.deleteUser();
manager.cancel(pendingIntent);
Toast.makeText(context, "Canceled", 10).show();
}else{
int = days + 1;
dbHandler.update_days(i, emp_id, birthday);
}
}
}
如果天数等于5,那么我将取消闹钟。 但错误是管理器是空指针。
答案 0 :(得分:0)
每次使用经理时,都需要手动调用:
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
答案 1 :(得分:0)
你必须使用
再次获得它manager =(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
答案 2 :(得分:0)
您收到空指针,因为pendingIntent
和'alarm manager'
未在您的代码中的任何位置初始化。
要取消闹钟,请尝试以下代码 -
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
// get pending intent by unique tag value assigned previously
int tag = 0;
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, tag, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();