zoukankan      html  css  js  c++  java
  • 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;
  • 相关阅读:
    PA
    核电站问题(codevs 2618)
    [转]SQL SERVER 的排序规则
    C# 窗体控件输入框大写
    查看哪些端口被使用
    [转]Windows服务“允许服务与桌面交互”的使用和修改方法
    [转]OBJECT_ID 有哪些种类
    如何:对 Windows 窗体控件进行线程安全调用
    老人手机不要买山寨机
    VBA文本型数字变成数值
  • 原文地址:https://www.cnblogs.com/arnoid/p/3185571.html
Copyright © 2011-2022 走看看