1. 程式人生 > 實用技巧 >Android BroadcastReceiver傳值

Android BroadcastReceiver傳值

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);