发送自定义广播
- 布局文件:activity_main.xml
在界面上加一个button和一个textview
2,主界面程序: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.tv);
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();
}
}
});
}
}
3,运行界面
单击按钮前:
单击按钮后: