代码之家  ›  专栏  ›  技术社区  ›  Usman Rana

定期WorkManager不会等到图像下载完成后才设置壁纸

  •  1
  • Usman Rana  · 技术社区  · 6 年前

    我正在使用定期WorkManager,但每x分钟自动更新一次墙纸。但我面临的问题是 下载壁纸 '调用方法下载图像,同时进入下一个方法' 布景壁纸 '无需等待图像加载完成。如何添加“等待图像下载完成”,然后再将其设置为壁纸?

    在活动中,我使用 AyncTask ,但WorkManager不需要。另一个选择是使用 封锁 RxJava的方法,但如何将其用于我的 下载壁纸 方法代码如下:

    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 回复  |  直到 6 年前
        1
  •  0
  •   Олег Котенко    6 年前

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

    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() 方法——方法不消耗资源