android开发:网络实时监听,适配android7.0

android实时监测到网络有俩种方式

一、利用系统广播监听网络状态

1.添加网络权限:

  
    
    

2.自定义广播接收器:

/**
 * Created by Carson_Ho on 16/10/31.
 */
public class NetWorkStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        System.out.println("网络状态发生变化");
        //检测API是不是小于23,因为到了API23之后getNetworkInfo(int networkType)方法被弃用
        if (android.os.Build.VERSION.SDK_INT < 23) {
            //获得ConnectivityManager对象
            ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            //获取ConnectivityManager对象对应的NetworkInfo对象
            //获取WIFI连接的信息
            NetworkInfo wifiNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            //获取移动数据连接的信息
            NetworkInfo dataNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (wifiNetworkInfo.isConnected() && dataNetworkInfo.isConnected()) {
                Toast.makeText(context, "WIFI已连接,移动数据已连接", Toast.LENGTH_SHORT).show();
            } else if (wifiNetworkInfo.isConnected() && !dataNetworkInfo.isConnected()) {
                Toast.makeText(context, "WIFI已连接,移动数据已断开", Toast.LENGTH_SHORT).show();
            } else if (!wifiNetworkInfo.isConnected() && dataNetworkInfo.isConnected()) {
                Toast.makeText(context, "WIFI已断开,移动数据已连接", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "WIFI已断开,移动数据已断开", Toast.LENGTH_SHORT).show();
            }
        } else {
            System.out.println("API level 大于23");
            //获得ConnectivityManager对象
            ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            try {
                //获取所有网络连接的信息
                NetworkInfo[] networks = connMgr.getAllNetworkInfo();
                //用于存放网络连接信息
                StringBuilder sb = new StringBuilder();
                HashMap netStatus = new HashMap();
                //通过循环将网络信息逐个取出来
                for (int i = 0; i < networks.length; i++) {
                    //获取ConnectivityManager对象对应的NetworkInfo对象
                    NetworkInfo networkInfo = networks[i];
                    int type = networkInfo.getType();
                    switch (type) {
                        case ConnectivityManager.TYPE_MOBILE:
                            if (networkInfo.isConnected()) {
                                netStatus.put("MOBILE", true);
                            }
                        case ConnectivityManager.TYPE_WIFI:
                            if (networkInfo.isConnected()) {
                                netStatus.put("WIFI", true);
                            }
                    }

                }

                System.out.println(netStatus.toString());

            } catch (Exception e) {

            }
        }
    }
}

3.注册我们的广播:

 NetWorkStateReceiver stateReceiver = new NetWorkStateReceiver();
            intentFilter = new IntentFilter();
            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(stateReceiver, intentFilter);

二、安卓5.0后可以采用NetworkCallback方式进行监听

1.实现ConnectivityManager.NetworkCallback

/**
 * @Author: david.lvfujiang
 * @Date: 2019/11/5
 * @Describe:
 */

@SuppressLint("NewApi")
public class NetworkCallbackImpl extends ConnectivityManager.NetworkCallback {
    @Override
    public void onAvailable(Network network) {
        super.onAvailable(network);
        Log.d("TAG", "onAvailable: 网络已连接");
    }

    @Override
    public void onLost(Network network) {
        super.onLost(network);
        Log.e("TAG", "onLost: 网络已断开");
    }

    @Override
    public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
        super.onCapabilitiesChanged(network, networkCapabilities);
        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                Log.d("TAG", "onCapabilitiesChanged: 网络类型为wifi");
            } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                Log.d("TAG", "onCapabilitiesChanged: 流量网络");

            } else {
                Log.d("TAG", "onCapabilitiesChanged: 其他网络");

            }
        }
    }
}

2.注册NetworkCallback

  NetworkCallbackImpl networkCallback = new NetworkCallbackImpl();
            ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connMgr != null) {

                //安卓系统大于5.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    connMgr.requestNetwork(new NetworkRequest.Builder().build(), networkCallback);
                    // 安卓系统大于7.0  connMgr.registerDefaultNetworkCallback(networkCallback);
                }ontext.CONNECTIVITY_SERVICE);

最后为了适配所有api,我们可以将俩种方式综合使用:

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            NetworkCallbackImpl networkCallback = new NetworkCallbackImpl();
            ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connMgr != null) {

                //安卓系统大于5.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    connMgr.requestNetwork(new NetworkRequest.Builder().build(), networkCallback);
                    // 安卓系统大于7.0  connMgr.registerDefaultNetworkCallback(networkCallback);
                }
            }

        } else {
            //api小于23使用广播监听的方式
            NetWorkStateReceiver stateReceiver = new NetWorkStateReceiver();
            intentFilter = new IntentFilter();
            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(stateReceiver, intentFilter);
        }

 

你可能感兴趣的:(android开发基础)