I try to start service , and then open socket to connect to the server.
When I click the button, I create a new Thread and then start the service.
Thread t = new Thread(){ public void run(){ mIntent= new Intent(MainActivity.this, ConnectonService.class); mIntent.putExtra("KEY1", "Value used by the service"); context.startService(mIntent); } }; t.start();
Then on service I try to open socket and have a connection to the server
@Override public int onStartCommand(Intent intent, int flags, int startId) { //TODO do something useful try { InetAddress serverAddr = InetAddress.getByName(SERVER_IP); socket = new Socket(serverAddr, SERVERPORT); Scanner scanner = new Scanner(socket.getInputStream()); message = scanner.nextLine(); } catch (IOException e) { e.printStackTrace(); } return Service.START_NOT_STICKY; }
But when I call it, I have a mistake
08-30 08:56:49.268: E/AndroidRuntime(3751): java.lang.RuntimeException: Unable to start service com.example.testofconnection.ConnectonService@40ef02a8 with Intent { cmp=com.example.testofconnection/.ConnectonService (has extras) }: android.os.NetworkOnMainThreadException*
I think the problem is that service is on the main thread , but I canβt find how I can start working with a new (independent) thread to keep the connection alive ?
source share