• Android网络连接监听


    接收系统网络服务的广播接收者

    public class NetStateReceiver extends BroadcastReceiver {
        private Handler handler;
    
        public NetStateReceiver(Handler handler) {
            this.handler = handler;
        }
    
        @Override
        public void onReceive(Context context, Intent arg1) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (!gprs.isConnected() && !wifi.isConnected()) {
                System.out.println("网络已断开");
                SysUtils.sendHandlerMsg(handler, SysConstant.MSG_NET_CONN_DISS);
            }
    
            if (gprs.isConnected() || wifi.isConnected()) {
                System.out.println("网络已连接");
                SysUtils.sendHandlerMsg(handler, SysConstant.MSG_NET_CONN_CONN);
            }
        }
    
    }

    对接收到的广播进行处理

    public class MyActivity extends Activity {
        /** 网络连接状态 true:连接;false:断开 */
        public boolean netState = false;
    
        private NetStateReceiver receiver;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            int device = GpdService.DEVICE_TYPE_SCANNER;// 一维或二维条码扫描头
            MyGpdUtils.startGpdService(this, device);
    
            // 注册广播接收者
            receiver = new NetStateReceiver(handler);
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(receiver, filter);
            receiver.onReceive(this, null);
        }
    
        Handler handler = new Handler() {
            public void handleMessage(android.os.Message msg) {
                switch (msg.what) {
                case SysConstant.MSG_NET_CONN_DISS:// 网络断开
                    MyGpdUtils.playSound("网络连接已断开");
                    netState = false;
                    break;
                case SysConstant.MSG_NET_CONN_CONN:// 网络连接
                    // MyGpdUtils.playSound("网络已连接");
                    netState = true;
                    break;
                }
            };
        };
    
    }

     自定义的消息常量

                    /** 网络连接消息 */
        public static final int MSG_NET_CONN_DISS = 222;
        public static final int MSG_NET_CONN_CONN = 223;
  • 相关阅读:
    特性(Attribute)
    泛型
    AngularJS 基础用法
    js date相关学习!
    android 数据存储分配的一些事
    angularjs model.service vs provider vs factory?
    angularJS 判断
    zepto.js 学习之(一)
    angularJS Directive学习
    AngularJS继续中
  • 原文地址:https://www.cnblogs.com/arnoid/p/3185571.html
Copyright © 2020-2023  润新知