I cannot change Android wallpaper using WallpaperManager

泄露秘密 提交于 2019-12-08 07:53:28

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/29089472/i-cannot-change-android-wallpaper-using-wallpapermanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!