Android Periodical WorkManager不触发

时间:2019-05-07 17:06:42

标签: android backgroundworker android-workmanager

此定期工作管理器任务似乎未执行。 为了进行测试,我简化了下面的googleFitHelper.syncData方法,使其仅使用Volley框架访问URL(帖子)。

manifest已设置android.permission.INTERNETmanifest没有与workmanager任务相关的其他参数。

要测试,当访问URL时,我正在服务器上写日志。

我想念什么吗?

注意:该任务按预期OneTimeWorkRequest运行。

class MainActivty {
    ...

    private void scheduleSyncJobService(){
        SyncWorkManagerUtility syncWorkManagerUtility = new SyncWorkManagerUtility();
        syncWorkManagerUtility.scheduleJob();
    }
}



class SyncWorkManagerUtility {
    private static final String TAG = SyncWorkManagerUtility.class.getSimpleName();
    private static final String SYNC_WORK_JOB1 = "SYNC_WORK_JOB1";

    void scheduleJob() {
        Constraints constraints = new Constraints.Builder()
        .setRequiresDeviceIdle(true)
        .setRequiredNetworkType(NetworkType.CONNECTED)
        .build();

    PeriodicWorkRequest syncRequest =
        new PeriodicWorkRequest.Builder(SyncWorkManagerService.class, 15, TimeUnit.MINUTES)
            .addTag(SYNC_WORK_JOB1)
            .setConstraints(constraints)
            .build();
            Log.d(TAG, "Scheduling Job " + SYNC_WORK_JOB1);
            WorkManager.getInstance().enqueueUniquePeriodicWork(SYNC_WORK_JOB1, ExistingPeriodicWorkPolicy.REPLACE, syncRequest);
    }
}


public class SyncWorkManagerService extends Worker {
    ...

    @Override
    public Result doWork() {
        GoogleFitHelper googleFitHelper = new GoogleFitHelper(getApplicationContext());
        googleFitHelper.syncData();
        return Result.success();
    }
}

public class GoogleFitHelper {
    ....

    void syncData(){
        String url="https://example.com/testbackgroundtask.php";
        StringRequest strRequest = new StringRequest(Request.Method.POST, url,
        responseString -> {},
        error -> {}) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("testdataA", "testdataA");
                params.put("testdataB", "testdataB");
                return params;
            }

            @Override
            public Map<String, String> getHeaders() {
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                return headers;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                return super.parseNetworkResponse(response);
            }
    };
    VolleyRequestQueue.getInstance(context).addToRequestQueue(strRequest);
}

1 个答案:

答案 0 :(得分:0)

您正在同步Worker中执行异步请求。尝试改用ListenableWorker。