My app strangely runs in infinite loop wildly. This is a simple code to download an image and apply as wallpaper.
But when removing this line of code, the loop disappears, ie asynctask returns to work as expected:
WallpaperManager.getInstance(weakContext.get()).setBitmap(bitmap);
I already thought the problem could be WeakReference
, but even running the code inside the onPostExecute()
method 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: