我有一个项目,我想在电池充满电后在WorkManager中运行任务。我几乎到处搜索,但找不到任何解决方案。

@NonNull
@Override
public Result doWork() {

    //I want to run this task when battery is full.

    if(BatteryManager.BATTERY_STATUS_CHARGING==100) {
          showNotification();
    }

    return Result.success();
}


和启动WorkManager的代码片段:

private void startWorkManager() {


    Constraints constraints = new Constraints.Builder()
        .setRequiresBatteryNotLow(true)
        .setRequiresCharging(true)
        .build();

    PeriodicWorkRequest periodicWorkRequest= new
            PeriodicWorkRequest.Builder(NotificationWork.class
    ,15,TimeUnit.MINUTES)
            .setConstraints(constraints)
            .build();

    WorkManager.getInstance().enqueue(periodicWorkRequest);
}


更新承包商

公共NotificationWork(@NonNull上下文上下文,@NonNull WorkerParameters workerParams){
超级(上下文,workerParams);
this.context =上下文;

}

public double batteryLevel(Context context){

    Intent batteryIntent = context.getApplicationContext().registerReceiver(null,
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int rawlevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    double scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    double level = -1;
    if (rawlevel >= 0 && scale > 0) {
        level = rawlevel / scale;
    }
    return level;    //This will return the value in range of 0.0-1.0
}


@NonNull
@Override
public Result doWork() {

    if (batteryLevel(context) == 1.0) {  //1.0 means 100%

      showNotification();

        return Result.success();
    } else {
          return Result.retry();
    }
}

最佳答案

首先,在您的worker类中,创建一个batteryLevel(Context context)函数以获取电池电量。

public double batteryLevel(Context context){

    Intent batteryIntent = context.getApplicationContext().registerReceiver(null,
                new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int rawlevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    double scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    double level = -1;
    if (rawlevel >= 0 && scale > 0) {
        level = rawlevel / scale;
    }
    return level;    //This will return the value in range of 0.0-1.0
}


然后在doWork()方法中,检查电池电量是否为100%:

if (batteryLevel(context) == 1.0){  //1.0 means 100%
    //Do your stuff
    return Result.success()
}else{
    return Result.retry()
}


更新资料
创建一个类级别的上下文对象。

Context context;


使用以下参数初始化构造函数

public NotificationWork(@NonNull Context context, @NonNull WorkerParameters workerParams){
    super(context,workParams);
    this.context = context;
}

关于java - Android WorkManager-手机充满电后运行任务,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57737779/

10-10 19:54