1、创建本地广播接收器
18 public class MainActivity extends AppCompatActivity{ 19 private Button mBtn;21 private BindService.MyBinder mMyBinder; 22 private MyReceiver mMyReceiver; //创建广播接收器类变量 23 private LocalBroadcastManager mLocalBroadcastManager; //创建本地广播管理器类变量 24 25 @Override 26 protected void onCreate(Bundle savedInstanceState) { 27 super.onCreate(savedInstanceState); 28 setContentView(R.layout.activity_main); 44 mMyReceiver = new MyReceiver(); //实例化广播接收器 MyReceiver() 45 IntentFilter filter = new IntentFilter("com.package.yanglei.action.test"); //动态配置广播接收器action 46 mLocalBroadcastManager = LocalBroadcastManager.getInstance(this); //广播变量管理器获得本地广播管理器 47 mLocalBroadcastManager.registerReceiver(mMyReceiver, filter); //注册本地广播 48 49 50 mBtn = findViewById(R.id.mOnclick); 51 mBtn.setOnClickListener(new View.OnClickListener() { 52 @Override 53 public void onClick(View view) { 54 55 Intent intent = new Intent("com.package.yanglei.action.test"); //创建发送广播的Action 56 intent.putExtra(Intent.EXTRA_TEXT, "hi lllllllllll"); //发送携带的数据 57 mLocalBroadcastManager.sendBroadcast(intent); //发送本地广播 62 } 63 }); 65 66 } 67 68 //广播接收器 69 private class MyReceiver extends BroadcastReceiver { 70 @Override 71 public void onReceive(Context context, Intent intent) { 72 Log.i("hhhhhhh0", intent.getStringExtra(Intent.EXTRA_TEXT)); //获取文本 73 } 74 } }
时间: 2024-10-08 06:40:06