android获得手机的电量

  在android中,要获得手机的电量的话,可以通过intent广播去实现,监听
action_battery_changed,例子如下:

package com.liao;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;

public class BatteryLevelActivity extends Activity {
    /** Called when the activity is first created. */
    private TextView batterLevel;

    @Override
    /**
     * Called when the current activity is first created.
     */
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        batterLevel = (TextView) this.findViewById(R.id.batteryLevel);
        batteryLevel();
    }

      private void batteryLevel() {
        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;
                }
                batterLevel.setText("Battery Level Remaining: " + level + "%");
            }
        };
        IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryLevelReceiver, batteryLevelFilter);
    }
    
}


  如果是2。0后的SDK,也可以这样:
public void onReceive(Context context, Intent intent) {
            
context.unregisterReceiver(this);
            
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

就是修改一下类而已

你可能感兴趣的:(android,battery)