android.os.NetworkOnMainThreadException on service start on android

倾然丶 夕夏残阳落幕 提交于 2019-11-28 13:34:15

This happens because you are doing a network operation on the main thread, and this is not allowed on Android 3.0 and above. Even though it is in a service, services are run on the UI thread unless you specifically launch them in another thread or create a thread inside it.

You can fix this by running the task in a service off the main UI thread, by using a Thread or an AsyncTask.

Try creating a new thread in onStartCommand(), as suggested by @CommonsWare.

Create function:

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

And call it from onStartCommand

thread.start(); 

As per the documentation, even though you use a Service to perform long running operations, the Service itself runs on the application's main thread. So you have to spawn a new thread to perform potentially long running tasks like network access.

Android's StrictMode actually checks for network operations performed on the main thread and throws a NetworkOnMainThreadException.

Ajay S

Try this. How to fix android.os.NetworkOnMainThreadException?

Read this thread carefully.

I hope this will solve your problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!