问题描述
我正在使用关于如何接收SMS消息的本教程:
该代码可以完美运行,并且完全符合我的要求.
The code works perfectly, and does exactly what I want.
我有1个问题.
我希望我的应用程序在后台运行,但是当它关闭时,我希望它停止拦截SMS消息.
I want my app to run in the background, but when it's closed I want it to stop intercepting SMS messages.
我的问题是,为什么我的应用在关闭后为什么仍在拦截SMS消息?
My question is, why is my app still intercepting SMS messages after it's been closed?
我想我必须找到一个关闭"处理程序,然后关闭广播接收器. (如果有关闭"事件处理程序..?).
I guess I have to find a "on close" handler and close the Broadcast Receiver then. (If there is a "on close" event handler..?).
如果有人能提供一些见解,我将不胜感激.谢谢!
If anyone can provide some insight I would be very grateful. Thanks!
推荐答案
通过将BroadcastReceiver
放入清单中,默认情况下它始终处于活动状态.因此,如果您希望它仅在显示Activity
时运行,那么您将希望在Activity
恢复/暂停时启用/禁用BroadcastReceiver
:
By putting your BroadcastReceiver
in your Manifest, it, by default, is always active. Therefore if you want it to only run while your Activity
is shown, you'll want to enable/disable your BroadcastReceiver
when your Activity
resumes/pauses:
public void onResume()
{
ComponentName component=new ComponentName(this, TextMessageReceiver.class);
getPackageManager()
.setComponentEnabledSetting(component,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
public void onPause()
{
ComponentName component=new ComponentName(this, TextMessageReceiver.class);
getPackageManager()
.setComponentEnabledSetting(component,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
另一种方法是在Activity
中声明您的BroadcastReceiver
,然后在相同的生命周期事件中调用registerReceiver
和unregisterReceiver
.
The alternative, is to declare your BroadcastReceiver
in your Activity
and then call registerReceiver
and unregisterReceiver
in the same lifecycle events.
这篇关于应用关闭后,广播接收器仍在运行-Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!