分类
Android开发

Android监控手机电池电量

以下这个工具类BatteryMonitorUtil可以获取android手机电池电量:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.PowerManager;
import android.util.Log;

/**
* 监测电池电量
* @author Administrator
*
*/
public class BatteryMonitorUtil {

//需要添加权限
//

private static final String TAG = "BatteryUtil";
private static BatteryMonitorUtil mInstance = null;
private static Context mContext = null;
private static BroadcastReceiver mReceiver = null;
private IntentFilter mFilter = null;
private PowerManager.WakeLock mWakeLock = null;
private boolean isRegister = false;

private int rawlevel = -1;
private int scale = -1;
private int status = -1;
private int health = -1;
private int level = -1;//电量满为100

private BatteryMonitorUtil(){
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
rawlevel = intent.getIntExtra("level", -1);
scale = intent.getIntExtra("scale", -1);
status = intent.getIntExtra("status", -1);
health = intent.getIntExtra("health", -1);
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
Log.i(TAG, "rawlevel:"+rawlevel+" scale:"+scale+" status:"+status+" health:"+health+" level:"+level);
}
};

PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "BatteryMonitorUtil");
mWakeLock.setReferenceCounted(false);
}

/**
* 获取程序实例
* @return
*/
public static BatteryMonitorUtil getInstance(Context context){
mContext = context;
if(mInstance == null){
mInstance = new BatteryMonitorUtil();
}
return mInstance;
}

/**
* 开始监听
*/
public void start(){
if(isRegister){
return;
}
mFilter = new IntentFilter();
mFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
mFilter.addAction(Intent.ACTION_BATTERY_LOW);
mFilter.addAction(Intent.ACTION_BATTERY_OKAY);
mFilter.addAction(Intent.ACTION_POWER_CONNECTED);
mContext.registerReceiver(mReceiver, mFilter);
isRegister = true;
mWakeLock.acquire();
}

/**
* 停止监听
*/
public void stop(){
if(!isRegister){
return;
}
mContext.unregisterReceiver(mReceiver);
isRegister = false;
mWakeLock.release();
}

public int getLevel() {
return level;
}

public int getStatus(){
return status;
}
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

发表评论

电子邮件地址不会被公开。 必填项已用*标注