Android常用組件Broadcast介紹,androidbroadcast

來源:互聯網
上載者:User

Android常用組件Broadcast介紹,androidbroadcast

一、Broadcast簡介

Broadcast是Android的四大組件之一。可分為:

1、普通廣播  發送一個廣播,所有監聽該廣播的廣播接收者都可以監聽到改廣播。 

2、非同步廣播  當處理完之後的Intent,依然存在,這時候registerReceiver(BroadcastReceiver,IntentFilter) 還能收到他的值,直到你把它去掉,不能將處理結果傳給下一個接收者,無法終止廣播。

3、有序廣播  按照接收者的優先順序順序接收廣播,優先順序別在intent-filter中的priority中聲明,-1000到1000之間,值越大,優先順序越高.可以終止廣播意圖的繼續傳播.接收者可以篡改內容. 

二、廣播Broadcast實現過程

1、註冊

a、設定檔註冊

1 <!-- 註冊自訂靜態廣播接收器 -->  2 <receiver android:name="com.example.androidtest.broadcast.MyReceiver">3   <intent-filter >4      <action android:name="MyAction"/>5    </intent-filter>6</receiver>

b、代碼註冊

1 MyReceiver myReceiver = new MyReceiver();2 IntentFilter filter = new IntentFilter();3 filter.addAction("MyAction");4 registerReceiver(myReceiver,filter);

2、發送廣播

1 Intent intent = new Intent();2 intent.setAction("MyAction");3 intent.putExtra("msg", "這是廣播發送的訊息");4 sendBroadcast(intent);

3、接收類的實現

繼承BroadcastReceiver並重寫onReceive方法。

1 public class MyReceiver extends BroadcastReceiver2 {3     public void onReceive(Context context, Intent intent)4     {5         Toast.makeText(context, "廣播訊息是:" + intent.getStringExtra("msg"), Toast.LENGTH_SHORT).show();6     }7 8 }

三、若內部類作為廣播接收類如何?

1、註冊

a、設定檔註冊

1 <!-- 註冊自訂靜態廣播接收器 -->  2 <receiver android:name="com.example.androidtest.broadcast.BroadcastTest$MyReceiver">  <!-- 注意內部類寫法:普通類$內部類 -->3   <intent-filter >4      <action android:name="MyAction"/>5    </intent-filter>6</receiver>

b、代碼註冊

1 MyReceiver myReceiver = new MyReceiver();2 IntentFilter filter = new IntentFilter();3 filter.addAction("MyAction");4 registerReceiver(myReceiver,filter);

2、發送廣播

1 Intent intent = new Intent();2 intent.setAction("MyAction");3 intent.putExtra("msg", "這是廣播發送的訊息");4 sendBroadcast(intent);

3、接收類的實現

注意:若在設定檔中註冊則該類必須聲明為static,否則找不到,若在代碼中註冊科省略static

1 public static class MyReceiver extends BroadcastReceiver 2 {3     public void onReceive(Context context, Intent intent)4     {5         Toast.makeText(context, "廣播訊息是:" + intent.getStringExtra("msg"), Toast.LENGTH_SHORT).show();6     }7 8 }

四、用途

開機、鎖屏、電量低…… 

五、注意

生命週期只有十秒左右,如果在 onReceive() 內做超過十秒內的事情,就會報錯 。

每次廣播到來時 , 會重新建立 BroadcastReceiver 對象 , 並且調用 onReceive() 方法 , 執行完以後 , 該對象即被銷毀 . 當 onReceive() 方法在 10 秒內沒有執行完畢, Android 會認為該程式無響應 . 所以在BroadcastReceiver 裡不能做一些比較耗時的操作 , 否側會彈出 ANR(Application NoResponse) 的對話方塊 

部分內容取自:http://yangguangfu.iteye.com/blog/1063732

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.