简体   繁体   English

如何正确停止Android Alarmmanager

[英]How to properly stop an android Alarmmanager

I have an alarm manager that triggers at regular interval. 我有一个定期触发的警报管理器。 A button in activity_main triggers it. activity_main中的按钮将触发它。

It works fine. 工作正常。 Without any problem. 没问题。 Alarm manager is defined in Main class. 警报管理器在Main类中定义。 A method (activated on button click) invokes the alarm manager. 一种方法(单击按钮时激活)将调用警报管理器。 Another method should stop it or cancel it. 另一种方法应该停止它或取消它。

Code: 码:

     public class MainActivity extends Activity {
    private PendingIntent pi;
       private AlarmManager alarmManager;

    .......................................
    ......................

    public void activate(View view) {
    //this activates the alarm manager.

    alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pi.getBroadcast(this, 1, i, pi.FLAG_UPDATE_CURRENT));
    }

    public void deactivate(View view) {
//this should Deactivate the alarm manager.

    alarmManager.cancel(pi);

    }

    }

However, the second method is not working. 但是,第二种方法不起作用。 (deactivate). (停用)。

When the 2nd button is clicked, the App will crash!! 单击第二个按钮时,应用程序将崩溃!

Log cat gives the reason as : 日志猫给出的原因如下:

Caused by: java.lang.NullPointerException.

Any idea on how to fix this? 关于如何解决此问题的任何想法? Should I create an intent again in second method? 我应该在第二种方法中再次创建意图吗? I tried it but no use.. Any suggestions or fixes for this?? 我试过了,但是没有用。

For anyone who has similar issue... 对于有类似问题的任何人...

The AlarmManager has to be initialized again in the method that your use to deactivate it. 必须使用您用来停用它的方法再次初始化AlarmManager。 Need to Create a Pending intent as well. 还需要创建一个待处理的意图。

Also, make sure that you create the same pending intent(name and attributes) that you used to activate or set repeating alarm. 另外,请确保创建用于激活或设置重复警报的相同挂起意图(名称和属性)。 Then, cancel it. 然后,取消它。 All credits to @joey chong 全部积分@joey chong

Hope it helps.. 希望能帮助到你..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM