I have this method where when you press the back button of the phone kills a thread that is running in the activity that you want to back out.
Class that calls I have initialized the thread:
//Declaras una variable tipo Thread
public Thread HiloConsumo;
// Se crea el hilo
HiloConsumo = new HiloConsumidor("INTC")
HiloConsumo.setName("HiloConsumidor");
HiloConsumo.start();
// Metodo que al pulsar el boton de retroceder vuelve al Main y mata el HiloConsumidor
public void onBackPressed() {
if (HiloConsumo != null)//valida si existe instancia de Thread.
{
HiloConsumo.interrupt(); //Interrumpe su ejecución.
super.onBackPressed();
}
}
HiloConsumidor:
public class HiloConsumidor extends Thread {
String codigo;
public HiloConsumidor(String codigo) {
this.codigo = codigo;
}
@Override
public void run() {
Stock stock = null;
while (!HiloConsumo.isInterrupted()) {
try {
stock = YahooFinance.get(codigo);
Thread.sleep(10000);
} catch (InterruptedException e) {
this.interrupt();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
But when leaving and returning to the previous activity, which is the main thread continues to make a series of requests to an API without stopping. Inside the thread I have an infinite blucle I comment it but I think it's because of that