I have an Activity. All I want is if user don't touch screen, after a TIMEOUT, this activity will automatically finish(). Anyone have any ideas?
CountDownTimer countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//TODO: Do something every second
}
public void onFinish() {
finish();
//YourActivity.finish(); outside the actvitiy
}
}.start();
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
countDownTimer.cancel();
countDownTimer.start();
}
return super.onTouchEvent(event);
}
So basically you start a countDown timer and than wait for it to get completed. Once completed, call finish on the activity.
If in between the user touches the screen, you cancel the timer and start it again.
Don't forget to accept the answer :)
Look for how to wait/sleep in Android, examples:
wait for 3 seconds or user click
Wait a time - Android
How to "wait" a Thread in Android
And when the wait/sleep ends just call the finish() method.
Try this in your Activity:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
finish();
//YourActivity.finish(); outside the actvitiy
}
}.start();
http://developer.android.com/reference/android/os/CountDownTimer.html
use this :
int time =0;
then add onTouchListener for your root layout and update time value like this :
time = 0;
and use the handler for count like this :
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
time++;
if(time>=10000){
finish();
}
}
}, 1000);
it is clear i set finish time for 10 second.
Related
While learning using Threads in Android I've created simple thread that updates time textview every second:
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
if(time!=0){
if(time>9){timeLeftTV.setText("0:"+time);}
else{timeLeftTV.setText("0:0"+time);}
time--;
}
else {
//timeLeftTV.setText("finished");
}
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
I want to display dialog box when the time expires. How do I stop this thread?
use CountDownTimer
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
This is example of 30 seconds for 1 second time interval.
You can display dialog box on onFinish() method.
Most of the time I use a Runnable that can be scheduled with a Handler as followed:
final int timeInterval = 1000;
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run () {
textView.setText("time..");
// schedule the same Runnable after one second
handler.postDelayed(this, timeInterval);
}
};
handler.postDelayed(runnable, timeInterval);
To stop your loop, remove the Runnable from the Handler:
handler.removeCallbacks(runnable);
When you don't want to use the method above, simply use a Boolean that prevents your loop to continue and your Thread will end itself:
boolean stop = false;
Thread t = new Thread() {
#Override
public void run () {
while (!stop) {
// do stuff
}
}
};
t.start();
To stop the Thread:
stop = true;
Just interrupt the thread, Where you want to stop it.
thread.interrupt();
There are many ways to stop thread.
Like you can use Executor Services instead of timer. But for the quick solution you can go ahead with the following one:
long startTimer= System.currentTimeMillis();
long stopTimer= startTimer+ 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < stopTimer)
{
// Perform your all the required operation here
}
Hope it will help you.
For Executor service check the below stack link:
How to timeout a thread
I have a button(in say Activity 1), which when clicked should start a service (eg Service 1). But there must be a delay of 5 seconds before the service starts. I achieved this using SystemClock.sleep(5000) in the onStartCommand of the service. This worked properly.
Now I want to add the functionality that if the button is clicked again(even before the 5 seconds end), the service WILL NOT BE STARTED.
Any ideas how to do this?
(Edit : Please read the entire question before marking it as a duplicate. Thanks)
You can use handler with post delayed to achieve your goal. Make your button disable and enable it after five seconds along with starting your service. You can implement the following code:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button.setEnabled(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//start your service here
button.setEnabled(true);
}
}, 5000);
}
});
Above code will disable your button for 5 second and will start your service after 5 second.
I'd use a util class similar to the following. Pass it in a runnable and a delay in ms and you can call stop() on it to cancel before it has run. You can also call restart() if you want to restart your timer. I use it for things like auto showing/hiding controls on an immersive view.
public class DelayableRunnable{
int mDelay = 0;
Handler mHandler = new Handler();
Runnable mRunnable;
boolean mIsRunning = false;
public DelayableRunnable(Runnable runnable, int delay){
mRunnable = runnable;
mDelay = delay;
}
public void setNewDelay(int delay){
mDelay = delay;
}
public void start(){
if(mIsRunning) {
stop();
}
mHandler.postDelayed(mRunnable, mDelay);
mIsRunning = true;
}
public void stop(){
mHandler.removeCallbacks(mRunnable);
mIsRunning = false;
}
public void restart(){
stop();
start();
}
}
You can use Handler.postDelayed function for delayed actions in Android enviroment (better than plan java methods)
final Handler handler = new Handler(); // or use existed one your_view.getHandler()
handler.postDelayed(new Runnable() {
#Override
public void run() {
//start your service
}
}, 5000 /* 5s * 1000ms */);
Or simpler use you view function (work same as above):
your_view.postDelayed(new Runnable() {
#Override
public void run() {
//start your service
}
}, 5000 /* 5s * 1000ms */);
A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals void schedule (TimerTask task,long delay) Schedules the specified task for execution after the specified delay.
new Timer().schedule(new TimerTask() {
#Override
public void run() {
alertDialog.dismiss();
startActivity(new Intent(****.this,*********.class));
}
},5000);
I use CountDownTimer in my code and when i run app i have one problem that is when i go to next level ( go to next activity ) the timer should be stop and dont run the onfinish method but when the first level timer down it run the onfinish method and go to activity GameOver .
I use Intent to move between my activity and my CountDownTimer is :
new CountDownTimer(timeoflevel, 1000) {
public void onTick(long millisUntilFinished) {
txtclock2.setText("Time: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
txtclock2.setText("..Finish..");
Intent intent = new Intent(Play.this , GameOver.class);
startActivity(intent);
}
}.start();
Sorry for my easy question and thanks for reading .
CountDownTimer countDownTimer;
countDownTimer = new CountDownTimer(timeoflevel, 1000) {
public void onTick(long millisUntilFinished) {
txtclock2.setText("Time: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
txtclock2.setText("..Finish..");
Intent intent = new Intent(Play.this , GameOver.class);
startActivity(intent);
}
}.start();
// and in OnStop
public void onStop(){
countDownTimer.cancel();
}
You should call countDownTimer.cancel() before starting next level. It will cancel the counDownTimer and will not call onFinish.
public void onStop(){
//Cancel your timer here before going to next activity.
}
CountDownTimer countDownTimer;
//in on Resume()
countDownTimer = new CountDownTimer(timeoflevel, 1000) {
public void onTick(long millisUntilFinished) {
txtclock2.setText("Time: " + millisUntilFinished / 1000);
//TODO perform operation
}
public void onFinish() {
txtclock2.setText("..Finish..");
Intent intent = new Intent(Play.this , GameOver.class);
startActivity(intent);
}
}.start();
// Cancel Timer in onPause()
public void in onPause(){
countDownTimer.cancel();
}
I have tried multiple ways to have a single persistent timer update the ui in multiple activities, and nothing seems to work. I have tried an AsyncTask, a Handler, and a CountDownTimer. The code below does not execute the first Log.i statement.... Is there a better way to start the timer (which must be called from another class) in Main (which is the only persistent class)?
public static void MainLawTimer()
{
MainActivity.lawTimer = new CountDownTimer(MainActivity.timeLeft, 1000)
{
public void onTick(long millisUntilFinished)
{
Log.i("aaa","Timer running. Time left: "+MainActivity.timeLeft);
MainActivity.timeLeft--;
if(MainActivity.timeLeft<=0)
{
//do stuff
}
else
{
//call method in another class
}
}
public void onFinish()
{ }
}.start();
}
To clarify my problem:
When I run the code the Log.i("aaa","Timer running") statement is never shown in the log, and the CountDownTimer never seems to start. MainLawTimer is called from another class only (not within the same class.
For CountDownTimer
http://developer.android.com/reference/android/os/CountDownTimer.html
You can use a Handler
Handler m_handler;
Runnable m_handlerTask ;
int timeleft=100;
m_handler = new Handler();
#Override
public void run() {
if(timeleft>=0)
{
// do stuff
Log.i("timeleft",""+timeleft);
timeleft--;
}
else
{
m_handler.removeCallbacks(m_handlerTask); // cancel run
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
Timer
int timeleft=100;
Timer _t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
Log.i("timeleft",""+timeleft);
//update ui
}
});
if(timeleft>==0)
{
timeleft--;
}
else
{
_t.cancel();
}
}
}, 1000, 1000 );
You can use a AsyncTask or a Timer or a CountDownTimer.
Thank you all for your help, I discovered the error in my code... timeLeft was in seconds rather then milliseconds. Since timeLeft was under 1000 (the wait period) the timer never started.
i want to save the time when countDownTimer begin working, is there any method like onStart()?
timeToDirectAnswer = new CountDownTimer(25000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
}
};
The timer starts ticking the moment start() is called on it. You can get the current time wherever start() is called.