[Android] 取得Device目前電池電量
(How to get current battery level)
Android系統會在電池狀態發生變化時,發出System broadcast intent,會附帶電池狀態、電量、溫度等內容,APP要取得電池電量就必須註冊BroadcastReceiver來接收此intent。
程式碼說明
一、建立BroadcastReceiver物件,實作其onReceive()方法
private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { int lv=intent.getIntExtra("level",0); batteryLevelTxt.setText(String.valueOf(lv)+"%"); } };二、註冊BroadcastReceiver,filter設定為ACTION_BATTERY_CHANGED,它將會在電池狀態改變時觸發其onReceive方法
package com.batteryDemo; import android.app.Activity; 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.widget.TextView; public class BatteryDemoActivity extends Activity { private TextView batteryLevelTxt; private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context context,Intent intent){ int lv=intent.getIntExtra("level",0); batteryLevelTxt.setText(String.valueOf(lv)+"%"); } }; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); batteryLevelTxt=(TextView)findViewById(R.id.LevelTxt); this.registerReceiver(batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); } }
留言
張貼留言