使用WorkManager关闭应用程序后如何运行后台服务?

时间:2019-02-19 12:03:43

标签: java android

以前,我尝试使用WorkManager运行后台服务,我使用的请求是OneTimeWorkRequest和PeriodicWorkRequest。

当我尝试PeriodicWorkRequest时,出现了一个奇怪的情况,奇怪的是,当我关闭应用程序时,该服务停止了,但是当我重新打开该应用程序时,该服务又返回了。

Constraints.Builder constraint = new Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED);

Data.Builder data = new Data.Builder();
data.putString("url", "https://html5demos.com/assets/dizzy.mp4");

WorkRequest request = new PeriodicWorkRequest.Builder(BackgroundDownloadService.class, 12,
            TimeUnit.HOURS)
            .setInputData(data.build())
            .setConstraints(constraint.build())
            .build();

WorkManager.getInstance().enqueue(request);

BackgroundDownloadService.java:

public class BackgroundDownloadService extends Worker {
    private Context context;
    private NotificationCompat.Builder notificationBuilder;
    private NotificationManager notificationManager;

    @Override
    public WorkerResult doWork() {
        context = getApplicationContext();
        Data data = getInputData();
        String url = "";
        if(data != null) {
            url = data.getString("url", "");
        }
        String mainName = "renaldi";
        String mimeType = url.substring(url.length()-4);
        String namePath = mainName + "Files-"+changeFormat(new Date())+mimeType;

        notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        createNotification();

        AndroidNetworking.initialize(context);

        AndroidNetworking.download(url, context.getExternalFilesDir(DIRECTORY_DOWNLOADS)+"/video/"  , namePath)
                .setTag("download")
                .setPriority(Priority.HIGH)
                .build()
                .setDownloadProgressListener(new DownloadProgressListener() {
                    @Override
                    public void onProgress(long bytesDownloaded, long totalBytes) {
                        final int dl_progress = (int) ((bytesDownloaded * 100l) / totalBytes);
                        updateNotification(dl_progress);
                    }
                })
                .startDownload(new DownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                        onDownloadCompleted();
                    }
                    @Override
                    public void onError(ANError error) {
                    }
                });

        return WorkerResult.SUCCESS;
    }

    public String changeFormat(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("HHmmssSSS");
        String dateFormat = format.format(date);
        return dateFormat;
    }

    private void updateNotification(int currentProgress) {
        notificationBuilder.setProgress(100, currentProgress, false);
        notificationBuilder.setContentText("Downloaded: " + currentProgress + "%");
        notificationManager.notify(0, notificationBuilder.build());
    }

    private void onDownloadCompleted() {
        notificationManager.cancel(0);
        notificationBuilder.setProgress(0, 0, false);
        notificationBuilder.setContentText("Video Download Complete");
        notificationManager.notify(0, notificationBuilder.build());

    }

    private void createNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel("id", "an", NotificationManager.IMPORTANCE_LOW);

            notificationChannel.setDescription("no sound");
            notificationChannel.setSound(null, null);
            notificationChannel.enableLights(false);
            notificationChannel.setLightColor(Color.BLUE);
            notificationChannel.enableVibration(false);
            notificationManager.createNotificationChannel(notificationChannel);
        }

        notificationBuilder = new NotificationCompat.Builder(context, "id")
                .setSmallIcon(android.R.drawable.stat_sys_download)
                .setContentTitle("Download")
                .setContentText("Downloading Video")
                .setDefaults(0)
                .setAutoCancel(true);
        notificationManager.notify(0, notificationBuilder.build());
    }
}

您是否为我提供了一种使用Workmanager关闭应用程序时运行后台服务的解决方案?

1 个答案:

答案 0 :(得分:0)

根据Worker API文档:

  

此方法(Worker类的doWork())用于同步处理您的工作,这意味着   从该方法返回后,该工作人员即被视为   完成并将会销毁。如果您需要工作   异步调用异步 API,您应该使用    ListenableWorker

因此请考虑扩展ListenableWorker而不是Worker,然后看看它是如何工作的。

相关问题