Android:靜態註冊BroadcastReceiver

來源:互聯網
上載者:User

標籤:android   廣播   broadcastreceiver   動態註冊   

由於動態註冊BroadcastReceiver只能在Activity的onCreate()方法調用時才能註冊再接收廣播,所以當程式沒有運行就不能接受到廣播;但是靜態註冊的則不依賴於程式是否處於運行狀態。

當然動態註冊的好處是,自由靈活。

下面來看一下靜態註冊的代碼吧:

MainActivity.java:

package com.example.staticbroadcastreceiverdemo;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.os.SystemClock;public class MainActivity extends Activity {    private Handler myHandler;    //定義一個Intent,用於發送廣播;    private Intent myIntent;    //子線程標誌位;    private boolean tag = false;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.fragment_main);        //執行個體化Intent        myIntent = new Intent();        //設定過濾條件;        myIntent.setAction("com.vrinux.static");        //此處我使用一個Handler,接收子線程每隔3秒發來一次訊息,        //就發送一個廣播,並將值發出去;        myHandler = new Handler() {            @Override            public void handleMessage(Message msg) {                // TODO Auto-generated method stub                super.handleMessage(msg);                int count = msg.arg1;                myIntent.putExtra("text", "來自activity的廣播~" + count);                //發送廣播;                sendBroadcast(myIntent);            }        };        new Thread(new Runnable() {            int count = 0;            @Override            public void run() {                // TODO Auto-generated method stub                //將標誌位值設為true;                tag = true;                while (tag) {                    Message msg = Message.obtain();                    msg.arg1 = count;                    myHandler.sendMessage(msg);                    SystemClock.sleep(3000);                    count += 1;                }            }        }).start();    }    @Override    protected void onDestroy() {        // TODO Auto-generated method stub        super.onDestroy();        //當Activity銷毀時,將標誌位設定為false;        //如果不設定為false,則會看到程式退出後手機螢幕上仍然有Toast顯示資訊;        //從這點可以看出:1.線程啟動後不會隨著Activity銷毀而銷毀;        //                      2.靜態註冊的廣播比依賴於程式是否處於運行狀態;        if(tag){            tag = false;        }           }}

PlaneBroadcastReceiver.java:

package com.example.staticbroadcastreceiverdemo;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;import android.widget.Toast;//繼承BroadcastReceiver類;public class PlaneBroadcastReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        // TODO Auto-generated method stub        Log.i("MainActivity","PlaneBroadcastReceiver");        //擷取intent傳來的值;        String text = intent.getStringExtra("text");        //通過Toast顯示在螢幕上;        Toast.makeText(context, text, Toast.LENGTH_LONG).show();;    }}

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.staticbroadcastreceiverdemo"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="14"        android:targetSdkVersion="15" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.staticbroadcastreceiverdemo.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>        <!-- 註冊BroadcastReceiver,並設定過濾器和過濾條件 -->        <receiver            android:name=".PlaneBroadcastReceiver"            android:enabled="true" >            <intent-filter>                <action android:name="com.vrinux.static" />            </intent-filter>        </receiver>    </application></manifest>

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.