首先介绍一下BroadCastRecieve有几种:
1.无序广播(普通广播):sendBroadcast()方式
2.有序广播:sendOrderedBroadcast()方式
3.粘性广播:sendStickyBroadcast()方式
生命周期比较简单:
下面是无序广播与有序广播的区别:
下面是普通广播(无序广播,有序广播)与粘性广播的区别:
sendBroadcast(intent); 发送之前必须注册广播,否则无法接收到广播信息。
sendStickyBroadcast(intent);发送广播后,注册也可收到广播信息。
首先看下一个无序广播,有序广播的例子:
package com.example.demo_broadcast2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 发送无序广播
*
* @param view
*/
public void send1(View view) {
Intent intent = new Intent();
intent.setAction("com.itheima.broadcasttest.songwennuan");
intent.putExtra("msg", "发1万块");
intent.putExtra("isUnordered", true);
// 无序广播,不可被拦截,不可终止
sendBroadcast(intent);
}
public void send2(View view) {
Intent intent = new Intent();
intent.setAction("com.itheima.broadcasttest.songwennuan");
// 有序广播,可被拦截,可终止,可以修改数据
sendOrderedBroadcast(intent, null, null, null, 0,
"给农民兄弟发10000块钱", null);
}
}
send1,send2分别为点击事件触发时调用的函数分别为发送无序广播按钮,发送有序广播按钮。
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"
tools:context=".MainActivity" >
<Button
android:onClick="send1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="发送无序广播" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="51dp"
android:onClick="send2"
android:text="发送有序广播" />
</RelativeLayout>
下面依次是多个广播的实例(为了体现有序广播)
package com.example.demo_broadcast2;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class Level1Receiver extends BroadcastReceiver {
private static final String TAG = "Broadcasttest";
@Override
public void onReceive(Context context, Intent intent) {
boolean isUnordered = intent.getBooleanExtra("isUnordered", false);
if (isUnordered) {
String message = intent.getStringExtra("msg");
Log.i(TAG, "省级部门得到中央的消息:" + message);
} else {
String message = getResultData();
Log.i(TAG, "省级部门得到中央的消息:" + message);
abortBroadcast(); // 这里是终止了消息,可以关闭或者取消这里查看LogCat中打印的效果。
setResultData("给农民兄弟发5000块钱"); // setResultData()方法,就是为了在有序广播中修改传到下一个广播中的值而存在的,且只能存储一个String.
}
}
}
package com.example.demo_broadcast2;
import android.content.BroadcastRecei