NetworkOnMainThreadException in Service

前端 未结 4 1350
渐次进展
渐次进展 2021-01-19 19:15

I\'m getting a NetworkOnMainThreadException in my Service class, which by nature doesn\'t make sense, because Services are background processes as

相关标签:
4条回答
  • 2021-01-19 19:34

    Service callbacks all run on the main thread, aka the UI thread. If you wish to do background work, either start a Thread, or use IntentService's onHandleIntent(Intent i).

    0 讨论(0)
  • 2021-01-19 19:41

    i just resolve this problem by using this :

    public int onStartCommand(Intent intent, int flags, int startId) {
    
        RefreshDBAsync task = new RefreshDBAsync(this);
        task.execute();
    
        return START_STICKY;
    }
    

    RefreshDBAsync is making request to a server at every 5 minutes

    0 讨论(0)
  • 2021-01-19 19:42

    The exception that is thrown when an application attempts to perform a networking operation on its main thread.

    This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.

    http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

    0 讨论(0)
  • 2021-01-19 19:46

    onStartCommand() runs on the UI thread in a Service. Try using IntentService, or alternatively use any other threading method in the Service (Handler/Runnable, AsyncTask).

    0 讨论(0)
提交回复
热议问题