Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發:輕鬆讀取電池各項資訊

編輯:關於 Android 程式設計

想讓 App 顯示目前電池的電量、電壓、溫度與類型嗎?Android 提供了 ACTION_BATTERY_CHANGED 這個系統廣播,透過自訂的 BroadcastReceiver 就能輕鬆取得這些資訊。以下一步步示範。

1、撰寫電池資訊的廣播接收器

建立 BatteryInfoBroadcastReceiver,攔截電池狀態變化的廣播,並用對話框把各項數據呈現出來。

 package org.lxh.demo; import android.app.AlertDialog; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; public class BatteryInfoBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) { int level = intent.getIntExtra(level, 0); int scale = intent.getIntExtra(scale, 0); int voltage = intent.getIntExtra(voltage, 0); int temperature = intent.getIntExtra(temperature, 0); String technology = intent.getStringExtra(technology); Dialog dialog = new AlertDialog.Builder(context) .setTitle(電池電量) .setMessage( 電池電量為: + String.valueOf(level * 100 / scale) + % + 電池電壓為: + String.valueOf((float)voltage / 1000) + v + 電池類型為: + technology + + 電池溫度為: + String.valueOf((float)temperature / 10) + °C) .setNegativeButton(關閉, new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { } }).create(); dialog.show(); } } } 

2、編寫版面配置 main.xml

畫面上放一顆按鈕,點擊後觸發電池資訊的讀取。

  

3、撰寫 Activity

在按鈕的點擊事件中註冊廣播接收器,並過濾電池狀態變化的 Action。

 package org.lxh.demo; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Hello extends Activity { private Button mybtn = null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 生命周期方法 super.setContentView(R.layout.main); // 設置要使用的布局管理器 this.mybtn = (Button) super.findViewById(R.id.mybtn); this.mybtn.setOnClickListener(new OnClickListenerImpl()); } private class OnClickListenerImpl implements OnClickListener { public void onClick(View v) { BatteryInfoBroadcastReceiver receiver = null; receiver = new BatteryInfoBroadcastReceiver(); IntentFilter filter = new IntentFilter( Intent.ACTION_BATTERY_CHANGED); Hello.this.registerReceiver(receiver, filter); } } }

在真機上執行後,即可看到如下的顯示效果:

透過這個範例可以發現,只要善用系統廣播,就能以極少的程式碼取得豐富的裝置狀態資訊。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved