Android學習筆記之廣播機制(1)

來源:互聯網
上載者:User

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


 
要實現一個廣播接收者方法如下:
 
介面:
 
package mars.testbc; 
 
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 TestActivity extends Activity { 
    /** Called when the activity is first created. */ 
    private Button sendButton; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.testreceiver); 
        sendButton = (Button)findViewById(R.id.sendButton); 
        sendButton.setOnClickListener(new BroadcastListener()); 
    } 
    class BroadcastListener implements OnClickListener{ 
 
        public void onClick(View v) { 
            Intent intent = new Intent(); 
            intent.setAction(Intent.ACTION_EDIT); 
            TestActivity.this.sendBroadcast(intent); 
        } 
         
    } 
} 
 
第一步:要想實現一個廣播機制,就必須實現一個類,這個類繼承於BroadcastReceiver並重寫onReceive()方法。
 
package mars.testbc; 
 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
 
public class TestReceiver extends BroadcastReceiver{ 
 
    public TestReceiver(){ 
        System.out.println("TestReceiver"); 
    } 
    @Override 
    public void onReceive(Context context, Intent intent) { 
        System.out.println("onReceive"); 
    } 
} 
事件響應的實現應在onReceive方法中實現。
第二步:訂閱感興趣的廣播Intent,訂閱者法有兩種:
第一種:使用代碼進行訂閱
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
IncomingSMSReceiver receiver = new IncomingSMSReceiver();
registerReceiver(receiver, filter);
第二種:在AndroidManifest.xml檔案中的<application>節點裡進行註冊:
<intent-filter>是一個過濾器。
在發送廣播過程中,如果某個BroadCastReceiver的Action和這裡的Action相符合,則啟動,接受廣播。
 
<receiver android:name=".TestReceiver"> 
            <intent-filter> 
                <action android:name="android.intent.action.PICK" /> 
            </intent-filter> 
        </receiver> 
 
生命週期:
每次廣播到來時,會重新建立BroadcastReceiver對象,並且調用onReceive()方法,執行完以後,該對象即被銷毀.
當onReceive()方法在10秒內沒有執行完畢,Android會認為該程式無響應.所以在
BroadcastReceiver裡不能做一些比較耗時的操作,否側會彈出ANR(Application No
Response)的對話方塊.。

摘自落日小屋

聯繫我們

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