问题
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