How to set image as wallpaper programmatically?

前端 未结 2 925
心在旅途
心在旅途 2021-01-12 21:43

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

Code:

WallpaperManager m=WallpaperManager.getInstan         


        
相关标签:
2条回答
  • 2021-01-12 22:12
    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..

    0 讨论(0)
  • 2021-01-12 22:17

    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);
        }
    
    0 讨论(0)
提交回复
热议问题