我的注册网络广播接收器有问题。由于没有人在这个应用程序中使用Android 7.0,所以没关系,因为我在清单中声明了这个广播。现在,我必须在点击保存按钮后在我的配置活动中注册广播接收器。但当有人点击这个按钮几次时,他就注册了很多网络服务。问题是,当应用程序未打开时,当互联网出现时,服务必须在后台工作并拦截情况。
networkService = new NetworkService();
if (!isReceiverRegistered(networkService)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
getActivity().registerReceiver(networkService, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
receivers.add(networkService);
}
}
现在,我已经在Manifest中安装了这个广播接收器,并且在点击“保存”按钮后我已经激活了它。
<receiver android:name=".services.NetworkService"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="999">
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.REBOOT"/>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
答案 0 :(得分:0)
您可以使用以下代码示例在清单中默认关闭广播: -
<receiver android:name="name_of_your_receiver" android:enabled="false">
</receiver>
然后在按钮上单击执行以下代码以启用接收器: -
PackageManager pm = context.getPackageManager();
ComponentName componentName = new ComponentName(context, name_of_your_receiver.class);
pm.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);