我们通过一个实例来认识一下BroadcastReceiver广播接收器。我们两个广播接收器我们用不同的方式去注册,然后设置一个优先级,第一个广播优先级更高,让第一个广播事件给第二个增加一些内容。
在manifest中注册并设置第一个广播的优先级为最高(-1000~1000,1000为最高)
<receiver android:name="com.example.broadcastreceiver.firstBroadReveiver"> <intent-filter android:priority="1000"> <action android:name="briup"/> </intent-filter> </receiver>activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.broadcastreceiver.MainActivity" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="btn"/> </RelativeLayout>MainActivity.java
package com.example.broadcastreceiver; import android.app.Activity; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { private SecandBroadReveiver secandBroadReveiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); secandBroadReveiver=new SecandBroadReveiver(); IntentFilter filter=new IntentFilter(); filter.addAction("briup"); registerReceiver(secandBroadReveiver,filter); } public void btn(View view) { // TODO Auto-generated method stub Intent intent=new Intent(); intent.setAction("briup"); intent.putExtra("data", "原来的广播"); sendOrderedBroadcast(intent, null); //sendBroadcast(intent); } }firstBroadcastReceiver.java
package com.example.broadcastreceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; public class firstBroadReveiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String data=intent.getStringExtra("data"); Toast.makeText(context, "我是firstBroadReveiver "+data, Toast.LENGTH_LONG).show(); //截断广播 //abortBroadcast(); Bundle bundle=new Bundle(); bundle.putString("data1", " 增加这句话"); setResultExtras(bundle); } }SecandBroadcastReceiver.java
package com.example.broadcastreceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; public class SecandBroadReveiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String data=intent.getStringExtra("data"); Bundle bundle=getResultExtras(false); String data1 =bundle.getString("data1"); Toast.makeText(context, "我是SecandBroadReveiver"+data+data1, Toast.LENGTH_LONG).show(); } }