问题描述
我使用以下代码在android 8.1手机上检索android锁屏壁纸:
I use the code below to retrieve the android lock screen wallpaper on an android 8.1 phone:
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
权限,并预先设置了锁屏壁纸.
I have granted the READ_EXTERNAL_STORAGE
permission and set a lock screen wallpaper beforehand.
我在真实的手机上运行演示,发现 pfd
对于 FLAG_LOCK
始终为空,因此无法获得锁屏墙纸.请帮助解决问题,谢谢.
I run the demo on a real phone, and found the pfd
is always null for FLAG_LOCK
, so I cannot get the lock screen wallpaper. Please help fix the problem, thanks.
推荐答案
我自己找到了答案,希望它可以帮助其他有相同问题的人.
I find the answer myself, I hope it can help others with the same question.
getWallpaperFile 的官方文档说:如果没有为给定的用户配置任何特定于锁的墙纸,则此方法在请求FLAG_LOCK时将返回null,而不是返回系统墙纸的图像文件.
描述含糊不清,至少不够清晰,这是什么意思?如果您同时将照片设置为锁定屏幕和主屏幕墙纸,则两者共享相同的文件,然后调用
The description is vague, at least not clear enough, what does it mean? If you set a photo as both lock screen and home screen wallpaper, the two share the same file, then by calling
ParcelFileDescriptor pfd = wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_LOCK);
pfd
始终为空,那么您应该通过以下方式获取锁屏墙纸:
pfd
will always be null, then you should get the lock screen wallpaper this way:
if (pfd == null)
pfd = wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_SYSTEM);
您将获得非空的 pfd
.这是未配置锁特定墙纸的情况.
you will get the non-null pfd
. This is the case no lock-specific wallpaper has been configured.
相反,如果您直接将照片设置为锁屏墙纸,则已经配置了锁定特定的墙纸
, wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_SYSTEM)
将返回一个非空值.
On the contrary, lock-specific wallpaper has been configured
if you set a photo as lock screen wallpaper directly, wallpaperManager.getWallpaperFile(WallpaperManager.FLAG_SYSTEM)
will return a non-null value.
这是我用来检索锁屏墙纸的代码:
So this is the code I use to retrieve the lock screen wallpaper:
/**
* 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
并将其授予外部.
Don't forget to add READ_EXTERNAL_STORAGE
in the manifest file and grant it outside.
这篇关于如何获取android锁屏壁纸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!