Android 四大组件之BroadcastReceiver(3)

1 package com.example.administrator.broadcastreceivertest; 2 3 import android.content.BroadcastReceiver; 4 import android.content.Context; 5 import android.content.Intent; 6 import android.util.Log; 7 import android.widget.Toast; 8 9 10 public class MyBroadcastReceiver2 extends BroadcastReceiver{ 11 12 @Override 13 public void onReceive(Context context, Intent intent) { 14 String msg = intent.getStringExtra("msg"); 15 Log.i("tag","MyBroadcastReceiver2:"+msg); 16 Toast.makeText(context,"MyBroadcastReceiver2:"+msg,Toast.LENGTH_LONG).show(); 17 } 18

  activity_main.xml

1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" 3 android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" 4 android:paddingRight="@dimen/activity_horizontal_margin" 5 android:paddingTop="@dimen/activity_vertical_margin" 6 android:orientation="vertical" 7 android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> 8 9 10 <Button 11 android:layout_width="wrap_content" 12 android:layout_height="wrap_content" 13 android:text="发送 Ordered Broadcast " 14 android:onClick="sendOrderedBroadcast"/> 15 </LinearLayout> 

  AndroidManifest.xml

1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.example.administrator.broadcastreceivertest" > 4 5 <application 6 android:allowBackup="true" 7 android:icon="@drawable/ic_launcher" 8 android:label="@string/app_name" 9 android:theme="@style/AppTheme" > 10 <activity 11 android:name=".MainActivity" 12 android:label="@string/app_name" > 13 <intent-filter> 14 <action android:name="android.intent.action.MAIN" /> 15 16 <category android:name="android.intent.category.LAUNCHER" /> 17 </intent-filter> 18 </activity> 19 20 21 <receiver android:name=".MyBroadcastReceiver"> 22 <intent-filter android:priority="1"> 23 <action android:name="com.example.administrator.broadcastreceiver.SEND_MESSAGE"/> 24 </intent-filter> 25 </receiver> 26 27 <receiver android:name=".MyBroadcastReceiver2"> 28 <intent-filter android:priority="2"> 29 <action android:name="com.example.administrator.broadcastreceiver.SEND_MESSAGE"/> 30 </intent-filter> 31 </receiver> 32 </application> 33 34 </manifest>

运行结果:

Android 四大组件之BroadcastReceiver

Android 四大组件之BroadcastReceiver

Android 四大组件之BroadcastReceiver

控制台输出结果:

Android 四大组件之BroadcastReceiver

从运行结果可以看出先是MyBroadcastReceiver2先接收到Broadcast,接着才是MyBroadcastReceiver,因为我在注册时将MyBroadcastReceiver2的优先级设置为2,MyBroadcastReceiver优先级为1。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/ba72a5c1b4e290d5b609100dc6951118.html