我正在使用unsplash
API构建墙纸应用程序。我已获取图像并显示在应用程序中。我有一个按钮,它显示一个对话框,设置为主屏幕(可以正常工作)或锁定屏幕墙纸。
当我尝试设置锁定屏幕墙纸时,这里会出现问题,它不会更改锁定屏幕上的图像。这是我的代码片段:
setBtn.setOnClickListener(new View.OnClickListener() {
@TargetApi(Build.VERSION_CODES.N)
@Override
public void onClick(View view) {
if (validate()) {
if (homeCheckBox.isChecked() && largeURL != null) {
setHomeWallpaper(largeURL);
getDialog().dismiss();
}
if (lockCheckBox.isChecked() && largeURL != null) {
setLockWallpaper(largeURL);
getDialog().dismiss();
}
} else {
Toast.makeText(getContext(), "Select an Option", Toast.LENGTH_SHORT).show();
}
}
});
并设置锁屏壁纸:
private void setLockWallpaper(final String largeURL) {
final WallpaperManager wpm = WallpaperManager.getInstance(getActivity());
if (Build.VERSION.SDK_INT >= 24){
if (wpm.isSetWallpaperAllowed()) {
Log.d(TAG, "Lock Screen Wallpapers Supported");
makeLockWallpaper(wpm, largeURL);
getDialog().dismiss();
} else {
Toast.makeText(getActivity(), "Your Device Does Not Support Lock Screen Wallpapers", Toast.LENGTH_SHORT).show();
}
} else {
makeLockWallpaper(wpm, largeURL);
getDialog().dismiss();
}
}
private void makeLockWallpaper(final WallpaperManager wpm, final String largeURL) {
new Thread(new Runnable() {
@TargetApi(Build.VERSION_CODES.N)
@Override
public void run() {
URL url = null;
try {
url = new URL(largeURL);
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
InputStream stream = Utils.bitmapToStream(bitmap);
// set wp
wpm.setStream(stream, null, true, WallpaperManager.FLAG_LOCK);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
要设置主屏幕墙纸,我已经使用Picasso
了,并且可以使用:
private void setHomeWallpaper(String largeURL) {
final WallpaperManager wpm = WallpaperManager.getInstance(getActivity());
Picasso.with(getActivity())
.load(largeURL)
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
wpm.setBitmap(bitmap);
Toast.makeText(getActivity(), "Your New Wallpaper Has Been Set", Toast.LENGTH_SHORT).show();
getDialog().dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.d(TAG, "Bitmap Load Failed");
Toast.makeText(getActivity(), "Could Not Set Wallpaper...Choose Another", Toast.LENGTH_SHORT).show();
getDialog().dismiss();
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Log.d(TAG, "Prep to Load Bitmap");
}
});
}
但是由于锁定屏幕的标志,我必须使用setStream or setResource
。有人知道Picasso是否可以解决此问题,因为至少我知道图像是否由于Picasso callbacks
而准备就绪,或者建议我对设置锁屏墙纸的代码进行改进。谢谢。