0
My app strangely runs around in an infinite loop uncontrollably. It’s a simple code to download an image and apply as wallpaper.
But when removing this line of code, the loop goes away, that is to say asynctask works again as expected:
WallpaperManager.getInstance(weakContext.get()).setBitmap(bitmap);
I thought the problem might be WeakReference
, but even running code within the method onPostExecute()
using a Listener
to execute the changes within the Fragment the problem persists.
public class WorkerTask extends AsyncTask<String, Void, Bitmap> {
private static final String TAG = "WorkerTask";
private WeakReference<Context> weakContext;
private WeakReference<ImageView> weakImage;
private Bitmap wallpaper;
private WallpaperListener wallpaperListener;
WorkerTask(Context context, ImageView imageView, WallpaperListener listener){
weakContext = new WeakReference<>(context);
weakImage = new WeakReference<>(imageView);
wallpaperListener = listener;
}
@Override
protected Bitmap doInBackground(String... url) {
Log.d(TAG, "doInBackground: ");
if (url[0].isEmpty()){
throw new NullPointerException("URL Bad formatted");
}
/* Network */
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url[0])
.build();
Response response = null;
try {
response = client.newCall(request).execute();
/* Generate Image */
wallpaper = BitmapFactory.decodeStream(
Objects.requireNonNull(response.body()).byteStream());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
response.close();
}
}
return wallpaper;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
try {
WallpaperManager.getInstance(weakContext.get()).setBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Logcat:
Because you don’t use a lib like
Picasso
orGlide
to download the image ?– Eduardo Dornel
what’s the difference? the problem isn’t in the download itself, but rather when applying the wallpaper on the device. If you remove from the code (or comment) the line that applies the wallpaper to
Thread
does not loop.– Nakamoto