Android 應用軟體開發(十三)廣播機制

來源:互聯網
上載者:User

廣播機制:發送方不管接收方是否接收到資料,如何接收和處理

一、要想實現廣播的接收,必須先建立一個類繼承自BroadcastReceiver,複寫其onReceive方法

二、在Manifest檔案當中進行註冊並設定action的過濾器,也可以在應用程式代碼中註冊

BroadcastReceiver的生命週期是,感興趣的廣播事件發生時建立對象,onReceive函數返回時銷毀對象。

Intent 是action和data共同完成資訊的攜帶的

如果BroadcastReceiver在Manifest中註冊,則當應用程式關閉時,它依然會接收廣播

<receiver android:name=".TestReceiver">      <intent-filter>           <action android:name="android.intent.action.EDIT"/>      </intent-filter></receiver>

在代碼中註冊,用於更新UI,Activity啟動時註冊,不可見時取消註冊

Android 系統中內建的BroadcastActions

這些內建的actions可以在協助文檔的Intent類的常量中查到

下面分別給出兩個例子(在manifest檔案中註冊廣播接收器和在代碼中註冊廣播接收器)

注意如果在代碼中註冊,則必須先在manifest檔案中設定許可權

TestBCActivity.java:

package mars.testBC;import android.app.Activity;import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class TestBCActivity extends Activity {    /** Called when the activity is first created. */    private Button sendButton;    private Button registerButton = null;    private Button unregisterButton = null;    private SMSReceiver smsReceiver = null;    private static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED";@Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        sendButton = (Button)findViewById(R.id.sendButton);        sendButton.setOnClickListener(new SendListener());        registerButton = (Button)findViewById(R.id.registerButton);        unregisterButton = (Button)findViewById(R.id.unregisterButton);        registerButton.setOnClickListener(new RegisterListener());        unregisterButton.setOnClickListener(new UnRegisterListener());    }//例一class SendListener implements OnClickListener{@Overridepublic void onClick(View v) {// TODO Auto-generated method stub//產生Intent對象,挾帶廣播資訊Intent intent = new Intent();//設定Actionintent.setAction(Intent.ACTION_EDIT);//廣播TestBCActivity.this.sendBroadcast(intent);}}//例二class RegisterListener implements OnClickListener{@Overridepublic void onClick(View v) {// TODO Auto-generated method stubsmsReceiver = new SMSReceiver();//設定過濾器IntentFilter filter = new IntentFilter();//添加過濾事件(短訊息接收事件)filter.addAction(SMS_ACTION);//註冊廣播接收器TestBCActivity.this.registerReceiver(smsReceiver, filter);}}class UnRegisterListener implements OnClickListener{@Overridepublic void onClick(View v) {// TODO Auto-generated method stub//解除綁定TestBCActivity.this.unregisterReceiver(smsReceiver);}}}

TestReceiver.java:

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("TestReceive");}@Overridepublic void onReceive(Context arg0, Intent arg1) {// TODO Auto-generated method stubSystem.out.println("onReceive");}}

SMSReceiver.java:

package mars.testBC;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.telephony.SmsMessage;public class SMSReceiver extends BroadcastReceiver {SMSReceiver(){System.out.println("SMSReceiver constructor");}@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubBundle bundle = intent.getExtras();Object[] myOBJpdus = (Object[])bundle.get("pdus");SmsMessage[] messages = new SmsMessage[myOBJpdus.length];System.out.println(messages.length);for(int i=0; i<myOBJpdus.length; i++){messages[i] = SmsMessage.createFromPdu((byte[])myOBJpdus[i]);System.out.println(messages[i].getDisplayMessageBody());}}}

main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello" />    <Button        android:id="@+id/sendButton"        android:layout_width="fill_parent"        android:layout_height="wrap_content"    android:text="start"/>        <Button         android:id="@+id/registerButton"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="綁定"/>        <Button         android:id="@+id/unregisterButton"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="解除綁定"/></LinearLayout>

Manifest.xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="mars.testBC"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk android:minSdkVersion="4" />    <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name" >        <activity            android:label="@string/app_name"            android:name=".TestBCActivity" >            <intent-filter >                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>                <receiver android:name=".TestReceiver">            <intent-filter>                <action android:name="android.intent.action.EDIT"/>            </intent-filter>        </receiver>    </application>    <!-- 設定許可權 -->    <uses-permission             android:name="android.permission.RECEIVE_SMS">           </uses-permission></manifest>

聯繫我們

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