当前位置:操作系统 > 安卓/Android >>

android获得手机的电量

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

Java代码 
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 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,