天天看點

Android學習_廣播

廣播接收器也是運作在ui線程,是以,onreceive方法中不能執行太耗時的操作。

否則将是以anr。一般情況下,根據實際業務需求,

onreceive方法中都會涉及到與其他元件之間的互動,

如發送notification、啟動service等。

當此activity執行個體化時,會動态将mybroadcastreceiver注冊到系統中。

當此activity銷毀時,動态注冊的mybroadcastreceiver将不再接收到相應的廣播。

 根據廣播的發送方式,可以将其分為以下幾種類型:

1.normal broadcast:普通廣播

2.system broadcast: 系統廣播

涉及到手機的基本操作,基本上都會發出相應的系統廣播。如:開啟啟動,網絡狀态改變,

拍照,螢幕關閉與開啟,點亮不足等等。每個系統廣播都具有特定的intent-filter,

其中主要包括具體的action,系統廣播發出後,将被相應的broadcastreceiver接收。

系統廣播在系統内部當特定事件發生時,有系統自動發出。

3.ordered broadcast:有序廣播

定義過程與普通廣播無異,

隻是其的主要發送方式變為:sendorderedbroadcast(intent, receiverpermission, ...)。

priority屬性值從大到小排序,對于具有相同的priority的動态廣播和靜态廣播,動态廣播會排在前面。

4.sticky broadcast:粘性廣播(在 android 5.0/api 21中deprecated,不再推薦使用,

相應的還有粘性有序廣播,同樣已經deprecated)

5.local broadcast:app應用内廣播

常見的增加安全性的方案是:

1.對于同一app内部發送和接收廣播,将exported屬性人為設定成false,使得非本app内部發出的此廣播不被接收;

2.在廣播發送和接收時,都增加上相應的permission,用于權限驗證;

3.發送廣播時,指定特定廣播接收器所在的包名,具體是通過intent.setpackage(packagename)指定在,

這樣此廣播将隻會發送到此包中的app内與之相比對的有效廣播接收器中。

//registerreceiver(mbroadcastreceiver, intentfilter);

//注冊應用内廣播接收器

localbroadcastmanager = localbroadcastmanager.getinstance(this);

localbroadcastmanager.registerreceiver(mbroadcastreceiver, intentfilter);

//unregisterreceiver(mbroadcastreceiver);

//取消注冊應用内廣播接收器

localbroadcastmanager.unregisterreceiver(mbroadcastreceiver);

intent intent = new intent();

intent.setaction(broadcast_action);

intent.putextra("name", "qqyumidi");

//sendbroadcast(intent);

//發送應用内廣播

localbroadcastmanager.sendbroadcast(intent);

1.//動态廣播 注冊和發送

/**

* 定義一個broadcastreceiver廣播接收類:

*/

private broadcastreceiver mbroadcastreceiver = new broadcastreceiver() {

@override

public void onreceive(context context, intent intent) {

string action = intent.getaction();

if (action.equals(action_name)) {

toast.maketext(mainactivity.this, "處理action名字相對應的廣播", 200);

}

};

* 注冊廣播

public void registerboradcastreceiver() {

intentfilter myintentfilter = new intentfilter();

myintentfilter.addaction(action_name);

// 注冊廣播

registerreceiver(mbroadcastreceiver, myintentfilter);//接收者對象、接受者action

1)先調用注冊廣播

2)發送廣播

intent mintent = new intent(action_name);

mintent.putextra("txt", "發送廣播,相當于在這裡傳送資料");

// 發送廣播

sendbroadcast(mintent);

3)銷毀

protected void ondestroy() {

// todo auto-generated method stub

super.ondestroy();

unregisterreceiver(recevier);

2.靜态注冊廣播

2.1定義廣播類繼承 broadcastreceiver

log.i("tag", "normalbroadcastrecevier");

log.i("tag", "action=" + intent.getaction());

2.2在manifest中注冊 廣播action

<receiver android:name="???" >

            <intent-filter>

                <action android:name="com.jingtai" />

            </intent-filter>

        </receiver>

2.3發送廣播

log.i("tag", "靜态注冊-正在發送正常廣播....");

// 封裝要啟動的廣播接收器的action

intent intent = new intent("com.jingtai");

sendbroadcast(intent);

3.有序廣播 priority

3.1廣播的注冊方法:通過設定android:priority的數值,控制廣播接收的優先級

<receiver android:name="com.??" >

            <intent-filter android:priority="80">

                <action android:name="com.order" />

3.2broadcastreceiver 中onreceive方法中的參數的傳遞

封裝 bundle參數

bundle bundle = new bundle();

bundle.putstring("txt", "收到廣播之後立馬結束廣播");

setresultextras(bundle);

接收 bundle參數

bundle bundle = this.getresultextras(true);

log.i("tag", "---->values=" + bundle.getstring("txt"));

1)建立 多了broadcastreceiver 對象

2)manifest 注冊相同的action  不同的 android:priority= "數值"

3)啟動調用  有序廣播

// 封裝id

intent.setaction("com.example.ch16_broadcast_abcd");

// 發送有序廣播

sendorderedbroadcast(intent, null);

============================================

資料傳遞  有序廣播接收者中的資料傳遞方法;

攔截有序廣播  abortbroadcast();

priority 數值越大,優先級越高,即,越先接收到廣播

<intent-filter android:priority="1000"> 

                 <action android:name="actionname" />

            </category></action></intent-filter>

string strmsg = intent.getstringextra("msg");

        log.e("pzf", "第一個:"+strmsg);

        bundle extras=new bundle();

        extras.putstring("msg", "第一個界面傳過來的"+strmsg);

        setresultextras(extras); //繼續向下川

//abortbroadcast();//開啟此處,可以截斷廣播,不讓它傳到third中

        string strmsg = intent.getstringextra("msg"); //擷取廣播的原始資料

        log.e("pzf", "第二個:"+strmsg);

        extras.putstring("msg", "第二個界面傳過來的"+strmsg);

        setresultextras(extras); //繼續向下   

        setresultdata("第二個:"+strmsg); // "第二個:"+strmsg這是two中新的資料,傳遞到third中,在third中是用getresultdata來獲得setresultdata("")中的資料

string resultdata = getresultdata();//擷取two中setresultdata中的資料

        bundle bundle = getresultextras(true);//擷取two中setresultextras中的資料

        string bundledata = bundle.getstring("msg", "");//擷取two中setresultextras()中的資料 

        string strmsg = intent.getstringextra("msg");//擷取廣播的原始資料

        log.e("pzf", "第三個:"+strmsg); 

        log.e("pzf", "two中傳到third新的資料:"+resultdata);

        log.e("pzf", "two中setresultextras(extras)傳到third新的資料:"+bundledata);

==============================================

4.舉例示範 service 和broadcast 結合重新整理ui

4.1首頁面注冊 廣播

private broadcastreceiver recevier = new broadcastreceiver() {

int value = intent.getintextra("key",0);

tv.settext(value + "%");

if (value == 100) {

btnstart.setenabled(true);

tv.settext("下載下傳完成!");

4.2 注冊廣播的 intentfilter 

private void initintentfilter(){

intentfilter filter = new intentfilter();

filter.addaction("myservice_send inner_broadcast");

this.registerreceiver(recevier, filter);

4.3 啟動服務類、模拟下載下傳的線程

intent intent = new intent(mainactivity.this, myservice.class);

startservice(intent);

btnstart.setenabled(false);//設定按鈕不可以點選

4.4 myservice 的實作類 模拟下載下傳耗時操作 發送廣播重新整理ui

public class myservice extends service {

public ibinder onbind(intent intent) {return null;}

public void oncreate() {super.oncreate();}

public int onstartcommand(intent intent, int flags, int startid) {

// 模拟耗時操作

new thread(new runnable() {

public void run() {

int count = 0;

intent i = new intent();

i.setaction("myservice_send inner_broadcast");

while (count < 100) {

count++;

// 模拟多少時間之後才發送廣播

try {

thread.sleep(100);

} catch (interruptedexception e) {

e.printstacktrace();

i.putextra("key", count);

// 開始發送廣播

sendbroadcast(i);

}).start();

return super.onstartcommand(intent, flags, startid);

系統的廣播的action,在離線api可以搜尋

standard broadcast actions

these are the current standard actions that intent defines for 

receiving broadcasts (usually through registerreceiver(broadcastreceiver, 

intentfilter) or a <receiver> tag in a manifest).

action_time_tick

action_time_changed

action_timezone_changed

action_boot_completed

action_package_added

action_package_changed

action_package_removed

action_package_restarted

action_package_data_cleared

action_uid_removed

action_battery_changed

action_power_connected

action_power_disconnected

action_shutdown

繼續閱讀