I want to start an activity and store the start time in a variable, suppose session variable and check every second for a duration of 30 minutes. The moment it elapses 30 minutes the activity will close.
Asked
Active
Viewed 280 times
0
-
do you want the activity itself or the initiater to stop the activity? – codebrane Apr 01 '19 at 10:29
-
activity itself should close, problem is not regarding activity, it is regarding how to count time in background ? – user3099225 Apr 01 '19 at 11:43
4 Answers
1
You can use CountDownTimer
new CountDownTimer(30000, 1000) { //time in miliseconds
public void onTick(long millisUntilFinished) {
view.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("here close your activity");
}
}.start();
It is not mentioned in the decantation but you may need to consider how to handle the task if it is in the background.

Tamir Abutbul
- 7,301
- 7
- 25
- 53
1
You can create Handler for that as below:
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
finish();
}
};
int MINUTES = 30;
handler.postDelayed(runnable, 1000 * 60 * MINUTES);
If you want to remove callbacks of Runnable.
@Override
protected void onDestroy() {
super.onDestroy();
if (handler != null) {
handler.removeCallbacks(runnable);
}
}
Hope it will helps you..

Pratik Butani
- 60,504
- 58
- 273
- 437
0
You can use following:
int finishTime = 30000;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
YourActivity.this.finish();
}
}, finishTime * 1000);

Amirhosein
- 4,266
- 4
- 22
- 35