Android 网路状态动态监听

  • 添加权限
  //网络状态
    
    //网络变更
    
    
    
  • 书写监听广播
public class NetStateReceiver  extends BroadcastReceiver {

    private NetType netType; //网络类型

    private NetChangeListenner listenner;

    public NetStateReceiver(){
        //初始化网络
        netType=NetType.NONE;
    }

    public  void setListenner(NetChangeListenner listenner){
        this.listenner=listenner;
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        if(intent ==null ||intent.getAction() ==null){
            return;
        }
        //处理广播事件
        if(intent.getAction().equalsIgnoreCase(Constants.ANDROID_NET_CHANGE_ACTION)){

            Log.e("net","网络发生改变了");
            netType= NetworkUtils.getNetType();
            if(NetworkUtils.isNetworkAvailable()){
                Log.e("net","网络连接成功");
                if(listenner!=null){
                    listenner.onConnect(netType);
                }
            }else {
                Log.e("net","没有网络连接");
                listenner.onDisConnect();
            }
        }
    }
}
  • 清单文件配置

            
                
            
        
  • 网络变化后的回调
public interface NetChangeListenner {

    void  onConnect(NetType type);

    void onDisConnect();
}
  • 网络判断的工具类
package com.example.library.util;

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

import com.example.library.NetworkManager;
import com.example.library.type.NetType;

/**
 * Created by Amn on 2019/4/4.
 */

public class NetworkUtils {


    /**
     * 判断网络是否可用
     * @return
     */
    public static boolean isNetworkAvailable (){

        ConnectivityManager connectivity = (ConnectivityManager) NetworkManager.getDefault().getApplication()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected())
            {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED)
                {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;

    }

    /**
     * 获取当前网络类型
     * @param
     * @return
     */
    public static NetType getNetType(){

        ConnectivityManager mConnectivityManager = (ConnectivityManager) NetworkManager.getDefault().getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
        if(mConnectivityManager==null) return NetType.NONE;
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if(mNetworkInfo ==null){
            return NetType.NONE;
        }
        int netType =mNetworkInfo.getType();

        if(netType==ConnectivityManager.TYPE_MOBILE){
            if(mNetworkInfo.getExtraInfo().toLowerCase().equals("cmnet")){
                return NetType.CMNET;
            }else {
                return NetType.CMWAP;
            }
        }else if(netType==ConnectivityManager.TYPE_WIFI){
            return NetType.WIFI;
        }
        return NetType.NONE;
    }

}

  • 网络状态枚举类
/**
 * Created by Amn on 2019/4/4.
 */

public enum  NetType {
    //只要由有网络不关心wifi 还是gprs
    AUTO,
    //wifi
    WIFI,
    //手机上网
    CMWAP,
    //主要是pc笔记本/pad 上网
    CMNET,

    //没有网络
    NONE

}
  • 常量类
/**
 * Created by Amn on 2019/4/4.
 */

public class Constants {
    
    public static final String ANDROID_NET_CHANGE_ACTION="android.net.conn.CONNECTIVITY_CHANGE";


    public static final int SETTING_REQUEST_CODE=8888;
}
  • 管理类 方便外部直接调用

package com.example.library;

import android.app.Application;
import android.content.Context;
import android.content.IntentFilter;

import com.example.library.listenner.NetChangeListenner;
import com.example.library.util.Constants;

/**
 * Created by Amn on 2019/4/4.
 */

public class NetworkManager {

    private static  volatile NetworkManager instance;

    private Application application;

    private NetStateReceiver receiver;


    public void setListenner(NetChangeListenner listenner){
        receiver.setListenner(listenner);

    }
    private NetworkManager(){
        receiver =new NetStateReceiver();
    }

    public static NetworkManager getDefault(){
        if(instance==null){
            synchronized (NetworkManager.class){
                if (instance==null){
                    instance=new NetworkManager();
                }
            }
        }
        return instance;
    }


    public void init (Application application){
        if(application ==null) return;
       this.application=application;
        //动态广播注册
        IntentFilter  filter=new IntentFilter();
        filter.addAction(Constants.ANDROID_NET_CHANGE_ACTION);
        application.registerReceiver(receiver,filter);
    }

    public Application getApplication(){
        if(application==null){
            throw new RuntimeException("xxxxx init");
        }
        return application;
    }
}

到此网络状态的监听的库就写好了 。使用如下:


package com.example.amn.amnnetwork;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.example.library.NetworkManager;
import com.example.library.annotation.Network;
import com.example.library.listenner.NetChangeListenner;
import com.example.library.type.NetType;

public class MainActivity extends AppCompatActivity implements NetChangeListenner {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        NetworkManager.getDefault().init(getApplication());
        NetworkManager.getDefault().setListenner(this);
    }

    

    @Override
    public void onConnect(NetType type) {
        Log.e("net",type.name());
    }

    @Override
    public void onDisConnect() {
        Log.e("net","没有网络");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

你可能感兴趣的:(Android 网路状态动态监听)