I need your help. I have a chronometer app very simply that show the time running. I created a thread that count the time and update the UI. When the app is in first plane, everything is fine. When I press back buttom the app goes background but the Thread is paused for the system. When I return to the App, the chronometer began to run again.
How I can do for maintenance the time running on background?
I will appreciate your hep.
Thanks, Rodrigo.
private void cronometro(){
new Thread(new Runnable(){
@Override
public void run() {
while (true) {
if (isOn) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
mensaje_log = "Se produjo un error";
Log.d("Miapp",mensaje_log);
Escribirlog.escribir_eventos(mensaje_log);
mensaje_log = e.getMessage();
Escribirlog.escribir_eventos(mensaje_log);
Thread.currentThread().interrupt();
}
mili++;
if (mili == 999) {
seg++;
mili = 0;
saltos++;
if (saltos == 10) {
//escribe log cada 10 segundos
mensaje_log = "Corriendo...";
Log.d("Miapp",mensaje_log);
Escribirlog.escribir_eventos(mensaje_log);
saltos = 0;
}
}
if (seg == 59) {
minutos++;
seg = 0;
}
h.post(new Runnable() {
@Override
public void run() {
String m = "", s = "", mi = "";
if (mili < 10) {
m = "00" + mili;
} else if (mili < 100) {
m = "0" + mili;
} else {
m = "" + mili;
}
if (seg < 10) {
s = "0" + seg;
} else {
s = "" + seg;
}
if (minutos < 10) {
mi = "0" + minutos;
} else {
mi = "" + minutos;
}
m = m.substring(0,2); //toma los 2 primeros numeros de milisegundos
crono.setText(mi + ":" + s + ":" + m);
}
});
}
}
}
}).start();
}
In order to keep a task running in the background in flutter you will need to use a package, a one you can go with is https://pub.dev/packages/background_fetch, the way you going to use it like this:
And then you will have to call it inside your main
And finally call it when you need it to start fetching this way: