When app goes background the thread pause

106 views Asked by At

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();
}
1

There are 1 answers

0
Adel Askri On

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:

 void backgroundFetchHeadlessTask(HeadlessTask task) async {
  String taskId = task.taskId;
  bool isTimeout = task.timeout;
  if (isTimeout) {
    // This task has exceeded its allowed running-time.  
    // You must stop what you're doing and immediately .finish(taskId)
    print("[BackgroundFetch] Headless task timed-out: $taskId");
    BackgroundFetch.finish(taskId);
    return;
  }  
  print('[BackgroundFetch] Headless event received.');
  // Do your work here...
  BackgroundFetch.finish(taskId);
}

And then you will have to call it inside your main

  void main() {    
  runApp(new MyApp());
  BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
}

And finally call it when you need it to start fetching this way:

BackgroundFetch.start().then((int status) {
        print('[BackgroundFetch] start success: $status');
      }).catchError((e) {
        print('[BackgroundFetch] start FAILURE: $e');
      });
    } else {
      BackgroundFetch.stop().then((int status) {
        print('[BackgroundFetch] stop success: $status');
      });