1

I am developing an android app in which I need to show the remaining time in which a user can complete a certain task that is a countdown timer. If the user exceeds the stipulated time, the timer should start counting up or become a Chronometer. So, I need to use both in the same component. A setCountdown method has been added in chronometer in API level 24 but I cannot use this. Can someone please provide some library reference or some code wherein I can find a way to implement my use case.

AmrataB
  • 1,066
  • 2
  • 10
  • 19

1 Answers1

1

You can use Asynctask for this purpose and fire broadcast when time decreases..i am posting example here:

/*******************
 * asyncTask for timer
 ********************/
public class MyTimer extends AsyncTask<String, String, String> {
private AsyncTimer asyncTimer;
private Context context;

public MyTimer(Context context) {
    asyncTimer = (AsyncTimer) context;
    this.context = context;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    asyncTimer.updateUi(false);  //updates UI
}

@Override
protected void onPostExecute(String s) {
    asyncTimer.updateUi(true);
}

@Override
protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
    int time = Integer.parseInt(values[0]);
    Intent i = new Intent(Constants.BROADCAST_TIMER_KEY);
    i.putExtra(Constants.INTENT_BROADCAST_TIME, time);
    context.sendBroadcast(i);
}

@Override
protected String doInBackground(String... params) {
    long i = Integer.parseInt(params[0]);
    while (i >= 0) {
        publishProgress(String.valueOf(i));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        i = i - 1;
    }
    return null;
}
}

Broadcast to change time, where TimeSet is my interface to change the value on UI

public class BroadcastTimer extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    TimeSet timeSet = (TimeSet) context;
    int time = intent.getExtras().getInt(Constants.INTENT_BROADCAST_TIME);
    int min = (time) / 60;
    int sec = time % 60;
    timeSet.FinalResult(min + context.getString(R.string.str_mins) + sec + context.getString(R.string.str_secs));
}
}
jaunvi
  • 111
  • 8