Skip to content

Commit 71556bd

Browse files
committed
Possibility to use library on non-UI thread (calling Looper.prepare) android-async-http#397
1 parent 4578068 commit 71556bd

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

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

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -166,10 +166,8 @@ public String getCharset() {
166166
* Creates a new AsyncHttpResponseHandler
167167
*/
168168
public AsyncHttpResponseHandler() {
169-
// Set up a handler to post events back to the correct thread if possible
170-
if (Looper.myLooper() != null) {
171-
handler = new ResponderHandler(this);
172-
}
169+
// Init Looper by calling postRunnable without argument
170+
postRunnable(null);
173171
}
174172

175173
/**
@@ -310,9 +308,19 @@ protected void sendMessage(Message msg) {
310308
* @param runnable runnable instance, can be null
311309
*/
312310
protected void postRunnable(Runnable runnable) {
313-
if (runnable != null) {
311+
boolean missingLooper = null != Looper.myLooper();
312+
if (missingLooper) {
313+
Looper.prepare();
314+
}
315+
if (null == handler) {
316+
handler = new ResponderHandler(this);
317+
}
318+
if (null != runnable) {
314319
handler.post(runnable);
315320
}
321+
if (missingLooper) {
322+
Looper.loop();
323+
}
316324
}
317325

318326
/**
@@ -370,7 +378,7 @@ byte[] getResponseData(HttpEntity entity) throws IOException {
370378
if (contentLength > Integer.MAX_VALUE) {
371379
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
372380
}
373-
int buffersize = (contentLength < 0) ? BUFFER_SIZE : (int) contentLength;
381+
int buffersize = (contentLength < 0) ? BUFFER_SIZE : (int) contentLength;
374382
try {
375383
ByteArrayBuffer buffer = new ByteArrayBuffer(buffersize);
376384
try {

0 commit comments

Comments
 (0)