Android AlarmManager - Cancel from another Activity

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 16:26:34

问题


I have a Homework Planner application which I want to create an Alarm for to remind users of the homework the night before/at a certain time. I have an Activity called AddNewHomework which is where the user creates a new homework item and it is added to the database. This code is then called.

Intent i = new Intent(this, AlarmNotificationReceiver.class);
i.putExtra("title", title);
PendingIntent pi = PendingIntent.getBroadcast(this.getApplicationContext(), (int) id, i, 0);
AlarmManager mAlarm = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
mAlarm.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 10 * 1000, pi);

This creates a new Alarm which is triggered in 10 seconds and creates a notification.

My problem is that I have another activity called HomeworkList which contains a ListView and displays all of the homeworks stored in the database. If a user long clicks on one then they have the option to delete it, however removing it from the database will not remove the alarm.

I have looked for code I can use to remove the alarm however I have not found anything that allows me to understand how to cancel the alarm from this different activity. I know that I need to make the PendingIntent's the same, but how do I do this as I cannot access the context from the other class. (I don't think).


回答1:


If it helps, you could access your context from another activity, by making a static getter for the current context. In your above class, just make a private field:

private static Context context;

public static Context getAppContext(){
    return MyActivity.context;
}

Then, simply add in the onCreate method a:

MyActivity.context = getApplicationContext();

Accessing the context from another activity is now pretty easy. You can use the context retrieved from "MyActivity" to cancel your alarm.




回答2:


According to this Android: Does context affect filterEquals(), used to cancel alarm? it doesn't matter if you use different contexts, this doesn't affect the recognition of the PendingIntent as matching. I have confirmed this in my own app, I set an alarm from one activity using the activity as the context, and cancelled it from a different activity using that activity's context, and it was successfully cancelled (the action wasn't triggered).



来源:https://stackoverflow.com/questions/10055462/android-alarmmanager-cancel-from-another-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!