How do I maintain and display CountDown when I quit the app?

0

I'm building an application to run tasks every hour, and I want to show countdown. But when I exit the application, upon returning, the count resumes. I need you to return to the app, the count is continuing. Can anyone help me?

    
asked by anonymous 26.03.2017 / 15:29

1 answer

1

Ok, come on then:

first, you need to initialize 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, there is the onReceive method that will be called at the conclusion of the initialization event. In it, let's 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);
     }
}

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

1) Add the permission to capture the load event at device boot:

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

2) Register the Service:

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

3) Register 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 service running in your app where every time it is started by the app it keeps running until the device completes the booot, that is, it is turned off.

You were due to what you have done there in code, so it was only to be generic, but I believe that onStart and onCreate of the Service you can manipulate your watch.

I hope it helps!

    
27.03.2017 / 20:33