2012年5月30日 星期三

[Android] [JAVA] 顯示剩餘電量的AP

1). 在主程式中,建立BroadcastReceiver類型的變數,利用BatteryManager讀出電量的資料

2). 註冊receive,僅有此可以利外寫在這,而不用寫在AndroidManifest.xml

//=============================================================
package com.broadcasttest2;
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 BroadcastTest2 extends Activity {
  private TextView BatteryChange;
  private BroadcastReceiver batteryReceiver = new 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", 100);
      // 也可以寫成這樣
      //int voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 100);
    BatteryChange.setText("電池用量" + (level * 100 / scale) + "%" );
    }
  }
 };
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  BatteryChange = (TextView) findViewById(R.id.battery);
  registerReceiver(batteryReceiver, new IntentFilter(
  Intent.ACTION_BATTERY_CHANGED));
 }
}

沒有留言:

張貼留言