¿Cómo ejecutar el servicio no en el hilo principal?

Estoy tratando de lanzar el service y luego abrir socket para tener conexión con el servidor.

En el botón haga clic en Crear un nuevo Thread y luego iniciar el servicio.

 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(); 

Entonces en el service , intento abrir el socket y tener conexión con el servidor

 @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; } 

Pero cuando lo llamo, tengo error

 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* 

Creo que el problema es que el service está en el main thread , pero no puedo encontrar cómo debo iniciar el servicio en nuevo (independend) hilo para mantener la connection alive ?

Puede utilizar IntentService para esto. Sólo tiene que lanzarlo normalmente con una Intención del hilo principal. onHandleIntent() se ejecuta en el subproceso de fondo. Ponga su socket-código allí. Aquí hay un código de ejemplo.

 public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentService"); } @Override protected void onHandleIntent(Intent intent) { // this method is called in background thread } @Override public IBinder onBind(Intent intent) { return null; } } 

En su actividad, inicia el servicio como sigue.

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

Si necesita un servicio duradero, puede crear un servicio normal e iniciar un hilo allí. Aquí hay un ejemplo. Asegúrese de iniciarlo como servicio de "primer plano". Esto permitirá que el servicio funcione más largo sin ser matado por Android.

 public class MyAsyncService extends Service { private Runnable runnable = new Runnable() { @Override public void run() { while(true) { // put your socket-code here ... } } } @Override public void onCreate() { // start new thread and you your work there new Thread(runnable).start(); // prepare a notification for user and start service foreground Notification notification = ... // this will ensure your service won't be killed by Android startForeground(R.id.notification, notification); } } 

Mueve este código a tu hilo:

 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(); } 

Sólo como un ejemplo (no estoy seguro de que esto encaje en su tarea):

 Thread t = new Thread(){ public void run(){ 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(); } mIntent= new Intent(MainActivity.this, ConnectonService.class); mIntent.putExtra("KEY1", "Value used by the service"); context.startService(mIntent); } }; t.start(); 

Usted debe saber que un servicio se está ejecutando en el hilo de interfaz de usuario, por lo que obtuvo este error. Compruebe este sitio agradable para obtener más información acerca de varios enfoques de subprocesos en Android.

  • Implementación cliente / servidor de socket TCP de Android
  • Conexión de dos teléfonos Android para transferir datos entre ellos a través de WIFI
  • ¿Cómo puede mi aplicación Android comunicarse con un daemon nativo?
  • Android - Socket del servidor
  • Android juego multi-jugador a través de la red
  • Comunicación de LocalSocket con el dominio de Unix en Android NDK
  • Cómo desbloquear InputStream.read () en Android?
  • Mensajes de error NetlinkListener y NetlinkEvent
  • No obtiene respuesta en la conexión de socket
  • Servicio de Android para sockets TCP
  • Androide, socket, programación, atrás, router
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.