方法和獲得連線、記憶卡資訊一樣,用收廣播的方式來獲得資訊,
以下是個小範例。
為了方便管理,宣告一個儲存資訊的小容器類別
public class BatteryStatus
{
public boolean m_bPresent; // 裝置是否有安裝電池?
public int m_nStatus; // 電源狀態(滿的?充電?)
public int m_nHealth; // 電池狀態(是否健康?)
public int m_nLevel; // 目前電量
public int m_nScale; // 總電量,通常為100
public int m_nPlugged; // 充電來源(AC或USB)
public int m_nVoltage; // 電壓
public int m_nTemperature; // 溫度
public String m_strTechnology; // 電池種類
void BatteryDtatus()
{
m_bPresent = false;
m_nStatus = m_nHealth = m_nLevel = m_nScale = 0;
m_nPlugged = m_nVoltage = m_nTemperature = 0;
m_strTechnology = "";
}
}
簡單的流程如下
import android.os.BatteryManager;
public class MainActivity extends Activity
{
private BatteryStatus m_bsMgr = new BatteryStatus();
private BroadcastReceiver mStatusListener = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
final String action = intent.getAction();
if (action.equals(Intent.ACTION_BATTERY_CHANGED))
{
changeBatteryMgr(intent);
}
}
};
@Override
public void onResume()
{
super.onResume();
IntentFilter f = new IntentFilter();
f.addAction(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(mStatusListener, new IntentFilter(f));
}
@Override
public void onPause()
{
super.onPause();
unregisterReceiver(mStatusListener);
}
@Override
public void onDestroy()
{
this.mStatusListener = null;
super.onDestroy();
}
private void changeBatteryMgr(Intent intent)
{
m_bsMgr.m_bPresent = intent.getBooleanExtra("present", false);
m_bsMgr.m_nStatus = intent.getIntExtra("status", 0);
m_bsMgr.m_nHealth = intent.getIntExtra("health", 0);
m_bsMgr.m_nLevel = intent.getIntExtra("level", 0);
m_bsMgr.m_nScale = intent.getIntExtra("scale", 0);
m_bsMgr.m_nPlugged = intent.getIntExtra("plugged", 0);
m_bsMgr.m_nVoltage = intent.getIntExtra("voltage", 0);
m_bsMgr.m_nTemperature = intent.getIntExtra("temperature", 0);
m_bsMgr.m_strTechnology = intent.getStringExtra("technology");
showBatteryInfo();
}
private void showBatteryInfo()
{
// 秀出 m_bsMgr 的資訊
}
}
除此之外,建議用 Handler 的方式控制一段時間更新一次資訊比較好,
畢竟電池狀態不常改,大多情況是電量有改變才會收到訊息,
有時要等一陣子才能看到畫面更新,讓人有不安的感覺,
倒不如用點其他方式讓用戶知道程式正常的在執行而非當在那不會動。
沒有留言:
張貼留言