Android BroadcastReceiver传值

Posted 代码艺术

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);

 

以上是关于Android BroadcastReceiver传值的主要内容,如果未能解决你的问题,请参考以下文章

Android_组件_BroadcastReceiver基础

Android BroadcastReceiver广播:基本使用

Android -- BroadCastReceiver的简单使用

Android BroadcastReceiver

android从broadcastreceiver刷新listview

Android开发实践 BroadcastReceiver