Broadcastreceiver to detect network is connected

前端 未结 6 1736
情书的邮戳
情书的邮戳 2020-12-05 02:36

I\'m trying to get the moment where user connects to a network, then I thought a BroadcastReceiver is a good approach... The thing that I would like to do is, w

6条回答
  •  既然无缘
    2020-12-05 03:26

    public abstract class NetworkReceiver extends BroadcastReceiver {
    
    @Override
    public void onReceive(Context context, Intent intent) {
        if (null != intent) {
            State wifiState = null;  
            State mobileState = null;  
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
            wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();  
            mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();  
            if (wifiState != null && mobileState != null  
                    && State.CONNECTED != wifiState  
                    && State.CONNECTED == mobileState) {  
                // phone network connect success
                gNetwork();
            } else if (wifiState != null && mobileState != null  
                    && State.CONNECTED != wifiState  
                    && State.CONNECTED != mobileState) {  
                // no network
                noNetwork();
            } else if (wifiState != null && State.CONNECTED == wifiState) {  
                // wift connect success
                WIFINetwork();
            }
        }
    }
    

    }

    manifest set

     
            
                
            
        
    

提交回复
热议问题