Why BroadcastReceiver works even when app is in background ?

后端 未结 9 927
感动是毒
感动是毒 2020-12-04 13:59

I am checking Internet connectivity in my app using BroadcastReceiver and I show an alert dialog if the connection is lost. It works fine. But my problem is that BroadcastRe

9条回答
  •  没有蜡笔的小新
    2020-12-04 14:11

    That is the way broadcast receivers work in Android. If you register for a broadcast in the manifest and your app is not running, Android will start a new process to handle the broadcast. It is generally a bad idea to directly show a UI from a broadcast receiver, because this may interrupt other apps. I'm also not convinced that a universal 'connection lost' dialog is a good idea either. This should probably be handled by each activity that uses network access.

    As for the original question, you need to disable your receiver when your activity goes in the background (onPause(), etc.) and enable it when you come to the foreground (onResume(), etc). Put enabled=false in your manifest and then use something like this in your code to toggle it as necessary:

       public static void toggle(Context context, boolean enable) {
            int flag = enable ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                    : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
            ComponentName receiver = new ComponentName(context,
                    ConnectivityMonitor.class);
    
            context.getPackageManager().setComponentEnabledSetting(receiver, flag,
                    PackageManager.DONT_KILL_APP);
       }
    

提交回复
热议问题