MainActivity3.java 发送广播意图的Activity
public class MainActivity3 extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
}
//发送无序广播--新闻联播
public void click(View view){
Intent intent=new Intent();
intent.setAction("com.example.bro");
sendBroadcast(intent);
}
//发送有序广播--中央文件
public void click2(View view){
Intent intent=new Intent();
intent.setAction("com.example.bro");
sendOrderedBroadcast(intent, null, null, null, 0, "给农民兄弟的10000元", null);
}
}
在Manifest.xml文件中注册广播:
<receiver
android:name="com.example.brocastreceiverdemo.Level1Broadcast">
<intent-filter android:priority="1000">
<action android:name="com.example.bro"/>
</intent-filter>
</receiver>
<receiver
android:name="com.example.brocastreceiverdemo.Level1Broadcast">
<intent-filter android:priority="1000">
<action android:name="com.example.bro"/>
</intent-filter>
</receiver>
<receiver
android:name="com.example.brocastreceiverdemo.Level2Broadcast">
<intent-filter android:priority="500">
<action android:name="com.example.bro"/>
</intent-filter>
</receiver>
<receiver
android:name="com.example.brocastreceiverdemo.Level3Broadcast">
<intent-filter android:priority="100">
<action android:name="com.example.bro"/>
</intent-filter>
</receiver>
<receiver
android:name="com.example.brocastreceiverdemo.Level4Broadcast">
<intent-filter android:priority="-1000">
<action android:name="com.example.bro"/>
</intent-filter>
</receiver>
3.xml布局文件:
<?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"
android:orientation="vertical" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送无序广播"
android:onClick="click"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送序广有播"
android:onClick="click2"
/>
</LinearLayout>
4. 四个具体的brocastreceiver 类:
public class Level1Broadcast extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
// abortBroadcast();//发无序广播,此api不生效
System.out.println("中央发给农民兄弟的10000元钱");
}
}
public class Level2Broadcast extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
System.out.println("省政府发给农民兄弟的5000元钱");
abortBroadcast();//发无序广播,此api不生效
}
}
public class Level3Broadcast extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
System.out.println("县政府发给农民兄弟的2500元钱");
}
}
public class Level4Broadcast extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
System.out.println("乡政府发给农民兄弟的1000元钱");
}
}