2011-03-22 6 views
8

Siguiendo los ejemplos de Google para usar un servicio, creé un par de temas como este. No puedo usar IntentService, porque estoy haciendo algo que implica esperar la devolución de llamadas.¿Cómo termino HandlerThreads?

Sin embargo, no sé cómo finalizar un hilo iniciado de esta manera. Según tengo entendido, los hilos terminan automáticamente cuando el método run() retorna. Sin embargo, este tipo de subproceso no tiene un método de ejecución. Mis hilos están goteando, se mantienen vivos después de stopSelf().

@Override 
public void onCreate() { 

    HandlerThread thread = new HandlerThread("ServiceStartArguments", 
      android.os.Process.THREAD_PRIORITY_BACKGROUND); 
    thread.start(); 
    HandlerThread thread2 = new HandlerThread("CallbackHandling", 
      android.os.Process.THREAD_PRIORITY_BACKGROUND); 
    thread2.start(); 

    mServiceLooper = thread.getLooper(); 
    mCallbackLooper = thread2.getLooper(); 
    mServiceHandler = new MyHandler(mServiceLooper); 
    mCallbackHandler = new Handler(mCallbackLooper); 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); 

    // For each start request, send a message to start a job and deliver the 
    // start ID so we know which request we're stopping when we finish the job 
    Message msg = mServiceHandler.obtainMessage(); 
    msg.arg1 = startId; 
    mServiceHandler.sendMessage(msg); 
    mMainThreadHandler=new Handler(); 
    // If we get killed, after returning from here, restart 
    return START_STICKY; 
} 

private final class MyHandler extends Handler { 
    public MyHandler(Looper looper) { 
     super(looper); 
    } 
    @Override 
    public void handleMessage(Message msg) { 
     cycle(); 


     // Stop the service using the startId, so that we don't stop 
     // the service in the middle of handling another job 
     stopSelf(msg.arg1); 
    } 
} 

protected void cycle() { 
    ... 
    mCallbackHandler.post(new Runnable(){ 
     public void run(){ 
      goAskForSomeCallbacks(); 
     } 
    }); 

    try { 
     Thread.sleep(GIVE_UP_TIME); 
    } catch (InterruptedException e){ 
     //The callback will interrupt this thread to stop it from waiting 
     Log.d(TAG,"Got early callback, stop waiting."); 
    } 
    Thread.interrupted(); //clear the interrupt 
    doStuff(); 

} 
+0

No entiendo por qué el uso de devoluciones de llamadas impediría que use un servicio de intendencia. Espero que "esperar las devoluciones de llamada" no implique esperar aquí. Si es así, entonces sugeriría un rediseño. De lo contrario, no hay ninguna razón para mantener HandlerThread por separado y por cada llamada esperada. Incluso si se trata de un gran procesamiento posterior de los datos proporcionados por devoluciones de llamadas, podría ser conveniente tener una cola para eso, etc. Por lo tanto, sería genial comprender la arquitectura que tiene en mente. –

Respuesta

16

Trate de llamar al método quit en los Loopers correspondientes.

+0

@ TenFour04 ¿publicaría la solución final? – eros

-1

El cierre forzado de la aplicación lo hace, pero de lo contrario simplemente continúan por su cuenta.

1

Puede llamar al método de abandono en los hilos de su controlador.

p. Ej.

thread.quit(); 
thread2.quit(); 
Cuestiones relacionadas