Question

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?

Was it helpful?

Solution

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());

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top