Android:Broadcast广播

静态注册广播:
在Androidmanifast.xml静态注册广播(广播全局生效):

//android提供的某些action,需要赋予权限才能发广播,权限也在Androidmanifast.xml中定义
<receiver android:name=".system.BvOtgReceiver">   #设置广播接收器
    <intent-filter android:priority="1000">        #priority:设置优先级
        <action android:name="android.hardware.usb.action.USB_STATE" />     #定义action,广播接收器接收时可以通过这个action作为判断条件
        <action android:name="com.android.ACTION_CLOSE_OTG"/>               #定义action可以自定义,也可以按需求使用系统的特定action
    </intent-filter>
</receiver>

定义一个广播接收类:

public class BvOtgReceiver extends BroadcastReceiver {
    private static final String ACTION_CLOSE_OTG = "com.android.ACTION_CLOSE_OTG";
    private static final String  ACTION_USB_STATE = "android.hardware.usb.action.USB_STATE"
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_USB_STATE.equals(action)){
           //当接收到ACTION_USB_STATE 此action时,运行的代码
        } else if (ACTION_CLOSE_OTG.equals(action)){
            //当接收到ACTION_CLOSE_OTG 此action时,运行的代码
        }
    }
}

动态注册广播:
直接在当前fragment或Activity中注册广播,它们若被销毁,广播也就接受不到了(非全局):

 	@Override
    public void onCreate() {
        super.onCreate();
        usbWithBroadcast();
    }
    private void usbWithBroadcast(){
        IntentFilter usbDeviceStateFilter = new IntentFilter();
        usbDeviceStateFilter.addAction("android.hardware.usb.action.USB_STATE");
        usbDeviceStateFilter.addAction("com.android.ACTION_CLOSE_OTG")
        getPrefContext().registerReceiver(mUsbReceiver, usbDeviceStateFilter);
    }

    BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            boolean connected = intent.getBooleanExtra(UsbManager.USB_CONNECTED, false);
            if ("android.hardware.usb.action.USB_STATE".equals(action)){
            //当接收到"android.hardware.usb.action.USB_STATE" 此action时,运行的代码
            } else if ("com.android.ACTION_CLOSE_OTG".equals(action)){
            //当接收到"com.android.ACTION_CLOSE_OTG" 此action时,运行的代码
            }
        }
    };

你可能感兴趣的:(android)