studio programacion para móviles libro edición desarrollo desarrollar curso aprende aplicaciones android multithreading textview runnable

para - manual de programacion android pdf



Actualización de Android TextView en Thread y Runnable (4)

Quiero hacer un temporizador simple en Android que actualice un TextView por segundo. Simplemente cuenta segundos como en Buscaminas.

El problema es cuando ignoro tvTime.setText (...) (lo hago //tvTime.setText (...), en LogCat se imprimirá el siguiente número cada segundo. Pero cuando quiero establecer este número en un TextView (creado en otro subproceso), el programa se bloquea.

¿Alguien tiene una idea de cómo resolver esto fácilmente?

Aquí está el código (se llama al método al inicio):

private void startTimerThread() { Thread th = new Thread(new Runnable() { private long startTime = System.currentTimeMillis(); public void run() { while (gameState == GameState.Playing) { System.out.println((System.currentTimeMillis() - this.startTime) / 1000); tvTime.setText("" + ((System.currentTimeMillis() - this.startTime) / 1000)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); th.start(); }

EDITAR:

Finalmente lo tengo. Aquí está la solución, para aquellos que estén interesados.

private void startTimerThread() { Thread th = new Thread(new Runnable() { private long startTime = System.currentTimeMillis(); public void run() { while (gameState == GameState.Playing) { runOnUiThread(new Runnable() { @Override public void run() { tvTime.setText(""+((System.currentTimeMillis()-startTime)/1000)); } }); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); th.start(); }


Alternativamente, también puede hacer esto en su hilo cada vez que quiera actualizar un elemento de UI:

runOnUiThread(new Runnable() { public void run() { // Update UI elements } });


Como opción, use runOnUiThread() para cambiar las propiedades de vistas en el hilo principal.

runOnUiThread(new Runnable() { @Override public void run() { textView.setText(" is cool!"); } });


No puede acceder a los elementos de la IU desde hilos que no sean UI. Intente rodear la llamada a setText(...) con otro Runnable y luego mire el View.post(Runnable) .


UserInterface solo se puede actualizar con el subproceso UI. Necesita un Handler para publicar en el hilo de la interfaz de usuario:

private void startTimerThread() { Handler handler = new Handler(); Runnable runnable = new Runnable() { private long startTime = System.currentTimeMillis(); public void run() { while (gameState == GameState.Playing) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } handler.post(new Runnable(){ public void run() { tvTime.setText("" + ((System.currentTimeMillis() - this.startTime) / 1000)); } }); } } }; new Thread(runnable).start(); }