本篇主要讲下如何设置系统桌面壁纸.
1:WallpaperManager简介
WallpaperManager是Android系统提供的一个类,用于管理设备的壁纸(即桌面背景)。
通过WallpaperManager类,我们可以获取当前设备的壁纸信息,设置新的壁纸,以及监听壁纸的变化。
2:常用方法
WallpaperManager类提供了以下常用方法:
- getInstance(Context context):获取WallpaperManager的实例。
- getDrawable():获取当前设备的壁纸Drawable对象。
- setResource(int resid):设置壁纸为指定资源ID对应的图片。
- setBitmap(Bitmap bitmap):设置壁纸为指定的Bitmap对象。
- clear():清除当前设备的壁纸,恢复为默认壁纸。
- getWallpaperInfo():获取当前设备壁纸的信息。
代码如下:
public static void setLauncherWallPaper(Context context, Bitmap bitmap) throws IOException {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
final int result;
try {
result = WallpaperManager.getInstance(context).setBitmap(bitmap, null, false, WallpaperManager.FLAG_SYSTEM);
} catch (Throwable e) {
throw new IOException(e);
}
if (result == 0) {
throw new IOException(“setLauncherWallPaper failed”);
}
} else {
try {
WallpaperManager.getInstance(context).setBitmap(bitmap);
} catch (Throwable e) {
throw new IOException(e);
}
}
}
本地调用如下:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.wallpaper);
try {
setLauncherWallPaper(this,bitmap);
} catch (IOException e) {
e.printStackTrace();
}