发送标准广播需要定义一个广播接收器StandardBroadcastReceiver,来看代码:
public class StandardBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "接收到了广播", Toast.LENGTH_SHORT).show();
}
}
当StandardBroadcastReceiver接收到广播会弹出提示消息
接下来我们在定义一个点击按钮事件,来实现广播的发送:
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.example.broadcasttest.STANDARD_BROADCAST");
sendBroadcast(intent);
}
});
最后我们在AndroidManifest文件中对广播接收器进行注册:
<receiver android:name=".StandardBroadcastReceiver" >
<intent-filter >
<action android:name="com.example.broadcasttest.STANDARD_BROADCAST"/>
</intent-filter>
</receiver>
好了,这样,一个完整的标准广播发送就完成了。
发送有序广播只需要将按钮点击事件中的sendBroadcast(intent)修改为
sendOrderedBroadcast(intent,null)就好了,null是一个与权限有关的字符串,这里传入null就可以。
既然是有序广播,那么就要有优先级,在AndroidManifest文件中可以对广播接收器进行优先级定义,使用android:priority属性进行声明。如:
<receiver android:name=".MyBroadcastReceiver" >
<intent-filter android:priority="100" >
<action android:name="com.example.broadcasttest.STANDARD_BROADCAST"/>
</intent-filter>
</receiver>
截断广播只需要在广播接收器的onReceive()方法中写入
abortBroadcast();就好了。