Android 网络监听(适配7以上)

本小妞迷上赌 提交于 2019-12-17 20:15:00
 

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.os.Build;
import android.telephony.TelephonyManager; 

/**
 * @param
 * @Comments : 功能
 * @Author : Lampo
 * @CreateDate : 2019/10/30 14:28
 * @ModifiedBy : Lampo
 * @ModifiedDate : 2019/10/30 14:28
 * @Modified :
 */

public class CitNetWorkMonitorManager {
    private static CitNetWorkMonitorManager ourInstance;
    private Application application;
    private final String ANDROID_NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
    private ConnectivityManager connectivityManager;
    private MyBroadcastReceiver receiver;
    public static CitNetWorkMonitorManager getInstance() {
        synchronized (CitNetWorkMonitorManager.class) {
            if (ourInstance == null) {
                ourInstance = new CitNetWorkMonitorManager();
            }
        }
        return ourInstance;
    }
    /**
     * 初始化 传入application
     *
     * @param application
     */
    public void init(Application application) {
        if (application == null) {
            throw new NullPointerException("application can not be null");
        }
        this.application = application;
        connectivityManager = (ConnectivityManager) this.application.getSystemService(Context.CONNECTIVITY_SERVICE);
    }
    /**
     * 初始化网络监听 根据不同版本做不同的处理
     */
    public void register(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//API 大于21时
            NetworkRequest.Builder builder = new NetworkRequest.Builder();
            NetworkRequest request = builder.build();
            connectivityManager.registerNetworkCallback(request, networkCallback);

        } else {//低版本
            if (receiver == null) receiver = new MyBroadcastReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            this.application.registerReceiver(receiver, intentFilter);
        }
    }
    public void unregister(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//API 大于21时
            connectivityManager.unregisterNetworkCallback(networkCallback);
        } else {//低版本
            if (receiver != null) {
                this.application.unregisterReceiver(receiver);//注销广播
            }
        }
    }
    private ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback(){
        /**
         * 网络可用的回调连接成功
         */
        @Override
        public void onAvailable(Network network) {
            super.onAvailable(network);
            postNetState();
        }
        /**
         * 网络不可用时调用和onAvailable成对出现
         */
        @Override
        public void onLost(Network network) {
            super.onLost(network);
            postNetState();
        }
    };
    private class  MyBroadcastReceiver extends BroadcastReceiver  {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equalsIgnoreCase(ANDROID_NET_CHANGE_ACTION)) {
                postNetState();
            }
        }
    };
    private void postNetState(){
        //网络发生变化 没有网络-0:WIFI网络1:4G网络-4:3G网络-3:2G网络-2
        int netType = getAPNType(this.application);
        UtilsManager.isNetAvailable(this.application);
        PDALogger.e("onNetWorkStateChange receiver>>> :" +netType);
        if(netType != 0){
            //当网络打开,你要处理的事情
            this.application.sendBroadcast(new Intent(Config.REQURSTTIMELOG_UPLOADDATA));
            this.application.sendBroadcast(new Intent(Config.CHANGELINEUPLOADDATA));
        }
    }
    /**
     * 获取当前的网络状态 :没有网络-0:WIFI网络1:4G网络-4:3G网络-3:2G网络-2
     * 自定义
     *
     * @param context
     * @return
     */
    private int getAPNType(Context context) {
        //结果返回值
        int netType = 0;
        //获取手机所有连接管理对象
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context
                .CONNECTIVITY_SERVICE);
        //获取NetworkInfo对象
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        //NetworkInfo对象为空 则代表没有网络
        if (networkInfo == null) {
            return netType;
        }
        //否则 NetworkInfo对象不为空 则获取该networkInfo的类型
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_WIFI) {
            //WIFI
            netType = 1;
        } else if (nType == ConnectivityManager.TYPE_MOBILE) {
            int nSubType = networkInfo.getSubtype();
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService
                    (Context.TELEPHONY_SERVICE);
            //3G   联通的3G为UMTS或HSDPA 电信的3G为EVDO
            if (nSubType == TelephonyManager.NETWORK_TYPE_LTE
                    && !telephonyManager.isNetworkRoaming()) {
                netType = 4;
            } else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
                    || nSubType == TelephonyManager.NETWORK_TYPE_HSDPA
                    || nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0
                    && !telephonyManager.isNetworkRoaming()) {
                netType = 3;
                //2G 移动和联通的2G为GPRS或EGDE,电信的2G为CDMA
            } else if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS
                    || nSubType == TelephonyManager.NETWORK_TYPE_EDGE
                    || nSubType == TelephonyManager.NETWORK_TYPE_CDMA
                    && !telephonyManager.isNetworkRoaming()) {
                netType = 2;
            } else {
                netType = 2;
            }
        }
        return netType;
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!