Search code examples
androidmultithreadingservicehttprequestnetworkonmainthread

Network on main thread exception in thread inside service


I am calling DBSync service from MainActivity

startService(new Intent(this, DBSync.class));

The DBSync Service contains

public class DBSync extends Service {
Thread readThread;
int var1,var2;
@Override
public void onCreate() {
    readThread = new Thread(new Runnable() {
        @Override
    public void run() {
              try{
                  // My code which uses network,JSON and DBUpdation
              } catch(Exception e){
              }
        }
     });
     readThread.run();
}
}

In manifest

<service android:name=".DBSync" />

But it shows network on main thread exception.

java.lang.RuntimeException: Unable to create service com.package.DBSync: android.os.NetworkOnMainThreadException

Solution

  • Use start() and not run() to execute your runnable in a separate thread.