6

我想在我的应用中显示电池电量统计信息。我们如何获得电池电量、电池电压等信息?

4

2 回答 2

3
   BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            context.unregisterReceiver(this);
            int rawlevel = intent.getIntExtra("level", -1);
            int scale = intent.getIntExtra("scale", -1);
            int level = -1;
            if (rawlevel >= 0 && scale > 0) {
                level = (rawlevel * 100) / scale; /* This is your battery level */ 
            }
         }
    };
    IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}

或查看这个人(他编写了我发布的代码): http: //mihaifonoage.blogspot.com/2010/02/getting-battery-level-in-android-using.html

于 2010-02-15T13:21:12.050 回答
3

这有什么帮助吗?

public class Main extends Activity {
   private TextView contentTxt;
   private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
      @Override
      public void onReceive(Context arg0, Intent intent) {
         // TODO Auto-generated method stub
         int level = intent.getIntExtra("level", 0);
         contentTxt.setText(String.valueOf(level) + "%");
      }
   };

   @Override
   public void onCreate(Bundle icicle) {
      super.onCreate(icicle);
      setContentView(R.layout.main);
      contentTxt = (TextView) this.findViewById(R.id.monospaceTxt);
      this.registerReceiver(this.mBatInfoReceiver, 
         new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
   }
}

另外,请参阅

于 2010-02-15T13:22:05.580 回答