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笔记(https://www.geekapp.cn/)。

原创博客,转载请标明出处:https://www.geekapp.cn/archives/160.html
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇