jhalterman / lyra

High availability RabbitMQ client
Apache License 2.0
262 stars 74 forks source link

android.os.NetworkOnMainThreadException #56

Closed EMIN3M1986 closed 7 years ago

EMIN3M1986 commented 8 years ago

Hi. I use Lyra in a Service and create Connection on a new thread. But when this line goes to execute

Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {

 try {
         connection = Connections.create(options, config);
            } catch (IOException e) {
               e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
           }
            getConsumerChannel();
        }
    });

    thread.setPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
    thread.run();

it shows me this error. android.os.NetworkOnMainThreadException

What is the reason ?

atfire commented 8 years ago

It's not allowed to run networking code in the main app thread on android. To fix your example you need to call thread.start() instead of thread.run(). To undetstand the difference read javadocs of these methods or some article like this: http://javarevisited.blogspot.com/2012/03/difference-between-start-and-run-method.html.

michaelklishin commented 8 years ago

What @atfire says. Connect in a separate thread.