Android的AlarmManager - 从另一个活动取消 [英] Android AlarmManager - Cancel from another Activity

查看:109
本文介绍了Android的AlarmManager - 从另一个活动取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想创建一个报警器,提醒作业的用户的前一天晚上/在一定时间作业Planner应用程序。我有称为AddNewHomework一个活动是其中用户创建一个新的家庭作业项,并将其添加到数据库中。这code,然后调用。

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

这将创建这是引发在10秒内一个新的警报,并创建一个通知。

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

我的问题是,我还有一个活动叫做HomeworkList其中包含一个ListView并显示所有存储在数据库中的家庭作业的。如果用户长时间点击一个,那么他们必须将其删除的选项,但是从数据库中删除它不会删除报警。

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.

我已经看过了code,我可以用它来去除,但是我没有发现任何的报警,让我懂得如何从这种不同的活动取消报警。我知道我需要做PendingIntent的相同,但如何做到这一点,因为我无法从其他类访问上下文。 (我不认为)。

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

感谢

汤姆

推荐答案

如果有帮助,你可以从另一个活动访问您的背景下,通过静态吸气当前上下文。在你的上面级,只是做一个私有字段:

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

然后,只需在onCreate方法中添加:

Then, simply add in the onCreate method a:

MyActivity.context = getApplicationContext();

这是另一项活动访问上下文现在pretty的方便。您可以使用从MyActivity检索的情况下取消报警。

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

这篇关于Android的AlarmManager - 从另一个活动取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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