1. 程式人生 > >Android的廣播機制基礎1---動態註冊監聽的使用,以獲得電池的使用狀態為例

Android的廣播機制基礎1---動態註冊監聽的使用,以獲得電池的使用狀態為例

以一個顯示手機電量和電池狀態的Demo為例。
1.要獲得電池的使用狀態,需在AndroidManifest.xml中新增使用許可權:

<uses-permission android:name="android.permission.BATTERY_STATS"/>

2.廣播有傳送方和接收方,接收方為BroadCastReceiver的例項或其子類
3.首先我們寫出activity的佈局檔案:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
//電池電量 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/current" android:textSize="30sp"/> <ProgressBar
android:layout_width="match_parent" android:layout_height="20dp" style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal" android:id="@+id/progressbar"/>
//電池充電狀態 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textSize="30sp" android:id="@+id/battryeStatus"/>
//電池健康狀態 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/batteryHealth" android:textSize="30sp"/> </LinearLayout>

4.activity實現部分

package com.example.apple.broadcast.BatteryMonitor;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.apple.broadcast.R;

/**
 * Created by apple on 2018/6/6.
 */

public class BatteryMonitorActivity extends AppCompatActivity {

    private TextView tv_level,tv_status,tv_health;
    private ProgressBar progressbar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.battry_layout);
//初始化控制元件
        tv_level=(TextView)findViewById(R.id.current);
        tv_health=(TextView)findViewById(R.id.batteryHealth);
        tv_status=(TextView)findViewById(R.id.battryeStatus);
        progressbar=(ProgressBar)findViewById(R.id.progressbar);
        progressbar.setMax(100);
    }
//註冊廣播
    @Override
    protected void onResume() {
        super.onResume();
        //IntentFilter傳遞相應的action
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        //註冊傳入引數為BroadcastReceiver和Intentfilter的例項
        registerReceiver(mBroadcastReceiver,intentFilter);

    }
//取消廣播
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

//BroadcastReceiver的例項,也可以用BroadcastReceiver的子類實現,書寫一個內部類,要重寫父類的onReceive方法
    private BroadcastReceiver mBroadcastReceiver=new BroadcastReceiver() {
    //Int 型別值用來判斷電池的狀態
        int health,level,status;
        @Override
        public void onReceive(Context context, Intent intent) {
        //獲取廣播的action
            String action=intent.getAction();
            //如果電池電量改變
            if(action==Intent.ACTION_BATTERY_CHANGED){
          level=intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);

//電池的充電狀態,預設為未充電    
            status=intent.getIntExtra(BatteryManager.EXTRA_STATUS,BatteryManager.BATTERY_STATUS_DISCHARGING);

 //獲取電池的健康狀態
                health=intent.getIntExtra(BatteryManager.EXTRA_HEALTH,BatteryManager.BATTERY_HEALTH_GOOD);
            }

            changeBattry(health,level,status);
        }
    };
//改變佈局,將狀態變化顯示在佈局檔案中
    private void changeBattry(int health, int level, int status) {
        tv_level.setText("當前電量為:"+level+"%");
        progressbar.setProgress(level);
        if(status==BatteryManager.BATTERY_STATUS_CHARGING){
            tv_status.setText("充電狀況:正在充電");
        }else if(status==BatteryManager.BATTERY_STATUS_DISCHARGING){
            tv_status.setText("充電狀況:未充電");
        }

        if(health==BatteryManager.BATTERY_HEALTH_GOOD){
            tv_health.setText("電池狀況:Good");
        }else if(health==BatteryManager.BATTERY_HEALTH_UNKNOWN){
            tv_health.setText("電池狀況:unkown");
        }else if(health==BatteryManager.BATTERY_HEALTH_DEAD){
            tv_health.setText("電池狀況:Dead");
        }
    }
}

這裡寫圖片描述