Android Main Thread Looper concern

1.3k views Asked by At

I'm writing a library, which does some intensive network work. So, I'm using a HandlerThread to carry out this operation like this:

Looper.prepare();
libraryThread = new LibraryHandlerThread(context);
libraryThread.start();
libraryThread.getLooper();

LibraryHandlerThread does the network operations and other time consuming operations.

When I call this code from a worker thread (any thread other than Main thread), it works fine. But complains about "can't initialize another looper when one is already active". I believe that a Looper runs on Main thread by default, and complains about Looper.prepare(). I can do something like following to make it working from Main thread:

Looper.getMainLooper().quit();
Looper.prepare();
libraryThread = new LibraryHandlerThread(context);
libraryThread.start();
libraryThread.getLooper();

My question is: what would be the impact on Main thread. In my ideal world, I want to run my library's operations on a separate thread without impacting the main thread. How can I achieve this without much destruction?

2

There are 2 answers

2
Nitin Sethi On BEST ANSWER

Try the below code:

private static final HandlerThread sWorkerThread = new HandlerThread("network-operations");
static {
    sWorkerThread.start();
}
private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
3
TheHamstring On

What you will want to look into is using a Asynctask to run this in the background which will allow your main thread to keep working http://developer.android.com/reference/android/os/AsyncTask.html

Or you can create a service if this is something that you will need constantly running. http://developer.android.com/reference/android/app/Service.html