¿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.
- Conexiones de socket y Polling. ¿Cuál es la mejor solución en términos de duración de la batería?
- Proteger un socket en VpnService
- HTTP Vs sockets Vanilla para cargar archivos binarios grandes (50-200 MB) desde un dispositivo Android a través de una red Wi-Fi de un solo salto
- Android: ¿Cómo detectar la aplicación eliminada de la lista de aplicaciones recientes?
- ¿Cómo puedo mantener mi aplicación en segundo plano?
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
?
- Cómo enviar el archivo binario y el texto usando el mismo socket
- Crear SSLSocket por SSLSocketFactory con tiempo de espera de conexión establecido
- La mejor manera de implementar Socket.io en android
- InputStream no recibe EOF
- Comunicación de socket cliente / servidor de Android mediante Service o IntentService
- UDP Multicasting desde el móvil a la PC
- ¿Cómo puedo manejar múltiples clientes conectados a un servidor mediante sockets?
- Cómo pasar datos del servidor a la aplicación de Android: REST vs Sockets
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.
- ¿Cómo cambiar el icono de notificación de Parse push en android?
- Android llama al método onClick sin hacer clic