我自己找到了答案,希望可以帮助其他有同样问题的人。
官方文档为获取壁纸文件 says: If no lock-specific wallpaper has been configured for the given user, then this method will return null when requesting FLAG_LOCK rather than returning the system wallpaper's image file.
描述很模糊,至少不够清楚,这是什么意思?如果你将一张照片同时设置为锁屏壁纸和主屏壁纸,两者共享同一个文件,那么通过调用
ParcelFileDescriptor pfd = wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_LOCK);
pfd
总是为空,那么你应该这样获取锁屏壁纸:
if (pfd == null)
pfd = wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_SYSTEM);
你会得到非空的pfd
。情况是这样的no lock-specific wallpaper has been configured.
相反,lock-specific wallpaper has been configured
如果直接将照片设置为锁屏壁纸,wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_SYSTEM)
将返回一个非空值。
这是我用来检索锁屏壁纸的代码:
/**
* please check permission outside
* @return Bitmap or Drawable
*/
public static Object getLockScreenWallpaper(Context context)
{
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
if (Build.VERSION.SDK_INT >= 24)
{
ParcelFileDescriptor pfd = wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_LOCK);
if (pfd == null)
pfd = wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_SYSTEM);
if (pfd != null)
{
final Bitmap result = BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor());
try
{
pfd.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
}
return wallpaperManager.getDrawable();
}
别忘了添加READ_EXTERNAL_STORAGE
在清单文件中并将其授予外部。