首页 > 解决方案 > 如果设备正在充电且电池电量已满,如何开始活动?

问题描述

当设备正在充电并且电池电量达到 100%(或接近它,比如 95% 以上)时,我需要开始一项活动。应用程序正在打开或关闭。

当充电器插入并检查电池电量时,我可以触发广播接收器,但如果它不在我想要的范围内,什么都不会发生。但这是我能做到的。我不知道如何继续监视它,直到它达到所需的电池电量而不在活动上运行任务。我需要在后台发生这种情况。

标签: androidandroid-broadcastreceiver

解决方案


检查设备是否正在使用此方法充电

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
}

推荐阅读