设置的BroadcastReceiver是不活跃活跃、BroadcastReceiver

2023-09-04 13:28:49 作者:呆橘

我有一个BroadcastReceiver设立在我接收的短信接收事件的Andr​​oid应用程序。这工作得很好,但我希望能够切换短信接收和关闭通过切换BroadcastReceiver的开启和关闭。因为如果我有方法的onReceive里面一个简单的布尔,即使短信接收关闭,我的应用程序将启动。

I have a BroadcastReceiver set up in my Android application that receives SMS receive events. This works fine, but I want to be able to toggle SMS receiving on and off by toggling the BroadcastReceiver on and off. Because if I have a simple boolean inside the onReceive method, even if the SMS receiving is off, my application will start.

这是可能的吗?

干杯!

推荐答案

您可以使用 PackageManager#setComponentEnabledSetting 启用/在你的清单文件中禁用的组件。您创建一个组件名与你的包的名字和你的广播接收器的类名。然后使用 COMPONENT_ENABLED_STATE_DISABLED 标记来禁用它。并根据如果你想整个应用程序上对象死亡或无法使用 DONT_KILL_APP 标记或0。虽然文档警告不要杀得了应用程序

You can use PackageManager#setComponentEnabledSetting to enable/disable a component in your manifest file. You create a ComponentName with your package name and class name of your broadcast receiver. Then use the COMPONENT_ENABLED_STATE_DISABLED flag to disable it. And depending on if you want the entire Application object to die or not use the DONT_KILL_APP flag or 0. Though the documentation warns against not killing the Application.