一、布局
二、自定义BroadcastRecevier
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle mybundle = intent.getExtras();
String str1 = mybundle.getString(“data1”);
String str2 = mybundle.getString(“data2”);
Toast.makeText(context, str1+" " +str2,Toast.LENGTH_LONG).show();
tv.setText(str1+" " +str2);
}
};
三、主界面程序:MainActivity
public class MainActivity extends AppCompatActivity {
private TextView tv; //用于显示接收到的广播信息
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle mybundle = intent.getExtras();
String str1 = mybundle.getString(“data1”);
String str2 = mybundle.getString(“data2”);
Toast.makeText(context, str1+" " +str2,Toast.LENGTH_LONG).show();
tv.setText(str1+" " +str2);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//使用意图过滤器类IntentFilter动态注册广播接收者
IntentFilter myintentfliter = new IntentFilter();
myintentfliter.addAction("com.example.broadcast.MY_BROADCAST");
registerReceiver(myReceiver, myintentfliter);
tv = findViewById(R.id.txt);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent myintent = new Intent("com.example.broadcast.MY_BROADCAST");
Bundle bundle = new Bundle();
bundle.putString("data1", "自定义广播与接收案例");
bundle.putString("data2", "啦啦啦");
myintent.putExtras(bundle); //捆绑数据
sendBroadcast(myintent); //发送广播
try {
Thread.sleep(1000); //休眠一下,模拟广播可能存在的延迟
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
四、运行结果
结语
个人理解自定义的广播核心就是BroadcastReceiver的编写。
这是最基础的自定义广播,但在实际应用时,广播通常是内嵌于activity和service的,之后会完善另一个作业——MusicBox。