Android N not sending android.net.conn.CONNECTIVITY_CHANGE broadcast?

前端 未结 3 1116
南笙
南笙 2020-12-15 06:35

I have defined a receiver in a sandbox Android N application:



        
相关标签:
3条回答
  • 2020-12-15 06:39

    Use this code to register receiver in your Activity or in Application class

    IntentFilter intentFilter = new IntentFilter(); 
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTI‌​ON); 
    registerReceiver(new NetworkConnectionReceiver(), intentFilter); 
    

    Where NetworkConnectionReceiver is a class extended by BroadcastReceiver. Just add this class in your app and perform action in onReceive(Context context, Intent intent) method.

    Note: If you register this receiver in an Activity, don't forget to unregister it.

    0 讨论(0)
  • 2020-12-15 06:52

    Apps targeting Android N (Nougat) do not receive CONNECTIVITY_ACTION broadcasts, even if they have manifest entries to request notification of these events. Apps that are running can still listen for CONNECTIVITY_CHANGE on their main thread if they request notification with a BroadcastReceiver.

    To see what changed in Android N (Nougat). Please refer below link. Android N Behaviour Changes

    0 讨论(0)
  • 2020-12-15 07:04

    Meanwhile ConnectivityManager.CONNECTIVITY_ACTI‌​ON was deprecated:

    @deprecated 
    apps should use the more versatile {@link #requestNetwork},
    {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
    functions instead for faster and more detailed updates about the network
    changes they care about.
    

    So registerDefaultNetworkCallback should be used:

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    cm.registerDefaultNetworkCallback(new ConnectivityManager.NetworkCallback(){
        @Override
        public void onAvailable(Network network) {
            doOnNetworkConnected();
        }
    });
    
    0 讨论(0)
提交回复
热议问题