其他分享
首页 > 其他分享> > 动态注册广播及接收广播

动态注册广播及接收广播

作者:互联网

动态注册不用在AndroidManifest.xml中声明,直接在代码中注册系统广播和自定义广播,注意使用file来匹配隐式Intent,IntentFilter类似Intent打包数据

        UsbStateReceiver receiver = new UsbStateReceiver();          //new一个广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);           //注册 U盘拔出广播
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);           //注册U盘插入广播
        filter.addAction(Intent.ACTION_MEDIA_REMOVED);
        filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
        filter.addDataScheme("file");                                  // 需要为过滤器设置URL匹配标签,使用file来匹配隐式intent,否则无法接收U盘插拔事件,非常重要
//        filter.addAction("com.lishun");                                //注册 自定义com.lishun广播
        this.registerReceiver(receiver, filter);                       //注册广播

需要自定义一个方法来继承BroadcastReceiver接收广播,并在广播到来时自动调用onReceive

        public class UsbStateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {  //onReceive会在广播来的时候自动调用
            String action = intent.getAction();
//            Log.d(TAG, "onReceive: *************************收到广播");
            Log.d(TAG, "onReceive: "+action);
            switch (action) {
                case Intent.ACTION_MEDIA_MOUNTED:          //收到U盘插入广播
                    Toast.makeText(context, "U盘已插入", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "onReceive: U盘已插入" + intent.getData().getPath());
                    String fromFile = intent.getData().getPath();   //得到U盘的根路径
                    String toFile = "//sdcard";
                    readUDiskDevsList(fromFile, toFile);            //将文件从U盘复制到android设备
                    break;
                case Intent.ACTION_MEDIA_UNMOUNTED:       //收到U盘拔出广播
                    Toast.makeText(context, "U盘已拔出", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "onReceive: U盘已拔出");
                    break;
                default:
                    break;
            }
        }
    }

 

标签:U盘,filter,广播,onReceive,Intent,注册,ACTION,接收
来源: https://blog.csdn.net/qq_42983207/article/details/114735752