我使用下面的代码在 android 8.1 手机上检索 android 锁屏壁纸:
WallpaperManager manager = WallpaperManager.getInstance(getActivity());
ParcelFileDescriptor pfd = manager.getWallpaperFile(WallpaperManager.FLAG_LOCK);
if (pfd == null) // pfd is always null for FLAG_LOCK, why?
return;
Bitmap lockScreenWallpaper = BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor());
// ...
我已经授予
READ_EXTERNAL_STORAGE
权限并事先设置了锁屏壁纸。我在真机上运行演示,发现
pfd
的 FLAG_LOCK
始终为空,因此无法获取锁屏壁纸。请帮忙解决问题,谢谢。 最佳答案
我自己找到了答案,我希望它可以帮助其他有同样问题的人。
getWallpaperFile 的官方文档说: 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);
您将获得非null的
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();
}
不要忘记在 list 文件中添加
READ_EXTERNAL_STORAGE
并在外部授予它。关于android - 如何获得安卓锁屏壁纸?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53881697/