set Wallpaper to a Bitmap by its resource ID - Android android.graphics

Android examples for android.graphics:Bitmap Operation

Description

set Wallpaper to a Bitmap by its resource ID

Demo Code


//package com.java2s;
import java.io.IOException;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Main {
    public static void setWallpaper(Context context, int resId)
            throws IOException {

        context.enforceCallingOrSelfPermission(
                android.Manifest.permission.SET_WALLPAPER,
                "need permission: SET_WALLPAPER");
        WallpaperManager wallpaperManager = WallpaperManager
                .getInstance(context);//from w  w  w .  jav  a2s.com
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        Bitmap wallpaper = BitmapFactory.decodeResource(
                context.getResources(), resId, options);

        if (wallpaperManager.getDesiredMinimumWidth() > wallpaper
                .getWidth()
                && wallpaperManager.getDesiredMinimumHeight() > wallpaper
                        .getHeight()) {
            int xPadding = Math.max(
                    0,
                    wallpaperManager.getDesiredMinimumWidth()
                            - wallpaper.getWidth()) / 2;
            int yPadding = Math.max(
                    0,
                    wallpaperManager.getDesiredMinimumHeight()
                            - wallpaper.getHeight()) / 2;
            Bitmap paddedWallpaper = Bitmap.createBitmap(
                    wallpaperManager.getDesiredMinimumWidth(),
                    wallpaperManager.getDesiredMinimumHeight(),
                    Bitmap.Config.ARGB_8888);
            int[] pixels = new int[wallpaper.getWidth()
                    * wallpaper.getHeight()];
            wallpaper.getPixels(pixels, 0, wallpaper.getWidth(), 0, 0,
                    wallpaper.getWidth(), wallpaper.getHeight());
            paddedWallpaper.setPixels(pixels, 0, wallpaper.getWidth(),
                    xPadding, yPadding, wallpaper.getWidth(),
                    wallpaper.getHeight());

            wallpaperManager.setBitmap(paddedWallpaper);
        } else {
            wallpaperManager.setBitmap(wallpaper);
        }
    }
}

Related Tutorials