Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android:動態注冊BroadcastReceiver

Android:動態注冊BroadcastReceiver

編輯:關於Android編程

注釋直接寫在代碼裡,比較直觀,我覺得這些定義系統的廣播的宏,不是很好使;

MainActivity.java:

package com.vrinux.broadcastdemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends Activity {

    //定義一個過濾器;
    private IntentFilter intentFilter;

    //定義一個廣播監聽器;
    private NetChangReceiver netChangReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);

        //實例化過濾器;
        intentFilter = new IntentFilter();
        //添加過濾的Action值;
        intentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);

        //實例化廣播監聽器;
        netChangReceiver = new NetChangReceiver();

        //將廣播監聽器和過濾器注冊在一起;
        registerReceiver(netChangReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        //銷毀Activity時取消注冊廣播監聽器;
        unregisterReceiver(netChangReceiver);
    }

    //創建一個繼承BroadcastReceiver的廣播監聽器;
    class NetChangReceiver extends BroadcastReceiver {

        //重寫onReceive方法,該方法的實體為,接收到廣播後的執行代碼;
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            Log.i("MainActivity", "飛行模式啟動~");

            Toast.makeText(MainActivity.this, "飛行模式啟動~", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved