1、定义两个常量:广播名和广播键值
public static final String ACTION_BONED = "ACTION_BONED"; public static final String ACTION_BONED_DATA = "ACTION_BONED_DATA";
2、在Activity或Service中发送广播
Intent mIntent = new Intent(BluetoothBonedReceiver.ACTION_BONED); mIntent.putExtra(BluetoothBonedReceiver.ACTION_BONED_DATA, sb.toString()); sendBroadcast(mIntent);
3、定义广播接收器
private BroadcastReceiver bonedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(BluetoothBonedReceiver.ACTION_BONED.equals(action)){ String data = intent.getStringExtra(BluetoothBonedReceiver.ACTION_BONED_DATA); Message msg = new Message(); msg.obj = data; handler.sendMessage(msg); } } };
4、注册广播
IntentFilter intentFilter = new IntentFilter(); // 监视蓝牙关闭和打开的状态 intentFilter1.addAction(BluetoothBonedReceiver.ACTION_BONED); registerReceiver(bonedReceiver, intentFilter);
5、注销广播
unregisterReceiver(bonedReceiver);