Keep an active countDonwTimer when you close the activity or app

0

I have a counter that counts down, but at the time of leaving the activity it restarts again, I hope this does not happen, I thought that maybe I will have to connect the app with a web page using ViewWeb , But would it be more tedious, will there be another solution?

I leave you my CountDown

inicar=(Button)findViewById(R.id.iniciar);
        inicar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countDown = new CountDownTimer(9000, 1000) {

                    public void onTick(long millisUntilFinished) {

                        contador.setText(""+String.format(FORMAT,
                                TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                                TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
                                        TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                                TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
                                        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
                    }

                    public void onFinish() {

                        contador.setText("Tiempo terminado!");
                    }
                }.start();
                inicar.setEnabled(false);
            }
        });
        pausar=(Button)findViewById(R.id.Reinicar);
        pausar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countDown.cancel();
                inicar.setEnabled(true);
                contador.setText("Esperando minutos...");
            }
        });

Thank you!

    
asked by Ashley G. 19.08.2017 в 23:01
source

1 answer

0

You have to create a service that stays active even if the application is closed. To be able to receive the notification that tick that%% of the service makes from the service, you have to subscribe to the service.

First define the service:

import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;
public class CountDownService extends Service {

    private final static String TAG = "BroadcastService";

    public static final String paquete_app = "nombrepaquete.countdown_broadcast";
    Intent bi = new Intent(paquete_app);

    CountDownTimer countDownTimer = null;

    @Override
        public void onCreate() {       
            super.onCreate();

            countDownTimer = new CountDownTimer(30000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                    bi.putExtra("countdown", millisUntilFinished);
                    sendBroadcast(bi);
                }

                @Override
                public void onFinish() {
                   bi.putExtra("countdown", -1);
                   sendBroadcast(bi);
                }
            };

            countDownTimer.start();
        }

        @Override
        public void onDestroy() {

            countDownTimer.cancel();
            super.onDestroy();
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {       
            return super.onStartCommand(intent, flags, startId);
        }

        @Override
        public IBinder onBind(Intent arg0) {       
            return null;
        }
}

Now we start the service and with the intent, we indicate the reference of the Activity to which you will notify for each CountDownTimer :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    startService(new Intent(this, CountDownService.class));
}

private BroadcastReceiver br = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {            
        actualizarContador(intent); 
    }
};

@Override  
public void onResume() {
    super.onResume();        
    registerReceiver(br, new IntentFilter(CountDownService.paquete_app ));
    }

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(br);
}

@Override
public void onStop() {
    try {
        unregisterReceiver(br);
    } catch (Exception e) {
    }
    super.onStop();
}
@Override
public void onDestroy() {        
    stopService(new Intent(this, CountDownService.class));
    super.onDestroy();
}

private void actualizarContador(Intent intent) {
    if (intent.getExtras() != null) {
        long millisUntilFinished = intent.getLongExtra("countdown", 0);
        if(millisUntilFinished > 0)
        {

            // actualiza aqui tu contador en la vista
            contador.setText(""+String.format(FORMAT,
                                TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                                TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
                                        TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                                TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
                                        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
        }
        else{
            contador.setText("Tiempo terminado!");
        }
    }
}

Remember to define your service in the manifest:

<service android:name=".CountDownService" />
    
answered by 20.08.2017 в 13:59