Skip to content

Commit

Permalink
Added the networking task cancellation/destruction to a background th…
Browse files Browse the repository at this point in the history
…read.
  • Loading branch information
jsligh committed Jan 11, 2024
1 parent 7653e7f commit 94adfba
Showing 1 changed file with 25 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import android.content.Context;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Looper;

import org.prebid.mobile.LogUtil;
import org.prebid.mobile.api.exceptions.AdException;
Expand Down Expand Up @@ -82,10 +83,32 @@ public abstract class Requester {

public abstract void startAdRequest();

/**
* This Async task is needed because the networkTask needs to be cancelled / destroyed
* on a background thread or it throws a NetworkOnMainThreadException
**/
private static class DestroyNetworkTaskAsyncTask extends AsyncTask<BaseNetworkTask, Void, Void> {

@Override
protected Void doInBackground(BaseNetworkTask... baseNetworkTasks) {
if (baseNetworkTasks.length > 0) {
if (baseNetworkTasks[0] != null) {
baseNetworkTasks[0].cancel(true);
baseNetworkTasks[0].destroy();
}
}
return null;
}
}

public void destroy() {
if (networkTask != null) {
networkTask.cancel(true);
networkTask.destroy();
if(Looper.getMainLooper().getThread() == Thread.currentThread()) {
new DestroyNetworkTaskAsyncTask().execute(networkTask);
} else {
networkTask.cancel(true);
networkTask.destroy();
}
}
networkTask = null;
if (fetchAdIdInfoTask != null) {
Expand Down

0 comments on commit 94adfba

Please sign in to comment.