1.发送广播:
private Button bt1;
private String action = "com.example.app.Bro";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button) findViewById(R.id.button1);//获取按钮
bt1.setOnClickListener(new OnClickListener() {//设置按钮点击事件
public void onClick(View v) {
Intent it = new Intent();//创建意图
it.setAction(action);//设置广播地址
it.putExtra("msg", "aaaaaa");//放入数据
sendBroadcast(it);//发送
}
});
}
2.接收广播
1.)
//重写BroadcastReceiver
public class Bro extends BroadcastReceiver {
public void onReceive(Context context,Intent intent) {
String msg = intent.getStringExtra("msg");//获取广播里的数据
System.out.println(msg);//输出数据
Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();//显示数据
}
}
添加清单文件
<receiver
android:name="com.example.app.Bro"
android:label="@string/app_name">
<intent-filter>
<action android:name="com.example.app.Bro"/>
</intent-filter>
</receiver>