Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

broadcastreceiver - cannot cancel the current alarm in Android

I am new to Android. Here, I am not getting any errors ,While debugging the stopAlarm() method debugger crossed all the lines but the AlarmReceiver is not get called .

can anyone help me to fix it .

Update :

AlarmActivity.java

public void stopAlarm(Context context) {
        Intent intent = new Intent(context,AlarmReceiver.class);
        intent.setAction("ALARM_OFF");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, mAlarmId, intent,0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is here, in WakeUpScreen:

alarmActivity.stopAlarm();

You are calling the stopAlarm() method of the AlarmActivity() and in this case, AlarmActivity.this is null. I can only assume that you are doing somethng like this in WakeUpScreen:

alarmActivity = new AlarmActivity();

This is an absolute no-no! You cannot instantiate Android components (Activity, Service, BroadcastReceiver, Provider) using the keyword new. Only Android can create and initialize these components, because these components need to have their Context setup by the framework before they can be used.

If you want to call a method in another Activity, then you need to ensure that that method is static. If you declare your stopAlarm() method as static, you will find that it complains about a few things (like AlarmActivity.this) which is why you will need to rewrite the method to take a Context parameter, something like this:

public void stopAlarm(Context context) {
    Intent intent = new Intent(context, AlarmReceiver.class);
    PendingIntent alarmIntent = PendingIntent.getBroadcast(context, mAlarmId, intent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(this.ALARM_SERVICE);
    alarmManager.cancel(alarmIntent);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...