How to set image as wallpaper programmatically?
Asked Answered
C

2

6

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?

Crosby answered 15/4, 2012 at 7:21 Comment(1)
is there an exception thrown?Antimonous
G
4

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);
    }
Guide answered 26/6, 2012 at 9:27 Comment(0)
D
1
File f = new File(Environment.getExternalStorageDirectory(), "1.jpg");
String path = f.getAbsolutePath();
File f1 = new File(path);

if(f1.exists()) {
    Bitmap bmp = BitmapFactory.decodeFile(path);
    BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
    WallpaperManager m=WallpaperManager.getInstance(this);

    try {
        m.setBitmap(bmp);
    } catch (IOException e) {
        e.printStackTrace();
    }
} 

Open Androidmanifest.xml file and add permission like..

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

Try this and let me know what happen..

Dirac answered 4/6, 2012 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.