美文网首页Android开发
Android 通过广播监听网络状态

Android 通过广播监听网络状态

作者: 皮皮铭 | 来源:发表于2019-11-13 13:50 被阅读0次

    首先定义一个接口作为回调

    public interface INetEvent {
        void onNetChange(int netWorkState);
    }
    

    网络工具类

    public class NetUtils {
        /**
         * 没有连接网络
         */
        public static final int NETWORK_NONE = -1;
        /**
         * 移动网络
         */
        public static final int NETWORK_MOBILE = 0;
        /**
         * 无线网络
         */
        public static final int NETWORK_WIFI = 1;
    
        /**
         * 得到当前网络的状态
         *
         * @param context
         * @return
         */
        public static int getNetWorkState(Context context) {
            // 得到连接管理器对象
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
    
            NetworkInfo activeNetworkInfo = connectivityManager
                    .getActiveNetworkInfo();
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
    
                if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
                    return NETWORK_WIFI;
                } else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
                    return NETWORK_MOBILE;
                }
            } else {
                return NETWORK_NONE;
            }
            return NETWORK_NONE;
        }
    }
    

    NetStateReceiver类,里面的判断主要是解决使用广播监听网络状态变化时接收到多个广播的问题

    public class NetStateReceiver extends BroadcastReceiver {
        private static final String TAG = "NetStateReceiver";
        private INetEvent mINetEvent = BaseActivity.mINetEvent;
    
        private static long WIFI_TIME = 0;
        private static long ETHERNET_TIME = 0;
        private static long NONE_TIME = 0;
    
        private static int LAST_TYPE = -3;
    
    
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG, "onReceive: " + intent.getAction());
            if (Objects.equals(intent.getAction(), ConnectivityManager.CONNECTIVITY_ACTION)) {
                long time = getTime();
                if (time != WIFI_TIME && time != ETHERNET_TIME && time != NONE_TIME) {
                    final int netWorkState = NetUtils.getNetWorkState(context);
                    if (netWorkState == 0 && LAST_TYPE != 0) {
                        WIFI_TIME = time;
                        LAST_TYPE = netWorkState;
                        if (mINetEvent != null) {
                            mINetEvent.onNetChange(NetUtils.getNetWorkState(context));
                        }
                    } else if (netWorkState == 1 && LAST_TYPE != 1) {
                        ETHERNET_TIME = time;
                        LAST_TYPE = netWorkState;
                        if (mINetEvent != null) {
                            mINetEvent.onNetChange(NetUtils.getNetWorkState(context));
                        }
                    } else if (netWorkState == -1 && LAST_TYPE != -1) {
                        NONE_TIME = time;
                        LAST_TYPE = netWorkState;
                        if (mINetEvent != null) {
                            mINetEvent.onNetChange(NetUtils.getNetWorkState(context));
                        }
                    }
                }
            }
        }
    
        public long getTime() {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
            String date = sDateFormat.format(new java.util.Date());
            return Long.valueOf(date);
        }
    
    }
    

    BaseActivity

    public abstract class BaseActivity extends AppCompatActivity implements INetEvent {
        public static INetEvent mINetEvent;
        private NetStateReceiver stateReceiver;
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mINetEvent = this;
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            stateReceiver = new NetStateReceiver();
            registerReceiver(stateReceiver,intentFilter);
    
        }
    
        public abstract void onNetChanged(int netWorkState);
        @Override
        public void onNetChange(int netWorkState){
            onNetChanged(netWorkState);
        }
    
        @Override
        protected void onDestroy() {
            unregisterReceiver(stateReceiver);
           super.onDestroy();
    
        }
    }
    

    MainActivity

    public class MainActivity extends BaseActivity {
        private static final String TAG = "MainActivity";
        private TextView tv;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        @Override
        public void onNetChanged(int netWorkState) {
            switch (netWorkState) {
                case NetUtils.NETWORK_NONE:
                    Toast.makeText(getApplicationContext(), "没有网络", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "onNetChanged:没有网络 ");
                    break;
                case NetUtils.NETWORK_MOBILE:
                    Toast.makeText(getApplicationContext(), "移动网络", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "onNetChanged:移动网络 ");
                    break;
                case NetUtils.NETWORK_WIFI:
                    Toast.makeText(getApplicationContext(), "WIFI网络", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "onNetChanged:WIFI网络 ");
                    break;
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:Android 通过广播监听网络状态

        本文链接:https://www.haomeiwen.com/subject/zdmhictx.html