A
I pass to explain to you the way I would, the operation is the following; A service is created as you have indicated, which will take charge of running the count back, it will be executed from the activity when pressing the button. In the same activity, a "hear" is created using a BroadcastReceiver which will receive the information of the service as the time elapsed, or when it ends. If the activity closes, the listening of the broadcast is eliminated, if it is destroyed, the service is finished; These latest behaviors can modify them according to your preference.
The implementation could be as follows:SERVICE:import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;
import java.util.concurrent.TimeUnit;
public class ServicioTimer extends Service {
String FORMAT = "%02d:%02d:%02d";
private static String TAG = "Servicio";
public static final String PAQETE = "nombre_de_tu_paquete.nombre_atividad"; //ejemplo com.proyecto.MainActivity
Intent bi = new Intent(PAQETE);
CountDownTimer cdt = null;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Comienza el timer...");
cdt = new CountDownTimer(9000, 1000) {
public void onTick(long millisUntilFinished) {
String tiempo = ""+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)));
//con esto se envia el tiempo
bi.putExtra("Tiempo", tiempo);
sendBroadcast(bi);
}
public void onFinish() {
//se envia el tiempo finalizado
bi.putExtra("Fin", "Tiempo terminado!");
sendBroadcast(bi);
}
}.start();
}
@Override
public void onDestroy() {
cdt.cancel();
Log.i(TAG, "Timer cancelado");
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;
}
}
ACTIVITY:import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static String TAG = "Servicio";
TextView contador;
Button iniciar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contador = (TextView) findViewById(R.id.contador);
iniciar = (Button) findViewById(R.id.iniciar);
iniciar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
iniciar.setEnabled(false);
//inicia el servicio
startService(new Intent(MainActivity.this, ServicioTimer.class));
}
});
}
private BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//aqui obtienes los datos enviados por el servicio
//obtienes el tiempo que lleva
if (intent.getExtras() != null) {
if (intent.hasExtra("Tiempo")) {
String tiempo = intent.getStringExtra("Tiempo");
contador.setText(tiempo);
} if (intent.hasExtra("Fin")) {
//se recibe que se ha finalizado el contador
String tiempo = intent.getStringExtra("Fin");
contador.setText(tiempo);
iniciar.setEnabled(true);
//cierras el servicio ya que no es necesario mantenerlo, sera creado al pulsar el boton nuevamente
stopService(new Intent(MainActivity.this, ServicioTimer.class));
}
}
}
};
@Override
public void onResume() {
super.onResume();
registerReceiver(br, new IntentFilter(ServicioTimer.PAQETE));
Log.i(TAG, "Broadcast registrado");
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(br);
Log.i(TAG, "Broadcast desligado");
}
@Override
public void onStop() {
try {
unregisterReceiver(br);
} catch (Exception e) {}
super.onStop();
}
@Override
public void onDestroy() {
stopService(new Intent(MainActivity.this, ServicioTimer.class));
Log.i(TAG, "Termina el servicio");
super.onDestroy();
}
}
MANIFEST:<service android:name=".ServicioTimer"/>
Obvite some little detail like you put your FORMAT and order it to your preference and needs, I have taken the liberty of adding small comments in the code and Logs to help you identify things, any doubt you can leave a comment and I will try to solve it as soon as possible.EDITO:
To complement my response, I add a https://github.com/kingcreek/Count-Down-Persistant-Android , the issue of persistence is solved if the application is closed, and when re-opening it continue the countdown.