无法在Android中取消当前警报 [英] cannot cancel the current alarm in Android

查看:78
本文介绍了无法在Android中取消当前警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android新手.在这里,我没有收到任何错误,虽然调试stopAlarm()方法调试器的过程跨越了所有行,但是没有调用AlarmReceiver.

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 .

谁能帮我修复它.

更新:

AlarmActivity.java

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);
    }

推荐答案

问题在这里,在WakeUpScreen中:

alarmActivity.stopAlarm();

您正在调用AlarmActivity()stopAlarm()方法,在这种情况下,AlarmActivity.thisnull.我只能假设您正在WakeUpScreen中进行这样的操作:

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();

这是绝对禁止!不能使用关键字实例化Android组件(ActivityServiceBroadcastReceiverProvider) new.只有Android才能创建和初始化这些组件,因为在使用这些组件之前,必须先由框架对其进行Context设置.

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.

如果要在另一个Activity中调用一个方法,则需要确保该方法为static.如果将stopAlarm()方法声明为static,您会发现它抱怨一些事情(例如AlarmActivity.this),这就是为什么您需要重写该方法以采用Context参数的原因,就像这样:

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);
}

这篇关于无法在Android中取消当前警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆