Android中的Intent廣播(broadcast)簡介

來源:互聯網
上載者:User

Intent可以使用sendBroadcast(), 在應用組件之間廣播事件;

使用BroadReceiver類監聽和響應Broadcast Intent, 需要註冊(register)和過濾器(intent-filter);

1. 建立Broadcast Intent

構建需要廣播的Intent, 包含Intent標識字串, 和資料(data, extras), 使用sendBroadcast()發送;

Intent標識字串, 可以標識要廣播的字串, 應該是能夠標誌的唯一字串,

public static final String [ACTION_STRING] = "[mzx].[clwang].action.[ACTION_STRING]";

Intent包含資料, 進行廣播, 可以使用data屬性指定一個URI, 可以在extras添加額外的基本值;

Intent intent = new Intent("[mzx].[clwang].action.[ACTION_STRING");

sendBroadcast(intent);

2. 接收Broadcast Intent

使用Broadcast Receiver來監聽Broadcast Intent, 在代碼或manifest中註冊, 使用Intent FIlter表明監聽的Intent(標識符)和資料;

應用程式可以被Intent啟動, 可以建立事件驅動的應用程式;

Broadcast Receiver, 繼承BroadcastReceiver類, 重寫onReceive事件, 進行處理, 必須在5秒之內完成;

代碼註冊:

註冊BroadcastReceiver, 需要使用IntentFilter, 指明標識符; 使用BroadReceiver類, 指明接收器;

註冊: registerReceiver(receiver, filter); 登出:unregisterReceiver(receiver);

Manifest註冊:

<receiver android:name = ".[Receiver]">

   <intent-filter>

       <action android:name="[mzx].[clwang].action.[ACTION_STRING">

   </intent-filter>

</receiver>

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.