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);
}
Related
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
}
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.
I can't stop this thread when I exit my activity or application.
public class MyThread extends Thread {
public Handler handler;
#Override
public void try{
Looper.prepare();
handler = new Handler();
Looper.loop();
}
}
...
myThread = new MyThread();
myThread.start();
final Runnable runnable = new Runnable() {
#Override
public void run(){
doSomething();
myThread.handler.postDelayed(this,30*1000);
}
};
myThread.handler.post(runnable);
#Override
public void onStop(){
myThread.handler.removeCallbacksAndMessages(null);
myThread.handler.getLooper().quit();
myThread = null;
}
I can confirm that all the onStop() code is run, but the logcat still shows the thread running after I exit the application.
I think even if I remove the battery and smash the device with a sledgehammer it will still keep running, I've tried everything. :~) I must be missing something about handlers, loopers, and threads. Please help.
add a boolean flag in the Activity, say "shouldThreadRun", set to true in onResume(), set to false in onPause()
In run() of the Thread, check whether the Activity is still running
if(shouldThreadRun){
doSomething();
myThread.handler.postDelayed(this,30*1000);
}
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;
}
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);
}
}
}