Search code examples
androidandroid-wallpaper

Android - Setting wallpaper from file path takes longer than expected


I'm trying to set wallpaper from file path. However it takes more than 10 seconds and causes my app to freeze.

Here's the code I'm using:

public void SET_WALLPAPER_FROM_FILE_PATH (String file_path)
{
    Bitmap image_bitmap;
    File   image_file;
    FileInputStream fis;

    try {
        WallpaperManager wallpaper_manager = WallpaperManager.getInstance(m_context);
        image_file                         = new File(file_path);
        fis                                = new FileInputStream(image_file);
        image_bitmap                       = BitmapFactory.decodeStream(fis);

        wallpaper_manager.setBitmap(image_bitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I have tried to use:

wallpaper_manager.setStream(fis)

instead of:

wallpaper_manager.setBitmap(image_bitmap);

as suggested in this answer but couldn't load the wallpaper.

Can anyone guide me?

Thanks


Solution

  • Try to use AsyncTask, in doInBackground method write something like this

    public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
        try {
            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);
    
            //The new size we want to scale to
            final int REQUIRED_WIDTH=WIDTH;
            final int REQUIRED_HIGHT=HIGHT;
            //Find the correct scale value. It should be the power of 2.
            int scale=1;
            while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
                scale*=2;
    
            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        }
            catch (FileNotFoundException e) {}
        return null;
    }