How to pause handler.postDelayed() timer on Android - android

How can i pause the handler.postDelayed() timer using a button. So when i click the same button again the handler.postDelayed() timer should resume.
handler.postDelayed(counterz, 60);

Handler does not have a timer to tweak. You are posting to event-queue of a thread, where a lot of other stuff is running as well.
You can cancel posted Runnable's:
handler.removeCallbacks(counterz);
And post again, to resume.

Handler does not have a pause method. You need to cancel and run again.
http://developer.android.com/reference/android/os/Handler.html#removeCallbacks(java.lang.Runnable)
public final void removeCallbacks (Runnable r)
Remove any pending posts of Runnable r that are in the message queue.
When not required you need to call m_handler.removeCallbacks(m_handlerTask) to cancel the run. If you need again you need to run the the task again.
Handler m_handler;
Runnable m_handlerTask ;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
// do something
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run(); // call run
Suppose you use a timer. Even timer does not have pause method.

public class YourActivity extends AppCompatActivity {
private static boolean handlerflag=false;
private Handler handler;
private Runnable runnable;
private int myind=0,index=0,count=0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activtiy);
//oncreate exe only
handlerflag=true;
handler = new Handler();
startyourtime(0);
}
private void startyourtime(int a) {
myind=0;
for (index=a; index<10 ;index++) {
myind++;
runnable=new Runnable() {
count++;
#Override
public void run() {
//your code here
}
};handler.postDelayed(runnable, Constants.TIME_LIMIT * myind);
}
#Override
protected void onPause() {
super.onPause();
handlerflag=false;
handler.removeCallbacksAndMessages(null);
}
#Override
protected void onResume() {
super.onResume();
if(!handlerflag)
{
startyourtime(count);
}
}
}

Related

Unable to stop handler despite calling removeCallbacks(runnable)

I have been trying to stop a handler in my onPause(). Despite of calling removeCallbacks(timeRunnable) or removeCallbacksAndMessages(timeRunnable), the handler is not stopped. I have seen many answers here. But nothing worked. I might be missing something here.
Code:
public Runnable timeRunnable = new Runnable() {
#Override
public void run() {
Log.d("Here is my task");
timeHandler.postDelayed(timeRunnable, 5000);
}
};
public void startTimeHandler() {
timeHandler.post(timeRunnable);
}
public void stopTimeHandler() {
timeHandler.removeCallbacks(timeRunnable);
}
#Override
protected void onPause() {
super.onPause();
stopTimeHandler();
}
I am using below code snippet to run a thread every 10 seconds and update UI based on the values received from Server, stop thread on onPause.
Declare below variables in your class:
public class ActivityPortfolio extends AppCompatActivity {
Handler handler = new Handler();
Runnable runnable;
int delay = 10*1000;
//---------
In your onResume:
#Override
protected void onResume() {
handler.postDelayed(new Runnable(){
public void run(){
doSomething();
handler.postDelayed(this, delay);
}
}, delay);
super.onResume();
}
onPause():
#Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(runnable); // this alone didnt work as we are calling postDelayed() in background as well.
handler.removeCallbacksAndMessages(null);//after adding this it stops thread
}

How to close a window/activity after a certain amount of time

am writing an android application, it allow someone add two numbers and input the answer. but I want this numbers to display for only 5 seconds and then a new number show up, if they input the correct or wrong answer, the timer reset and display new numbers..
i have written the code that does the random numbers and other just the timer am unable to do
someone help please
Using a Handler and Runnable should work for you but don't use an Anonymous runnable as they can cause memory leaks. Instead extend runnable into a static class and use removeCallbacks in onDestroy.
Also you can use WeakReference as onDestroy is not guaranteed to be called so a WeakReference will allow GC to free up the memory if your activity gets killed
public class BarActivity extends AppCompatActivity {
private Handler mHandler;
private FooRunnable mRunnable;
private void finishActivityAfterDelay(int milliSeconds) {
mHandler = new Handler();
mRunnable = new FooRunnable(this);
mHandler.postDelayed(mRunnable, 5000); // 5 seconds
}
#Override
protected void onDestroy() {
mHandler.removeCallbacks(mRunnable);
super.onDestroy();
}
private static class FooRunnable implements Runnable {
private WeakReference<AppCompatActivity> mWeakActivity;
public FooRunnable(AppCompatActivity activity) {
mWeakActivity = new WeakReference<>(activity);
}
#Override
public void run() {
AppCompatActivity activity = mWeakActivity.get();
if (activity != null) activity.finish();
}
}
}
You can use android.os.Handler class to do so,
Like
private Handler handler = new Handler(); // Create Handler
Runnable runnable = new Runnable() {
#Override
public void run() {
// Perform action here...
}
};
handler.postDelayed(runnable, 3 * 1000); // action will be performed after 3 seconds.
CountDownTimer timer = new CountDownTimer(30000/*modify value as per need*/, 1000) {
public void onTick(long millisUntilFinished) {
//millisUntilFinised is the remaining time
}
public void onFinish() {
//timer finished .Do what you need to do next here
}
};
use timer.start();where you had to start the timer.

How do i stop runnable after a specific time

Am having a handler method which is running in a interval of 5ms. I want to stop this execution after certain period? Any suggestion please
You can manage a handler(runnable) by creating an instance member for the handler and runnable, then managing the handler in the Activity Lifecycle methods.
private Handler myHandler;
private Runnable myRunnable = new Runnable() {
#Override
public void run() {
//Do Something
}
};
Start the runnable with handler.post.
protected void onStart() {
super.onStart();
myHandler = new Handler();
myHandler.post(myRunnable);
}
If the runnable hasn't executed by the time onStop is called, we don't want to run it. Remove the callback in the onStop method:
protected void onStop() {
super.onStop();
mHandler.removeCallbacks(myRunnable);
}

Termination of a thread not possible

I've got an activity with the following code:
Handler dataLoaderHandler = new Handler();
int mInterval = 3000;
public MyActivity myself;
Thread dataLoader = new Thread( new Runnable() {
#Override
public void run() {
Log.e("MyActivity","ReloadData");
new DataLoader(new JSONData(myself)).execute(Configuration.dataURL);
dataLoaderHandler.postDelayed(dataLoader, mInterval);
}
});
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myself = this;
... some other stuff...
dataLoader.start();
}
... other code ...
#Override
protected void onDestroy() {
super.onDestroy();
Log.e("MyActivity","onDestroy ending thread");
try { dataLoader.join(); } catch(Exception e) { e.printStackTrace(); }
Log.e("MyActivity","onDestroy called");
}
When I hit the back button my activity gets destroyed but the thread still continues to run every 3 seconds. Why is the thread not stopped or better said deleted?
Because you haven't stopped it. Since calling stop() on a thread is already deprecated, you should stop the thread within the thread itself. This can be easily done by calling return on it.
However, don't expect your Thread to finish immediately you hit your back button. The Thread will probably run up until Android OS determines it has to (basically, it may take a while to stop even you call it).
You may want to check that question I made a time ago, it's well answered.
try:
boolean finished=false;
Handler dataLoaderHandler = new Handler();
int mInterval = 3000;
public MyActivity myself;
Thread dataLoader = new Thread( new Runnable() {
#Override
public void run() {
if(!finished){
Log.e("MyActivity","ReloadData");
new DataLoader(new JSONData(myself)).execute(Configuration.dataURL);
dataLoaderHandler.postDelayed(dataLoader, mInterval);}
}
});
#Override
protected void onStop() {
super.onStop();
finished=true;
}

Using Handler as a timer but can't stop it

I found the code pasted below in a post on this forum back in 2011. I was using a timer to trigger the execution of doSomeWork but doSomeWork spawns an asynctask and (as I found out) asynctasks can only be spawned from the UI thread. So, I converted to using this postDelayed function of a Handler.
Now this code does indeed call doSomeWork every ten seconds and my asynctask no longer has problems. But when I call stopRepeatingTask() it does NOT stop the execution of doSomeWork - it keeps getting called every ten seconds.
This code is in a service and stopSelf() has been called but the code keeps running. The Android system doesn't even show the service as running but it's still calling doSomeWork.
What's wrong? How can I stop it?
Thanks, Gary
private int m_interval = 5000; // 5 seconds by default, can be changed later
private Handler m_handler;
#Override
protected void onCreate(Bundle bundle) {
// ...
m_handler = new Handler();
}
Runnable m_statusChecker = new Runnable() {
#Override
public void run() {
doSomeWork(); //this function can change value of m_interval.
m_handler.postDelayed(m_statusChecker, m_interval);
}
};
void startRepeatingTask() {
m_statusChecker.run();
}
void stopRepeatingTask() {
m_handler.removeCallbacks(m_statusChecker); // <--this does not appear to work
}
Add a status to your code to stop respawning new tasks:
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
private boolean mIsRunning;
protected void onCreate(Bundle bundle) {
// ...
mHandler = new Handler();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
if (!mIsRunning) {
return; // stop when told to stop
}
doSomeWork(); // this function can change value of mInterval.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mIsRunning = true;
mStatusChecker.run();
}
void stopRepeatingTask() {
mIsRunning = false;
mHandler.removeCallbacks(mStatusChecker);
}

Categories

Resources