Android AlarmManager - Cancel from another Activit

2019-04-17 08:49发布

问题:

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).