android.os.NetworkOnMainThreadException on service start on android

前端 未结 4 1254
忘了有多久
忘了有多久 2020-12-11 16:40

after trying my brand new service on android i get this:

i guess is something related to the manifest file and permissions, the service is started after the last act

4条回答
  •  天涯浪人
    2020-12-11 17:07

    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.

提交回复
热议问题