广播监听USB和外设插拔状态

直入正题,看代码

         //USB插入监听 添加广播过滤意图
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.hardware.usb.action.USB_DEVICE_ATTACHED");
        filter.addAction("android.hardware.usb.action.USB_DEVICE_DETACHED");
        filter.addAction("android.hardware.usb.action.USB_STATE");
        registerReceiver(mUsbBroadcastReceiver, filter);
    //BOOLEAN为成员变量,自己随便起一个就行
    BroadcastReceiver mUsbBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //判断外设
            if (action.equals("android.hardware.usb.action.USB_DEVICE_ATTACHED")) {//外设已经连接
                mIvUsb.setVisibility(View.VISIBLE);
            }
            if (action.equals("android.hardware.usb.action.USB_DEVICE_DETACHED")) {
                if (BOOLEAN) {//外设已经移除  
                    mIvUsb.setVisibility(View.GONE);
                }
            }
            //判断存储usb
            if (action.equals("android.hardware.usb.action.USB_STATE")) {
                boolean connected = intent.getExtras().getBoolean("connected");
                if (connected) {//USB 已经连接
                    mIvUsb.setVisibility(View.VISIBLE);
                } else {
                    if (BOOLEAN) {//USB 断开
                        mIvUsb.setVisibility(View.GONE);
                    }

                }
            }
             //判断耳机  
            if (action.equals("android.intent.action.HEADSET_PLUG")) {  
                int intExtra = intent.getIntExtra("state", 0);  
                // state --- 0代表拔出,1代表插入  
                // name--- 字符串,代表headset的类型。  
                // microphone -- 1代表这个headset有麦克风,0则没有  
                // int i=intent.getIntExtra("",0);  
                if (intExtra == 0) {  
                    if (BOOLEAN) {  
                        //拔出耳机
                    }  
                }  
                if (intExtra == 1) {  
                    //耳机插入
                    int intType = intent.getIntExtra("microphone", 0);  
                    if (intType == 0) {  

                        //没有麦克风
                    }  
                    if (intType == 1) {  

                        //有话筒
                    }  
                }  

            }  
            BOOLEAN = true;
        }

    };

最后广播在ondestory里面unregister一下就行

第二个是发送广播到服务器

   private void setBroadCast(long restflow) {
        Intent intent = new Intent();
        intent.setAction("realtimeflow");
        intent.putExtra("restflow", restflow);
        sendBroadcastAsUser(intent, UserHandle.ALL);
        // UserHandle.ALL只有在源码情况下才能编译通过,在AS上无法直接编译
    }

最后:验证自己写的广播接收器能否接收到广播

ctrl+r进入命令行界面后按照如下格式发送广播
"adb shell am broadcast -a 你的广播 "

adb shell am broadcast -a "a_test_broadcast"

代码里面写好广播接收

广播监听USB和外设插拔状态_第1张图片

日志打印,如果能收到命令行发送的广播表示成功

你可能感兴趣的:(广播监听USB和外设插拔状态)