Search code examples
androidwallpaperandroid-wallpaper

I cannot change Android wallpaper using WallpaperManager


I am trying to change Android wallpaper using code. I am using the WallpaperManager class, but with no prevail. I used a .png image in the /drawable directory. I am getting an error that says, "Expected resource of type raw". When I run the application(when that method runs), it crashes. I must be victim of a really stupid mistake. The method changeWallpaper() is run after the user taps a button. Here is my code:

 public void changeWallpaper(View view) {

    try{
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
        wallpaperManager.setResource(R.drawable.material_wallpaper);
        String successMessage = "Wallpaper Changes";
        Toast.makeText(this, successMessage, Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
        String failedMessage = "Operation failed";
        Toast.makeText(this, failedMessage, Toast.LENGTH_SHORT).show();
    }

}

EDIT: There is no "raw" folder in my /res/ directory.


Solution

  • If you want to stay with Drawable, you can convert the resource into a Bitmap and then set it as wallpaper by using setBitmap(Bitmap _bitmap) (see WallpaperManager).

    WallpaperManager wallpaperManager = WallpaperManager.getInstance(getActivity().getApplicationContext());
    Bitmap bitmap = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.material_wallpaper);
    wallpaperManager.setBitmap(bitmap);