该应用被终止后,如何运行Android Worker?

时间:2018-10-12 11:29:28

标签: android android-workmanager

我当前正在在设备上录制视频,将其压缩,然后使用Retrofit 2将压缩后的视频上传到服务器。我还使用Worker类在后台执行所有这些操作。正在进行上传时,进度也会显示在notification bar中。我的问题是该应用被杀死时,整个上传过程停止。我试图返回WorkerResult.RETRY,它确实可以工作,但是它只是重复执行,因此一个文件被多次上传。代码如下:

工人阶级

public class UploadWorker extends Worker implements ProgressRequestBody.UploadCallBacks {

private static final String LOG_TAG = UploadWorker.class.getSimpleName();
public static final int UPDATE_PROGRESS = 8344;
Context context;
WorkerParameters parameters;
private static final String SERVER_PATH = "";
String filePath;

/*For notification update*/
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager;


public UploadWorker(Context context,
                    WorkerParameters parameters) {
    super(context, parameters);
    this.context = context;
    this.parameters = parameters;
}


@NonNull
@Override
public Result doWork() {

    showNotificationUpdate();

  compressVideo(getInputData().getString("currentPhotoPath");, 
  getInputData().getString("fileDestination"););

    constructFile(filePath);

    // Indicate success or failure with your return value:
    return Result.SUCCESS;


}

    private void uploadVideoToServer(File fileToUpload) {

    ProgressRequestBody fileBody = new ProgressRequestBody(fileToUpload, this);

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    MultipartBody.Part vFile = MultipartBody.Part.createFormData("fileToUpload", fileToUpload.getName(), fileBody);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(SERVER_PATH)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(provideClient())
            .build();

    VideoInterface vInterface = retrofit.create(VideoInterface.class);

    Call<ResponseBody> serverCom = vInterface.uploadVideo(vFile);

    serverCom.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            try {
                if (response.body() != null) {
                    Log.d(LOG_TAG, "Resposne == " + response.body().string());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.d(LOG_TAG, "Response In String == " + response);
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d(LOG_TAG, "Error == " + t.getLocalizedMessage());
        }
    });

}

@Override
public void onProgressUpdate(int percentage) {
    updateNotification(percentage);
}

@Override
public void onError() {
    sendProgressUpdate(false);
}

@Override
public void onFinish() {
    sendProgressUpdate(true);

    notificationManager.cancel(0);
    notificationBuilder.setProgress(0, 0, false);
    notificationBuilder.setContentTitle("Upload Done");
notificationBuilder.setSmallIcon(android.R.drawable.stat_sys_upload_done);
    notificationManager.notify(0, notificationBuilder.build());
}
}

这就是我在活动中设置工作人员的方式

 Data inputData = new Data.Builder()
                    .putString("currentPhotoPath", mCurrentPhotoPath)
                    .putString("fileDestination", f.getPath())
                    .build();

            Constraints constraints = new Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .setRequiresStorageNotLow(true)
                    .build();

            OneTimeWorkRequest compressionWork =
                    new OneTimeWorkRequest.Builder(UploadWorker.class)
                            .setConstraints(constraints)
                            .addTag("CompressVideo")
                            .setInputData(inputData)
                            .build();

            WorkManager.getInstance()
                    .enqueue(compressionWork);

            WorkManager.getInstance().getStatusById(compressionWork.getId())
                    .observe(this, new Observer<WorkStatus>() {
                        @Override
                        public void onChanged(@Nullable WorkStatus workStatus) {

                            Log.d(LOG_TAG, "WORKER STATE == " + workStatus.getState().name());

                            if (workStatus != null && workStatus.getState().isFinished()) {
                                Log.d(LOG_TAG, "Is WOrk Finished == " + workStatus.getState().isFinished());
                            }

                        }
                    });

有人可以帮我找到合适的解决方案,以便在关闭应用程序时,文件上传仍然继续并在完成后停止吗?

0 个答案:

没有答案