Android之BroadcastReceiver

來源:互聯網
上載者:User

標籤:android   broadcastreceiver   廣播機制   

Android廣播機制包含三個基本要素:
廣播寄件者(調用sendBroadcast方法) - 用於發送廣播;
廣播接收器(BroadcastReceiver) - 用於接收廣播;
意圖內容(Intent)-用於儲存廣播相關資訊的媒介。
Broadcast是Android中一種廣泛運用的在應用程式之間或應用程式內個組件直接傳輸資訊的機制。而BroadcastReceiver是對發送出來的廣播Intent進行過濾接受並響應的一類組件。

BroadcastReceiver廣播接收者用於非同步接收廣播Intent,廣播Intent的發送是通過調用Context.sendBroadcast()來實現的。通常一個廣播Intent可以被訂閱了此Intent的多個廣播接收者所接收。

每次廣播Intent發出後,系統就會建立對應的BroadcastReceiver的執行個體,並自動觸發它的onReceiver()方法,onReceiver()方法執行完後,BroadcastReveiver的執行個體就會被銷毀。

通常一個BroadcastReceiver對象的生命週期不超過5秒,所以在BroadcastReceiver裡不能做一些比較耗時的操作。如果需要根據Broadcast來完成一項比較耗時的操作,則可以考慮通過Intent啟動一個Service來完成該操作。

執行個體:BroadcastDemo
運行效果:

代碼清單:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.rainsong.broadcastdemo"      android:versionCode="1"      android:versionName="1.0">    <uses-sdk        android:minSdkVersion="11"        android:targetSdkVersion="19" />    <application android:label="@string/app_name" android:icon="@drawable/ic_launcher">        <activity android:name="MainActivity"                  android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <receiver android:name="MyReceiver">            <intent-filter>                <action android:name="com.rainsong.action.NEW_BROADCAST" />             </intent-filter>        </receiver>    </application></manifest>
布局檔案:main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >    <Button        android:id="@+id/button1"        android:layout_width="fill_parent"        android:layout_height="wrap_content"         android:text="發送廣播"     /></LinearLayout>
Java原始碼檔案:MainActivity.java
package com.rainsong.broadcastdemo;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity{    public final String ACTION = "com.rainsong.action.NEW_BROADCAST";    Button btn1;    OnClickListener listener1;    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        btn1 = (Button)findViewById(R.id.button1);        listener1 = new OnClickListener() {            public void onClick(View v) {                Intent intent = new Intent(ACTION);                sendBroadcast(intent);            }        };        btn1.setOnClickListener(listener1);    }}
Java原始碼檔案:MyReceiver.java
package com.rainsong.broadcastdemo;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;public class MyReceiver extends BroadcastReceiver {    public static int NOTIFICATION_ID = 12345;    @Override    public void onReceive(Context context, Intent intent) {        NotificationManager nm =             (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);        Notification notification = new Notification(android.R.drawable.stat_notify_chat,             "MyReceiver onReceive", System.currentTimeMillis());        Intent intent1 = new Intent(context, MainActivity.class);        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent1, 0);        notification.setLatestEventInfo(context, "MyReceiver onReceive", null, pendingIntent);        nm.notify(NOTIFICATION_ID, notification);      }}

代碼邏輯:
單擊“發送廣播”按鈕,我們的程式開始發送廣播Intent,這個廣播Intent被MyReceiver所截獲,然後就開始執行MyReceiver裡的onReceive方法,在onReceive裡邊將一個Notification顯示在狀態列中。

Android之BroadcastReceiver

聯繫我們

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