android - 如果设备正在充电且电池电量已满,如何开始活动?
问题描述
当设备正在充电并且电池电量达到 100%(或接近它,比如 95% 以上)时,我需要开始一项活动。应用程序正在打开或关闭。
当充电器插入并检查电池电量时,我可以触发广播接收器,但如果它不在我想要的范围内,什么都不会发生。但这是我能做到的。我不知道如何继续监视它,直到它达到所需的电池电量而不在活动上运行任务。我需要在后台发生这种情况。
解决方案
检查设备是否正在使用此方法充电
public static boolean isCharging(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
BatteryManager batteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
return batteryManager.isCharging();
} else {
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent intent = context.registerReceiver(null, filter);
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
if (status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL) {
return true;
}
}
return false;
}
使用此方法获取电池百分比
public static int getBatteryPercentage(Context context) {
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, iFilter);
int level = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1;
int scale = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1;
float batteryPct = level / (float) scale;
return (int) (batteryPct * 100);
}
然后检查
if(isCharging(getContext()) && getBatteryPercentage(getContext()) == 100){
//start your activity here
}
推荐阅读
- angular - 带有路由的角度导航栏中的问题
- java - Spring Boot 项目不在 Gradle 本地存储库上运行
- assembly - 为什么我在火星上得到“无效的程序计数器值”?
- javascript - react-map-gl中的动画geojson位置
- mysql - MySQL Sakila DB,获取类别列表并计算出现次数最多的演员
- python - 如何将熊猫数据框保存到分区的 JSON 中
- asp.net-core - asp.net 核心身份服务器 4 仅接受请求的三个自定义域之一
- ios - iOS 中的 Flutter_root 未显示
- reactjs - TypeError:无法读取未定义的属性“searchField”
- python - Python中的对数似然和梯度函数实现