I am making a Simple Timer app.It has a start and pause button. so when i click pause button and then again start button the timer is not publishing progress. It get stuck at the pause time and when i press start it still at the pause time. maybe because the onProgress function in the asyncTask class.
java file:
‘’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’
package com.example.stopwatch;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public static final String TAG = “ASYNC”;
Button btnStart, btnPause;
EditText etMin, etSec;
TextView tvTime;
int minutes = 0;
int seconds = 0;
Stopwatch sw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPause = findViewById(R.id.btnPause);
btnStart = findViewById(R.id.btnStart);
etMin = findViewById(R.id.etMin);
etSec = findViewById(R.id.etSec);
tvTime = findViewById(R.id.tvTime);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "btnStart: Started");
if (etMin.getText().toString() != "") {
minutes = Integer.parseInt(etMin.getText().toString());
}
if (etSec.getText().toString() != "") {
seconds = Integer.parseInt(etSec.getText().toString());
}
etMin.setText(null);
etSec.setText(null);
sw = new Stopwatch();
// Log.d(TAG, "Min: " + minutes + " sec: " + seconds);
sw.execute();
Log.d(TAG, "btnStart: Ended");
}
});
btnPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sw.cancel(true);
sw=null;
String time = minutes + " : " + seconds;
tvTime.setText(time);
etMin.setText(String.valueOf(minutes));
etSec.setText(String.valueOf(seconds));
}
});
}
class Stopwatch extends AsyncTask<Integer, Integer, Void> {
@Override
protected Void doInBackground(Integer... integers) {
Log.d(TAG, "Do in Background: Started");
int min = minutes;
int sec = seconds;
for (int i = min; i >= 0; i--) {
if (i == min) {
for (int j = sec; j >= 0; j--) {
--seconds;
wait1sec();
publishProgress(i, j);
}
} else {
for (int j = 59; j >= 0; j--) {
--seconds;
wait1sec();
publishProgress(i, j);
}
}
--minutes;
}
Log.d(TAG, "Do in Background: Ended");
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
String time = values[0] + " : " + values[1];
if (values[0] == 0 && values[1] == 0) {
tvTime.setText("TIME UP !!!!");
} else
tvTime.setText(time);
}
}
void wait1sec() {
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() < startTime + 1000) ;
}
}