0

I have a looper and handler:

private Handler handler;

public class LooperThread extends Thread
{
    @Override
    public void run()
    {
        Looper.prepare();
        handler = new Handler()
        {
            @Override
            public void handleMessage(Message message)
            {
                updateUI(message.obj);
            }
        };

        Looper.loop();
    }
}

In my MainActivity I then call:

new LooperThread().start();
new Thread(new WorkerTask()).start();

Where WorkerTask implements Runnable.

Can't create handler inside thread that has not called Looper.prepare().

Inside my workerTask it is throwing the error on the second line:

locationManager = (LocationManager) activity.getSystemService(activity.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
B-Rad
  • 1,519
  • 5
  • 17
  • 32
  • I think this post answers my question: http://stackoverflow.com/questions/17476847/error-cant-create-handler-inside-thread-that-has-not-called-looper-prepare – B-Rad Aug 29 '14 at 21:38
  • can you post the code of worker task?your LooperThread is fine – eldjon Aug 29 '14 at 22:08

2 Answers2

0

If this is in Activity or fragment you can simply use runOnUiThread to update ui.

Ajit Pratap Singh
  • 1,299
  • 12
  • 24
0

You need to use this:

activity.runOnUiThread(new Runnable() {
  public void run() {
    updateUI(message.obj);
  }
});

Or to use it with your existing code:

private Handler handler;

public class LooperThread extends Thread
{
    @Override
    public void run()
    {
        Looper.prepare();
        handler = new Handler()
        {
            @Override
            public void handleMessage(Message message)
            {
                activity.runOnUiThread(new Runnable() {
                public void run() {
                    updateUI(message.obj);
                }
                });
            }
        };

        Looper.loop();
    }
}
apmartin1991
  • 3,064
  • 1
  • 23
  • 44