Android 如何从活动中获取服务上下文?

Android 如何从活动中获取服务上下文?,android,android-activity,service,android-context,Android,Android Activity,Service,Android Context,我需要从活动中获取服务上下文,因为我正在服务中创建报警,并且我想在活动中删除它,因此必须使用相同的上下文。我可以将此服务的上下文保存在SharedReferences中作为字符串,但如何将此字符串转换为上下文 我的报警代码是: Intent intentAlarm = new Intent(getApplicationContext(), TimeAlarm.class); //add the notification body to the in

我需要从活动中获取服务上下文,因为我正在服务中创建报警,并且我想在活动中删除它,因此必须使用相同的上下文。我可以将此服务的上下文保存在
SharedReferences
中作为字符串,但如何将此字符串转换为上下文

我的报警代码是:

 Intent intentAlarm = new Intent(getApplicationContext(), TimeAlarm.class);            
           //add the notification body to the intent:
           intentAlarm.putExtra("Notif_body", Notif_Body);             
           // create the object
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
           //set the alarm for particular time
           alarmManager.set(AlarmManager.RTC_WAKEUP,new GregorianCalendar().getTimeInMillis()+60*1000, PendingIntent.getBroadcast(getApplicationContext(),1,intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
我如何删除它

 AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            Intent i = new Intent(getApplicationContext(),TimeAlarm.class);
            PendingIntent displayIntent = PendingIntent.getBroadcast(getApplicationContext(),1,i, PendingIntent.FLAG_UPDATE_CURRENT);               
            alarmManager.cancel(displayIntent);
为什么不起作用

嗨,我需要从活动中获取服务上下文

不,你没有

所以必须使用相同的上下文

不,你没有

我可以将此服务的上下文保存在SharedReferences中作为字符串吗

不,你不能

我认为需要同样的背景

不,你没有

使用其他上下文时,无法删除警报


那么你的代码还有其他问题。您可以使用完全不同的流程取消报警,更不用说使用不同的
上下文了

您不必使用相同的上下文。只要使用“活动”上下文,一切都会正常工作。或者,在两种情况下都使用应用程序上下文。确定将在两种情况下都使用应用程序上下文,因为我认为需要相同的上下文,因为我无法删除报警,当我使用另一个上下文时,我将尝试这样做。我想您正在寻找
getApplicationContext()
很抱歉,您的评论太有用了,但无法对其进行标记。请检查我添加的代码,我不知道为什么它不起作用。@user2849412:尝试删除您在
取消()
中使用的
挂起内容的
FLAG\u UPDATE\u CURRENT
。除此之外,还可以使用adb shell dumpsys alarm
查看您是否计划了另一个警报,可能是您应用程序之前运行的某个警报。您可以通过卸载并重新安装应用程序,或通过“设置”中的“强制停止”来清除警报。@user2849412:您有两个名为
TimeAlarm
的类吗?不确定,我甚至添加了intentAlarm.putExtra(“Notif_body”,”);因为我认为这是原因,但仍然无法删除它。。