Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set image as wallpaper programmatically?

I have been developing the application which need to set an image as wallpaper.

Code:

WallpaperManager m=WallpaperManager.getInstance(this);

String s=Environment.getExternalStorageDirectory().getAbsolutePath()+"/1.jpg";
File f=new File(s);
Log.e("exist", String.valueOf(f.exists()));
try {
        InputStream is=new BufferedInputStream(new FileInputStream(s));
        m.setBitmap(BitmapFactory.decodeFile(s));

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.e("File", e.getMessage());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.e("IO", e.getMessage());
    }

Also I have added the following permission:

<uses-permission android:name="android.permission.SET_WALLPAPER" />

But it doesn't works; the file exists on sdcard. Where have I made a mistake?

like image 824
user1166635 Avatar asked Apr 15 '12 07:04

user1166635


1 Answers

Possibly, you run out of memory if your image is big. You can make sure of it by reading Logcat logs. If this is the case, try to adjust your picture to device size by somewhat like this:

    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    int height = displayMetrics.heightPixels;
    int width = displayMetrics.widthPixels << 1; // best wallpaper width is twice screen width

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, width, height);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    Bitmap decodedSampleBitmap = BitmapFactory.decodeFile(path, options);

    WallpaperManager wm = WallpaperManager.getInstance(this);
    try {
        wm.setBitmap(decodedSampleBitmap);
    } catch (IOException e) {
        Log.e(TAG, "Cannot set image as wallpaper", e);
    }
like image 58
mbakulin Avatar answered Oct 28 '22 23:10

mbakulin