How to use intervals in Android CountdownTimer - android

I am creating a countdown time in Android and I have the timer part working perfectly. However, I want to add a feature where the user can set the number of times they wish the timer to repeat. This is my current attempt at implementation
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
minutesText = (EditText) findViewById(R.id.minutesText);
secondsText = (EditText) findViewById(R.id.secondsText);
startButton = (Button) findViewById(R.id.startButton);
intervalCount = (EditText) findViewById(R.id.intervalCount);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (minutesText.getText().toString().equals("")) {
minutesInt = 0;
} else {
minutesString = minutesText.getText().toString();
minutesInt = Integer.parseInt(minutesString);
}
secondsString = secondsText.getText().toString();
if (secondsText.getText().toString().equals("")) {
secondsInt = 0;
} else {
secondsString = secondsText.getText().toString();
secondsInt = Integer.parseInt(secondsString);
}
intervalsString = intervalCount.getText().toString();
intervals = Integer.parseInt(intervalsString);
final int timerAmount = ((minutesInt * 60) + (secondsInt)) * 1000;
CountDownTimer timer = new CountDownTimer(timerAmount, 1000) {
#RequiresApi(api = Build.VERSION_CODES.N)
public void onTick(long millisUntilFinished) {
isRunning = true;
String timeLeft = String.format("%02d : %02d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))
);
textView.setText("Reamining: " + timeLeft);
}
public void onFinish() {
isRunning = false;
intervals--;
if (intervals > 0) {
timer.start();
}
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
};timer.start();
}
});
My error is in the onFinish()
it wont let me use timer.start()

CountDownTimer basically uses a Handler thread which is like other threads can not be restarted once its ended.
You need to use a new instance of the CountDownTimer in each interval.
So in your case, bring the
intervals--;
if (intervals > 0) {
// for each interval left create a new CountDownTimer here and start it.
}
outside of
new CountDownTimer(timerAmount, 1000 } {
// do your operations here.
}

Related

Timer with Handler and SharedPreference

Nowdays I tried to make a timer by using handler and sharedpreferences.
Today I had a problem with sharedprefereces.
The problem is that it is okay to push start button and go to background and then restart this app, the app is working correctly.
But it is not okay if i try twice the pattern(push start button -> background -> app -> background -> app) , the textview which display the time turns to zero....
I don't know what is problem....
Here is the code..
private Button mStartBtn, mStopBtn, mRecordBtn, mPauseBtn;
private TextView mTimeTextView, mRecordTextView;
private Thread timeThread = null;
private Boolean isRunning = false;
ArrayList<String> record = new ArrayList<>();
Boolean timeThreadd = false;
long i;
long mEndTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stop_watch);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#4ea1d3"));
}
mStartBtn = (Button) findViewById(R.id.btn_start);
mStopBtn = (Button) findViewById(R.id.btn_stop);
mRecordBtn = (Button) findViewById(R.id.btn_record);
mPauseBtn = (Button) findViewById(R.id.btn_pause);
mTimeTextView = (TextView) findViewById(R.id.timeView);
mRecordTextView = (TextView) findViewById(R.id.recordView);
mStartBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setVisibility(View.GONE);
mStopBtn.setVisibility(View.VISIBLE);
mRecordBtn.setVisibility(View.VISIBLE);
mPauseBtn.setVisibility(View.VISIBLE);
if (isRunning != true) {
isRunning = true;
}// start 가 true 일때만 실행된다.
timeThread = new Thread(new timeThread());
timeThread.start();
}
});
mStopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setVisibility(View.GONE);
mRecordBtn.setVisibility(View.GONE);
mStartBtn.setVisibility(View.VISIBLE);
mPauseBtn.setVisibility(View.GONE);
mRecordTextView.setText("");
mTimeTextView.setText("00:00:00:00");
timeThread.interrupt();
i = 0;
mEndTime = 0;
timeThreadd = false;
isRunning = false;
if (record.size() > 1) {
for (int i = 0; i < record.size(); i++) {
record.remove(i);
}
}
SharedPreferences sharedPreferences = getSharedPreferences("timer", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
});
mRecordBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
record.add(mTimeTextView.getText().toString());
mRecordTextView.setText(mRecordTextView.getText() + mTimeTextView.getText().toString() + "\n");
}// 앞에 mRecordTextView.getText()은 n번이상 저장할때 첫번째 값을 n-1번째 라인에 놓고
}); // n번째 저장한것을 n번째 놓기 위해서 설정
mPauseBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isRunning = !isRunning;
if (isRunning) {
mPauseBtn.setText("PAUSE");
} else {
mPauseBtn.setText("PAUSE");
}
}
});
}
#SuppressLint("HandlerLeak")
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
int mSec = msg.arg1 % 100;
int sec = (msg.arg1 / 100) % 60;
int min = (msg.arg1 / 100) / 60;
int hour = (msg.arg1 / 100) / 360;
//1000 = 1 sec, 1000*60 = 1 min, 1000*60*10 = 10min 1000*60*60 = 1 hour
#SuppressLint("DefaultLocale")
String result = String.format(Locale.getDefault(), "%02d:%02d:%02d:%02d", hour, min, sec, mSec);
mTimeTextView.setText(result);
}
};
public class timeThread implements Runnable {
#Override
public void run() {
mEndTime = System.currentTimeMillis() / 10 + i;
timeThreadd = true;
while (true) {
while (isRunning) { //일시정지를 누르면 멈춤
Message msg = new Message();
msg.arg1 = (int) i++;
handler.sendMessage(msg);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
mTimeTextView.setText("");
mTimeTextView.setText("00:00:00:00");
}
});
return;
}
}
}
}
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences sharedpreferences = getSharedPreferences("timer", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putLong("time", i);
editor.putBoolean("switch", isRunning);
editor.putInt("recordsize", record.size());
editor.putLong("endTime", mEndTime);
Log.v("i", String.valueOf(i));
Log.v("iswitch", String.valueOf(isRunning));
Log.v("endTime", String.valueOf(mEndTime));
isRunning = false;
for (int i = 0; i < record.size(); i++) {
editor.putString("record" + i, record.get(i));
}
editor.apply();
if (timeThreadd != false) {
timeThread.interrupt();
}
if (record.size() > 0) {
for (int i = 0; i < record.size(); i++) {
record.remove(i);
}
}
}
#Override
protected void onStart() {
super.onStart();
SharedPreferences sharedpreferences = getSharedPreferences("timer", MODE_PRIVATE);
i = sharedpreferences.getLong("time", 0);
isRunning = sharedpreferences.getBoolean("switch", isRunning);
int b = sharedpreferences.getInt("recordsize", 0);
for (int i = 0; i < b; i++) {
String c = sharedpreferences.getString("record" + i, null);
record.add(c);
mRecordTextView.setText(mRecordTextView.getText() + c + "\n");
}
if (isRunning) {
mEndTime = sharedpreferences.getLong("endTime", 0);
Log.v(" set mEndTime",String.valueOf(mEndTime));
i = System.currentTimeMillis() / 10 - mEndTime;
Log.v(" set i",String.valueOf(i));
if (i < 0) {
isRunning = false;
i = 0;
mEndTime = 0;
timeThreadd = false;
mRecordBtn.setVisibility(View.GONE);
mStartBtn.setVisibility(View.VISIBLE);
mPauseBtn.setVisibility(View.GONE);
mRecordTextView.setText("");
mTimeTextView.setText("00:00:00:00");
} else if (i > 0) {
mStartBtn.setVisibility(View.GONE);
mStopBtn.setVisibility(View.VISIBLE);
mRecordBtn.setVisibility(View.VISIBLE);
mPauseBtn.setVisibility(View.VISIBLE);
timeThread = new Thread(new timeThread());
timeThread.start();
}
}
}
}
I solve the problem.
public void run() {
if(timeThreadd!= true){
mEndTime = System.currentTimeMillis() / 10 + i;
timeThreadd = true;
}
The problem was System.currentTimeMillis().
The System.currentTimeMillis() needs to store just one time when user push the start button.

chronometer not running in service

I am trying to run chronometer inside a Service. But I am not able to run it. I press a button in Activity and that event is passed to the Service. If the button in pressed then start the Chronometer but problem is setOnChronometerTickListener is called only once and it stops. Where am I making mistake? Here is my Service and Activity class:
Service class:
public class TimerService extends Service {
NotificationManager notificationManager;
NotificationCompat.Builder mBuilder;
Callbacks activity;
private final IBinder mBinder = new LocalBinder();
private Chronometer chronometer;
SharedPreferences sharedPreferences;
private int state = 0; //0 means stop state,1 means play, 2 means pause
private boolean running = false;
private long pauseOffSet = -1;
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
if (event.message) {
if (!running) {
if (pauseOffSet != -1) {
pauseOffSet = sharedPreferences.getLong("milli", -1);
}
chronometer.setBase(SystemClock.elapsedRealtime() - pauseOffSet);
chronometer.start();
state = 1;
pauseOffSet = 0;
running = true;
}
} else {
if (running) {
chronometer.stop();
pauseOffSet = SystemClock.elapsedRealtime() - chronometer.getBase();
state = 2;
running = false;
}
}
}
#Override
public void onCreate() {
super.onCreate();
EventBus.getDefault().register(this);
}
#Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
sharedPreferences = getSharedPreferences("myprefs", MODE_PRIVATE);
chronometer = new Chronometer(this);
state = sharedPreferences.getInt("state", 0);
chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
Log.e("TimerService","timer");
pauseOffSet = SystemClock.elapsedRealtime() - chronometer.getBase();
if (pauseOffSet >= 79200000) {
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.stop();
running = false;
// progressBar.setProgress(0);
} else {
chronometer.setText(setFormat(pauseOffSet));
// int convertTime = (int) pauseOffSet;
// progressBar.setProgress(convertTime);
}
if (activity != null) {
activity.updateClient(pauseOffSet);
}
}
});
if (state == 1) { // its in play mode
running = true;
chronometer.setBase(SystemClock.elapsedRealtime() - sharedPreferences.getLong("milli", 0));
chronometer.start();
} else if (state == 2) { //its in pause mode
running = false;
pauseOffSet = sharedPreferences.getLong("milli", -1);
long time = SystemClock.elapsedRealtime() - pauseOffSet;
chronometer.setBase(time);
int convertTime = (int) pauseOffSet;
// progressBar.setProgress(convertTime);
} else {
running = false;
}
//Do what you need in onStartCommand when service has been started
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
//returns the instance of the service
public class LocalBinder extends Binder {
public TimerService getServiceInstance() {
return TimerService.this;
}
}
//Here Activity register to the service as Callbacks client
public void registerClient(Activity activity) {
this.activity = (Callbacks) activity;
}
//callbacks interface for communication with service clients!
public interface Callbacks {
public void updateClient(long data);
}
String setFormat(long time) {
int h = (int) (time / 3600000);
int m = (int) (time - h * 3600000) / 60000;
int s = (int) (time - h * 3600000 - m * 60000) / 1000;
String hh = h < 10 ? "0" + h : h + "";
String mm = m < 10 ? "0" + m : m + "";
String ss = s < 10 ? "0" + s : s + "";
return hh + ":" + mm + ":" + ss;
}
}
This is my Activity class:
public class MainActivity extends AppCompatActivity implements View.OnClickListener, TimerService.Callbacks {
private static final String TAG = MainActivity.class.getSimpleName();
Chronometer tvTextView;
Button btnStart, btnStop;
private int state = 0; //0 means stop state,1 means play, 2 means pause
SharedPreferences sharedPreferences;
private boolean running = false;
private long pauseOffSet = -1;
ProgressBar progressBar;
Intent serviceIntent;
TimerService myService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTextView = findViewById(R.id.textview);
progressBar = findViewById(R.id.puzzleProgressBar);
btnStart = findViewById(R.id.button1);
btnStop = findViewById(R.id.button2);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
serviceIntent = new Intent(this, TimerService.class);
sharedPreferences = getSharedPreferences("myprefs", MODE_PRIVATE);
state = sharedPreferences.getInt("state", 0);
tvTextView.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
long time = SystemClock.elapsedRealtime() - chronometer.getBase();
pauseOffSet = time;
Log.e(TAG, "pauseOffSet " + pauseOffSet);
if (time >= 79200000) {
tvTextView.setBase(SystemClock.elapsedRealtime());
tvTextView.stop();
running = false;
progressBar.setProgress(0);
} else {
chronometer.setText(setFormat(time));
int convertTime = (int) time;
progressBar.setProgress(convertTime);
}
}
});
startService(serviceIntent); //Starting the service
bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE); //Binding to the service!
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
TimerService.LocalBinder binder = (TimerService.LocalBinder) service;
myService = binder.getServiceInstance();
myService.registerClient(MainActivity.this);
Log.e(TAG, "service connected");
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.e(TAG, "service disconnected");
}
};
public void onClick(View v) {
if (btnStart == v) {
EventBus.getDefault().post(new MessageEvent(true));
} else if (btnStop == v) {
EventBus.getDefault().post(new MessageEvent(false));
}
}
#Override
protected void onStop() {
super.onStop();
sharedPreferences.edit().putLong("milli", pauseOffSet).commit();
sharedPreferences.edit().putInt("state", state).commit();
}
String setFormat(long time) {
int h = (int) (time / 3600000);
int m = (int) (time - h * 3600000) / 60000;
int s = (int) (time - h * 3600000 - m * 60000) / 1000;
String hh = h < 10 ? "0" + h : h + "";
String mm = m < 10 ? "0" + m : m + "";
String ss = s < 10 ? "0" + s : s + "";
return hh + ":" + mm + ":" + ss;
}
#Override
public void updateClient(long data) {
Log.d(TAG, "Data from service" + data);
}
}
The Chronometer is a View, that is, a UI element. You never add your Chronometer to any layout, I guess that's why it's never updating.
You could try using a CountDownTimer or a Handler / Runnable combination.
http://developer.android.com/reference/android/os/CountDownTimer.html http://developer.android.com/reference/android/os/Handler.html
Here's an example using Handler / Runnable, I've even thrown in a stopTimer() method for good measure:
private Handler timerHandler;
private Runnable timerRunnable;
// ...
#Override
public void onCreate() {
super.onCreate();
Log.d(LOG_TAG, "TimerService created");
timerHandler = new Handler();
timerRunnable = new Runnable() {
#Override
public void run() {
Log.d(LOG_TAG, "TICK");
timerHandler.postDelayed(timerRunnable, 1000);
}
};
}
public void startTimer() {
Log.d(LOG_TAG, "Timer started");
timerHandler.post(timerRunnable);
}
public void stopTimer() {
Log.d(LOG_TAG, "Timer stopped");
timerHandler.removeCallbacks(timerRunnable);
}
Here is a video which do not use Handler and directly implement the chronometer ,
Do check it out...
https://youtu.be/RLnb4vVkftc
Plus I had this problem I solved by removing
android:format="00:00"
from Chronometer in activity_main.xml
So my code looks like this :
<Chronometer
android:id="#+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:height="20sp"
android:foregroundGravity="fill_horizontal|top|bottom|center|fill_vertical|fill"
android:maxLines="2"
android:minLines="2"
android:textColor="#FFF"
android:textSize="40sp"
android:verticalScrollbarPosition="defaultPosition"
app:layout_constraintBottom_toBottomOf="#+id/progress_breathing"
app:layout_constraintEnd_toEndOf="#+id/progress_breathing"
app:layout_constraintStart_toStartOf="#+id/progress_breathing"
app:layout_constraintTop_toTopOf="#+id/progress_breathing"
app:layout_constraintVertical_bias="0.43" />

How to start timer for 3 hours even app is closed or back from activity in android

once a timer start it couldn't be stop for 3 hours.if I click on backpress timer stoped.I am not sure how to pause and resume the timer as the textview.Please check my code.
TextView timer;
SharedPreferences mpref;
SharedPreferences.Editor ed;
String output;
MyCount counter;
long seconds;
long millisFinished;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start__test2);
mpref=getSharedPreferences("com.example.bright", Context.MODE_PRIVATE);
timer = (TextView) findViewById(R.id.timer);
//startService(new Intent(this, MyService.class));
counter = new MyCount(10800000, 1000);
counter.start();
}
countDownTimer method
public class MyCount extends CountDownTimer {
Context mContext;
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
Log.e("timeeeee", millisInFuture + "");
}
public void onTick(long millisUntilFinished) {
Log.e("time",millisUntilFinished+"");
millisFinished = millisUntilFinished;
timer.setText(formatTime(millisUntilFinished));
/* String timer_str = timer.getText().toString();
//SharedPreferences sp=
ed = mpref.edit();
ed.putString("time", timer_str);
ed.commit();*/
if (seconds == 0) {
}
}
public void onFinish() {
Toast.makeText(getApplicationContext(), "Time Up", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onResume() {
super.onResume();
/*// Log.e("valueeeee",millisFinished+"");
// new MyCount(millisFinished,1000);
// Log.e("value",millisFinished+"");*/
//counter
}
#Override
public void onDestroy() {
super.onDestroy();
// counter.cancel();
}
//================================================================================Time format
public String formatTime(long millis) {
output = "";
seconds = millis / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
seconds = seconds % 60;
minutes = minutes % 60;
hours = hours % 60;
String secondsD = String.valueOf(seconds);
String minutesD = String.valueOf(minutes);
String hoursD = String.valueOf(hours);
if (seconds < 10)
secondsD = "0" + seconds;
if (minutes < 10)
minutesD = "0" + minutes;
if (hours < 10)
hoursD = "0" + hours;
output = hoursD + " : " + minutesD + " : " + secondsD;
return output;
}
Please check my code
U need to use a service so that the timer runs even if the app is closed/destroyed. Try as below
public class TimerService extends Service {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private Context mContext;
public IBinder onBind(Intent intent)
{
return null;
}
public void onCreate()
{
super.onCreate();
mContext = this;
startService();
}
private void startService()
{
scheduler.scheduleAtFixedRate(runner, 0, 3, TimeUnit.HOURS);
}
final Runnable runner = new Runnable() {
public void run()
{
mHandler.sendEmptyMessage(0);
}
}
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
}
private final Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
//do what ever you want as 3hrs is completed
}
};
}
If you create objects in your activities scope they will be disposed once the activity is gone because of the activity lifecycle.
The solution for running long background tasks is us inn services by IntentService.
You can read more about it here :
https://developer.android.com/training/run-background-service/create-service.html
Good luck!

Android - Timer layout is not getting updated

I am new to android. I am learning to create a simple stop watch app. I got layout with three buttons and one textview. When I click start button, it will start the timer.
Single layout and single activity.
public void startTimer(View view){
running = true;
TextView textView = (TextView) findViewById(R.id.timer);
while(running) {
int hours = seconds / 3600;
int minutes = (seconds % 60) / 60;
int sec = seconds % 60;
String time = String.format("%02d:%02d:%02d", hours, minutes, seconds);
textView.setText(time);
seconds++;
if(seconds == 10){
running = false;
}
}
}
This is the method called when I click start button. I debugged the code. Values are generating properly. But not updating the layout.
Any suggestions?
I get the final result else one by one increase with the following addition
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stop_watch);
runTimer(); //I added this extra.
}
I will give you an alternate solution on your task,
public void startTimer(View view){
new CountDownTimer(10000, 1000) { //For 10 seconds
public void onTick(long seconds) {
String time = String.format("%02d : %02d ",
TimeUnit.MILLISECONDS.toMinutes(seconds),
TimeUnit.MILLISECONDS.toSeconds(seconds) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(seconds))
);
textView.setText(time);
}
}
public void onFinish() {
textView.setText("Finished");
}
}.start();
}
UPDATE :
public void startTimer(View view) {
running = true;
seconds = 0;
textView = (TextView) findViewById(R.id.txtView);
new Thread(new Runnable() {
#Override
public void run() {
while(running) {
runOnUiThread(new Runnable() {
#Override
public void run() {
int hours = seconds / 3600;
int minutes = (seconds % 60) / 60;
int sec = seconds % 60;
time = String.format("%02d:%02d:%02d", hours, minutes, seconds);
textView.setText(time);
seconds++;
}
}) ;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(seconds==10){
running=false;
}
}
}).start();
}
Try using below code
public void startTimer(View view){
running = true;
TextView textView = (TextView) findViewById(R.id.timer);
while(running) {
int hours = seconds / 3600;
int minutes = (seconds % 60) / 60;
int sec = seconds % 60;
String time = String.format("%02d:%02d:%02d", hours, minutes, seconds);
seconds++;
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(time);
}
});
Thread.sleep(1000)
if(seconds == 10){
running = false;
}
}
}

why thread don't work accurately (a count down with thread)

I need count down timer that whenever I clicked or times up, send result and time score to another activity. So I used thread, but I don't know why in first time run activity it don't show time for some seconds in textview, one more strange thing is that when press back,then go to activity again it works fine.
count down code:
if (flagTime) {
flagTime = false;
new Thread(new Runnable() {
#Override
public void run() {
int counter = 60;
while (function.isActivityVisible() && counter > 0) {
counter--;
final int finalCounter = counter;
try {
Thread.sleep(1000);
G.HANDLER.post(new Runnable() {
#Override
public void run() {
if (function.isActivityVisible()) {
timeSc=finalCounter;
String preSec = "";
if (finalCounter < 10) {
preSec = "0";
}
if (function.isActivityVisible()
&& finalCounter <= 0) {
flagTime = false;
Intent intent = new Intent(
Memorize.this,
MemorizeResult.class);
intent.putExtra("TIME", 60);
intent.putExtra("ARRAY_RESULT",
array_choice);
startActivity(intent);
finish();
}
String score = "00:" + preSec
+ finalCounter;
txt[20].setText( " time ramaining " + score);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
if (!function.isActivityVisible()) {
flagTime = false;
finish();
}
}
}).start();
}
I use many flag to handle it, but it seems don't work properly.
Try using a CountDownTimer
Something like:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();

Categories

Resources