How to maintain and display CountDown when exiting the app?

I'm building an app to run tasks every hour, and I want to show Countdown. But when I exit the app, upon coming back, the count restarts. I need that when I return to the app, the count is continuing. Can anyone help me ?

Author: viana, 2017-03-26

1 answers

Ok, come on then:

First, you need to start the service:

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class ServicoIniciadoNoBoot extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // Algo para ser feito quando o serviço for criado
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        // algo que precisa ser feito quando o serviço for incializado
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Algo que precisa ser feito quando o serviço for finalizado (destruido)
    }
}

Then, you will need a BroadcastReceiver, in it is that there is the OnReceive method that will be called at the completion of the startup event. In it, we will launch the service we just created.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class BootCompletadoReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
         Intent serviceIntent = new Intent(context, ServicoIniciadoNoBoot.class);
         context.startService(serviceIntent);
     }
}

Then you need to modify the AndroidManifest file.xml for the app to respond to the service:

1) Add permission to capture loading event on boot Device:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

2) Register the service:

<service android:name=".ServicoIniciadoNoBoot" ></service>

3) Register the BroadcastReceiver to receive the event:

<receiver
    android:name=".BootCompletadoReceiver"
    android:enabled="true"
    android:exported="false" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

With these steps you create a running service in your app where every time it is started by the app it keeps running until the device completes boot, that is, it is turned off.

You were the duty of what you have done ai in code, so only gave to be generic, but I believe that onStart and onCreate service you can manipulate your watch.

Hope it helps!

 1
Author: Armando Marques Sobrinho, 2017-03-27 18:33:16