android 全局网络监听

平常我们在android的页面要检测是否有网络,并且还要根据不同的网络来处理相关事务
1.开启系统广播监听

package com.dejun.commonsdk.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.dejun.commonsdk.observer.NetChangeObserver;
import com.dejun.commonsdk.util.NetUtils;

import java.util.ArrayList;

/**
 * Author:DoctorWei
 * Time:2018/12/15 9:43
 * Description:
 * email:[email protected]
 */

public class NetStateReceiver extends BroadcastReceiver {
    public final static String CUSTOM_ANDROID_NET_CHANGE_ACTION = "com.zhanyun.api.netstatus.CONNECTIVITY_CHANGE";
    private final static String ANDROID_NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
    private static boolean isNetAvailable = false;
    private static NetUtils.NetType mNetType;
    private static ArrayList mNetChangeObservers = new ArrayList<>();
    private static BroadcastReceiver mBroadcastReceiver;

    @Override
    public void onReceive(Context context, Intent intent) {
        mBroadcastReceiver = NetStateReceiver.this;
        if (intent.getAction().equalsIgnoreCase(ANDROID_NET_CHANGE_ACTION) || intent.getAction().equalsIgnoreCase(CUSTOM_ANDROID_NET_CHANGE_ACTION)) {
            if (!NetUtils.isNetworkAvailable(context)) {
                isNetAvailable = false;
            } else {
                isNetAvailable = true;
                mNetType = NetUtils.getAPNType(context);
            }
            notifyObserver();
        }
    }

    private void notifyObserver() {
        if (!mNetChangeObservers.isEmpty()) {
            int size = mNetChangeObservers.size();
            for (int i = 0; i < size; i++) {
                NetChangeObserver observer = mNetChangeObservers.get(i);
                if (observer != null) {
                    if (isNetworkAvailable()) {
                        observer.onNetConnected(mNetType);
                    } else {
                        observer.onNetDisConnect();
                    }
                }
            }
        }
    }

    public static boolean isNetworkAvailable() {
        return isNetAvailable;
    }

    /**
     * 注册广播
     *
     * @return
     */
    public static void registerNetworkStateReceiver(Context mContext) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(CUSTOM_ANDROID_NET_CHANGE_ACTION);
        filter.addAction(ANDROID_NET_CHANGE_ACTION);
        mContext.getApplicationContext().registerReceiver(getReceiver(), filter);
    }

    /**
     * 销毁广播
     *
     * @return
     */
    public static void unRegisterStateReceiver(Context context) {
        if (mBroadcastReceiver != null) {
            context.getApplicationContext().unregisterReceiver(mBroadcastReceiver);
        }

    }

    private static BroadcastReceiver getReceiver() {
        if (mBroadcastReceiver == null) {
            synchronized (NetStateReceiver.class) {
                if (mBroadcastReceiver == null) {
                    mBroadcastReceiver = new NetStateReceiver();
                }
            }
        }
        return mBroadcastReceiver;
    }

    /**
     * 注册回调函数观察者
     */

    public static void registerObserver(NetChangeObserver observer) {
        if (mNetChangeObservers == null) {
            mNetChangeObservers = new ArrayList<>();
        }
        mNetChangeObservers.add(observer);
    }

    /**
     * 移除监听
     */
    public static void removeObserver(NetChangeObserver netChangeObserver) {
        if (mNetChangeObservers != null) {
            boolean contains = mNetChangeObservers.contains(netChangeObserver);
            if (contains) {
                mNetChangeObservers.remove(netChangeObserver);
            }
        }
    }
}
2.获取网络状态工具类

package com.dejun.commonsdk.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.util.Locale;

/**
 * Author:DoctorWei
 * Time:2018/12/14 14:03
 * Description:网络监听工具类负责实时监听网络
 * email:[email protected]
 */

public class NetUtils {
    public static enum NetType {
        WIFI, CMNET, CMWAP, NONE
    }

    /**
     * 判断是否已连接上了网络
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] allNetworkInfo = manager.getAllNetworkInfo();//获取设备支持的所有网络类型的链接状态信息。
        if (allNetworkInfo != null) {
            for (int i = 0; i < allNetworkInfo.length; i++) {
                if (allNetworkInfo[i].getState() == NetworkInfo.State.CONNECTED) {//已连接
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (networkInfo != null) {
                return networkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 判断是否是wifi环境
     *
     * @param context
     * @return
     */
    public static boolean isWifiConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfoWifi = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (networkInfoWifi != null) {
                return networkInfoWifi.isAvailable();
            }
        }
        return false;
    }

    /**
     * 判断是否是4g环境
     *
     * @param context
     * @return
     */
    public static boolean isMobileConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfoMobile = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (networkInfoMobile != null) {
                return networkInfoMobile.isAvailable();
            }
        }
        return false;
    }

    /**
     * 获取连接方式
     */
    public static int getConnectedType(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (activeNetworkInfo != null && activeNetworkInfo.isAvailable()) {
                return activeNetworkInfo.getType();
            }
        }
        return -1;
    }

    public static NetType getAPNType(Context context) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo == null) {
            return NetType.NONE;
        }
        int type = activeNetworkInfo.getType();
        if (type==ConnectivityManager.TYPE_MOBILE){
            if (activeNetworkInfo.getExtraInfo().toLowerCase(Locale.getDefault()).equals("cmnet")){
                return NetType.CMNET;
            }else{
                return NetType.CMWAP;
            }
        }else if (type==ConnectivityManager.TYPE_WIFI){
            return NetType.WIFI;
        }
        return NetType.NONE;

    }
}

3.分别在Apllication中注册广播和在baseAcitvity中监听广播的的触发
public class MyApllication extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        NetStateReceiver.registerNetworkStateReceiver(this);
    }

public abstract class BaseActivity extends SupportActivity implements BaseView{
    /**
     * 网络观察者
     * @param savedInstanceState
     */
    protected NetChangeObserver netChangeObserver;
    @Override
    public void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置全局的网络监听
        netChangeObserver=new NetChangeObserver() {
            @Override
            public void onNetConnected(NetUtils.NetType netType) {
                Logger.d("onNetConnected");
            }

            @Override
            public void onNetDisConnect() {
                Logger.d("onNetDisConnect");
            }
        };
        NetStateReceiver.registerObserver(netChangeObserver);
    
    }

   

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (netChangeObserver!=null) {
            NetStateReceiver.removeObserver(netChangeObserver);
        }
        Logger.d(TAG,"onDestroy");
        if (mPresenter!=null){
            mPresenter.dettachView();
        }
    }

}
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        NetStateReceiver.unRegisterStateReceiver(this);
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}

你可能感兴趣的:(android 全局网络监听)