布局相对简单,界面上放置一个按钮,单击按钮以后就会发送一个广播,当广播接收器收到该广播时就会在界面弹出一个提示消息。
1.界面设计
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送广播"/>
</LinearLayout>
2.编写MainActivity代码
public class MainActivity extends AppCompatActivity {
private Button send;
private final String action="MyBroadcast";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
send=(Button)findViewById(R.id.send);
send2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setAction(action);
MainActivity.this.sendBroadcast(intent);
}
});
}
}
上述代码为按钮添加了单击事件,当单击按钮时,就会发送广播。其中 Action 的值与清单文件中定义的值相同。
3.自定义广播接收器自定义广播接收器继承自 BroadcastReceiver ,然后实现它的 onReceiver()方法。
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"广播接收成功",Toast.LENGTH_SHORT).show();
}
}
从上述代码中可以看出,当接收广播时,就会在主界面上显示一个内容为“广播接收成功”的通知。
4.注册广播接收器
注册广播接收器由于本案例使用的是静态的注册方式,所以需要在 Androidmanifest . xml 文件中注册。
<receiver
android:name=".MyReceiver">
<intent-filter>
<action android:name="MyBroadcast"/>
</intent-filter>
</receiver>
从上述代码中可以看出,</ intent - filter >中定义的 action 的 name 属性值要与发送广播时的字符串相同。
5.运行程序
运行程序上述操作完成以后,运行程序,单击主界面上的“发送广播”按钮,就会弹出一个通知。