Skip to content

Commit 641d4a8

Browse files
committed
Fixed NetworkOnMainThreadException when cancelling requests by RequestHandle, Closes android-async-http#686
1 parent c422dce commit 641d4a8

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

library/src/main/java/com/loopj/android/http/RequestHandle.java

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818

1919
package com.loopj.android.http;
2020

21+
import android.os.Looper;
22+
2123
import java.lang.ref.WeakReference;
2224

2325
/**
@@ -45,9 +47,21 @@ public RequestHandle(AsyncHttpRequest request) {
4547
* @return false if the request could not be cancelled, typically because it has already
4648
* completed normally; true otherwise
4749
*/
48-
public boolean cancel(boolean mayInterruptIfRunning) {
49-
AsyncHttpRequest _request = request.get();
50-
return _request == null || _request.cancel(mayInterruptIfRunning);
50+
public boolean cancel(final boolean mayInterruptIfRunning) {
51+
final AsyncHttpRequest _request = request.get();
52+
if (_request != null) {
53+
if (Looper.myLooper() == Looper.getMainLooper()) {
54+
new Thread(new Runnable() {
55+
@Override
56+
public void run() {
57+
_request.cancel(mayInterruptIfRunning);
58+
}
59+
}).start();
60+
} else {
61+
_request.cancel(mayInterruptIfRunning);
62+
}
63+
}
64+
return false;
5165
}
5266

5367
/**

0 commit comments

Comments
 (0)