安卓USB挂载设备监听

安卓USB挂载设备监听

其实这个东西没什么太多可讲的,但是对于安卓电视、机顶盒开发的人来说却也是必备知识点,为了节约大家的开发时间,也呈现给大家看看,这里只讲关键代码,先贴图:
安卓USB挂载设备监听_第1张图片
CARD内部存储盘是一直都存在的,但是设备如果有USB接口,我们就有了一个需求:需要即时更新存储设备界面,当然google官方早给大家准备了相应的广播机制,帮助监听USB接口挂载的情况,既然是广播,那么第一步自然是注册:
private void detectionUSB() {
        IntentFilter usbFilter = new IntentFilter();
        usbFilter.addAction(Intent.ACTION_UMS_DISCONNECTED);
        usbFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        usbFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        usbFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
        usbFilter.addDataScheme("file");
        registerReceiver(usbReceiver, usbFilter);
    }
然后写接收代码:
private BroadcastReceiver usbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            mHandler.removeMessages(0);
            Message msg = new Message();
            msg.what = 0;
            if (action.equals(Intent.ACTION_MEDIA_REMOVED)
                     || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
                //设备卸载成功
                msg.arg1 = 0;
                Toast.makeText(context, getString(R.string.uninstall_equi), Toast.LENGTH_SHORT).show();
             } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)){
                //设备挂载成功
                msg.arg1 = 1;
                Toast.makeText(context, getString(R.string.install_equi), Toast.LENGTH_SHORT).show();}
            Bundle bundle = new Bundle();
            bundle.putString(MOUNT_PATH, intent.getData().getPath());
            msg.setData(bundle);
            mHandler.sendMessageDelayed(msg, 1000);
        }
    };
最后更新UI:
private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0){
                //卸载成功
                if (msg.arg1 == 0){
                    File file = new File(msg.getData().getString(MOUNT_PATH));
                    files.remove(file);
                    refreshFile();
                }else {//挂载成功
                    File file = new File(msg.getData().getString(MOUNT_PATH));
                    files.add(0,file);
                    refreshFile();//刷新
                }
            }
            super.handleMessage(msg);
        }
    };
三步搞定,马上试试吧。



你可能感兴趣的:(USB)