首页 > 解决方案 > 应用程序被杀死时如何运行 Android Worker?

问题描述

我目前正在设备上录制视频,压缩此视频,然后使用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());
                            }

                        }
                    });

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

标签: androidandroid-workmanager

解决方案


推荐阅读