定期WorkManager无需等待图像下载完成即可设置墙纸

时间:2018-09-06 18:59:34

标签: android rx-java rx-java2 android-workmanager

我正在使用Periodic WorkManager,但是每隔X分钟自动更新墙纸。但是我面临的问题是,当调用' downloadWallpaper '方法下载图像时,它同时进入下一个方法' setWallpaper ',而无需等待图像加载完成。如何在将图片设置为墙纸之前添加等待图像下载完成?

在活动中,我正在使用 AyncTask ,但是WorkManager不需要它。另一种选择是使用RxJava的 blockingGet 方法,但是如何将其与我的 downloadWallpaper 方法一起使用?以下是代码:

import androidx.work.Worker;

public class WallpaperChangeWorker extends Worker {
    protected final Result[] workerResult = {Result.SUCCESS};
    private String filePath;


    protected void setWorkerResult(Result result) {
        workerResult[0] = result;
    }

    @NonNull
    @Override
    public Result doWork() {
        prf = new PrefManager(getApplicationContext());
        wallpaperList = new ArrayList<>();

                loadFavorites();

        return workerResult[0];
    }

    private void downloadWallpaper(Wallpaper wallpaper) {
        title = wallpaper.getTitle();
        extension = wallpaper.getExtension();

        int count;
        try {
            URL url = new URL(wallpaper.getWallpaper());
            URLConnection conection = url.openConnection();
            conection.connect();
            // this will be useful so that you can show a tipical 0-100% progress bar
            int lengthOfFile = conection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            String dir_path = Environment.getExternalStorageDirectory().toString() + getApplicationContext().getResources().getString(R.string.DownloadFolder);

            if (!dir_exists(dir_path)) {
                File directory = new File(dir_path);
                if (directory.mkdirs()) {
                    Log.v("dir", "is created 1");
                } else {
                    Log.v("dir", "not created 1");

                }
                if (directory.mkdir()) {
                    Log.v("dir", "is created 2");
                } else {
                    Log.v("dir", "not created 2");

                }
            } else {
                Log.v("dir", "is exist");
            }

            // Output stream
            OutputStream output = new FileOutputStream(dir_path + title.toString().replace("/", "_") + "." + extension);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                //   publishProgress(""+(int)((total*100)/lenghtOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();


            output.close();
            input.close();
            MediaScannerConnection.scanFile(getApplicationContext(), new String[]{dir_path + title.toString().replace("/", "_") + "." + extension},
                    null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(String path, Uri uri) {

                        }
                    });
            /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                final Uri contentUri = Uri.fromFile(new File(dir_path + title.toString().replace("/", "_") + "." + extension));
                scanIntent.setData(contentUri);
                sendBroadcast(scanIntent);
            } else {
                final Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()));
                sendBroadcast(intent);
            }*/
            filePath = dir_path + title.toString().replace("/", "_") + "." + extension;

            setWallpaper();

        } catch (Exception e) {

            setWorkerResult(Result.FAILURE);
        }
    }

    private void setWallpaper() {

        WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());

        wallpaperManager.setWallpaperOffsetSteps(1, 1);
        wallpaperManager.suggestDesiredDimensions(width, height);
   wallpaperManager.setBitmap(bitmap);

            setWorkerResult(Result.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            setWorkerResult(Result.RETRY);
        }
    }

    private boolean dir_exists(String dir_path) {
        boolean ret = false;
        File dir = new File(dir_path);
        if (dir.exists() && dir.isDirectory())
            ret = true;
        return ret;
    }

    private Bitmap loadBitmap(Uri src) {

        Bitmap bm = null;

        try {
            bm = BitmapFactory.decodeStream(
                    getApplicationContext().getContentResolver().openInputStream(src));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return bm;
    }


    private void loadFavorites() {
        final FavoritesStorage storageFavorites = new FavoritesStorage(getApplicationContext());
        wallpaperList = storageFavorites.loadFavorites();

        if (wallpaperList.size() > 0) {
            downloadWallpaper(wallpaperList.get(0));
        } else {
            setWorkerResult(Result.FAILURE);
        }

    }
}

1 个答案:

答案 0 :(得分:0)

您可以编写将墙纸下载和设置为不同的作品,并按顺序进行:

OneTimeWorkRequest download = new OneTimeWorkRequest.Builder(MyWorker.class).build();
OneTimeWorkRequest set = new OneTimeWorkRequest.Builder(MyWorker2.class).build();

WorkManager.getInstance()
   .beginWith(download)
   .then(set)
   .enqueue();

或者您可以使用此构造

private final Object lock = new Object();
public void setImage(){
    synchronized (lock){
        lock.wait();
    }
    //wallpaperManager.setBitmap and etc work
}

,当您收到有关文件加载完成的回调时,请致电lock.notify() 但我认为这不是最好的变体,您可以继续搜索更好的体系结构或组织下载的方式。 但是wait()方法的优点-该方法不消耗资源