实现内容为点击按钮打印接收到的广播内容 1.静态注册
静态注册需要在Manifest.xml去配置:
2.动态注册接收广播消息
动态注册是在类里面去注册:
MainActivity.java:
//实现MyBroadcastReceiver的接口
public class MainActivity extends AppCompatActivity implements MyBroadcastReceiver.MyReceiver {
private TextView mTv_fruit;
IntentFilter filter;
MyBroadcastReceiver myReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTv_fruit = findViewById(R.id.tv_fruit);
//动态注册广播
myReceiver = new MyBroadcastReceiver();
filter = new IntentFilter("myBroadCast");
registerReceiver(myReceiver, filter);
//调用MyBroadcastReceiver类里面的MyThis方法传入MainActivity对象;
myReceiver.MyThis(this);
}
//布局里面的点击事件
public void getReceiver(View view) {
Intent intent = new Intent("myBroadCast");
//android版本为8以上的,静态声明广播注册需要设置包名
intent.setPackage("com.example.broadcat2");
intent.putExtra("fruit", "bana");
sendBroadcast(intent);
}
@Override
protected void onDestroy() {
super.onDestroy();
//页面被销毁了,如finish时,注销广播
//注意如果这个Activity被销毁时,没被注销会报一个异常
unregisterReceiver(myReceiver);
}
//从MyBroadcastReceiver类获取广播接收到的消息内容,并设置给TextView
@Override
public void interFruit(String fruit) {
mTv_fruit.setText(fruit);
}
}
MyBroadcastReceiver.java
package com.example.broadcat2;
public class MyBroadcastReceiver extends BroadcastReceiver {
private MyReceiver mReceiver;
private String fruit;
@Override
public void onReceive(Context context, Intent intent) {
//接收广播消息
fruit = intent.getStringExtra("fruit");
//调用接口MyReceiver里面的interFruit方法传入接收的内容
mReceiver.interFruit(fruit);
//使用Toast显示广播消息
Toast.makeText(context,fruit,Toast.LENGTH_SHORT).show();
}
//创建一个接口把接收到的广播内容传递回MainActivity
interface MyReceiver{
void interFruit(String fruit);
}
public void MyThis(MyReceiver mr){
mReceiver = mr;
}
}
activity_main.xml:
实现图:
点击按钮发送广播,然后使用Toast显示发出的信息并赋值给TextView控件
作者:yulou3