尝试将壁纸应用到设备时出现 OutOfMemoryError。
我正在使用 AsyncTask,有时它工作正常,但有时会发生这种情况。
有人可以帮助我进一步优化它吗?提前致谢。
异步任务代码:
public class ApplyWallpaper extends AsyncTask<Void, String, Boolean> {
private Context context;
private Activity activity;
private MaterialDialog dialog;
private Bitmap resource;
private View layout;
private boolean isPicker;
private Snackbar snackbar;
public ApplyWallpaper(Context context, MaterialDialog dialog, Bitmap resource, Boolean isPicker, View layout) {
this.activity = (Activity) context;
this.context = context;
this.dialog = dialog;
this.resource = resource;
this.isPicker = isPicker;
this.layout = layout;
}
@Override
protected Boolean doInBackground(Void... params) {
WallpaperManager wm = WallpaperManager.getInstance(context);
Boolean worked;
try {
wm.setBitmap(scaleToActualAspectRatio(resource));
worked = true;
} catch (IOException e2) {
worked = false;
}
return worked;
}
@Override
protected void onPostExecute(Boolean worked) {
if (worked) {
dialog.dismiss();
Util.showSimpleSnackbar(layout,
context.getString(R.string.set_as_wall_done), 1);
} else {
String retry = context.getResources().getString(R.string.retry);
snackbar = Snackbar
.make(layout, R.string.error, Snackbar.LENGTH_INDEFINITE)
.setAction(retry.toUpperCase(), new View.OnClickListener() {
@Override
public void onClick(View view) {
new ApplyWallpaper(context, dialog, resource, isPicker, layout);
}
});
snackbar.setActionTextColor(context.getResources().getColor(R.color.accent));
snackbar.show();
}
if (isPicker) {
activity.finish();
}
}
public Bitmap scaleToActualAspectRatio(Bitmap bitmap) {
if (bitmap != null) {
boolean flag = true;
int deviceWidth = activity.getWindowManager().getDefaultDisplay()
.getWidth();
int deviceHeight = activity.getWindowManager().getDefaultDisplay()
.getHeight();
int bitmapHeight = bitmap.getHeight();
int bitmapWidth = bitmap.getWidth();
if (bitmapWidth > deviceWidth) {
flag = false;
int scaledHeight = deviceHeight;
int scaledWidth = (scaledHeight * bitmapWidth) / bitmapHeight;
try {
if (scaledHeight > deviceHeight)
scaledHeight = deviceHeight;
bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth,
scaledHeight, true);
} catch (Exception e) {
e.printStackTrace();
}
}
if (flag) {
if (bitmapHeight > deviceHeight) {
int scaledHeight = deviceHeight;
int scaledWidth = (scaledHeight * bitmapWidth)
/ bitmapHeight;
try {
if (scaledWidth > deviceWidth)
scaledWidth = deviceWidth;
bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth,
scaledHeight, true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return bitmap;
}
}
壁纸资源加载自:
Glide.with(context)
.load(linkForWallpaper)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(final Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
if (resource != null) {
new ApplyWallpaper(context, dialogApply, resource,
false, layout, fab).execute();
}
}
});