How Threads are stop - android

public void onGenerate3() {
Log.i("onGenerate", "WorkingStart");
// thread is used for recursion
myActivity.myHandler.postDelayed(new Runnable() {
#Override
public void run() {
myActivity.myHandler.sendEmptyMessage(myActivity.GenerateBallonsForTargetScene);
Log.i("onGenerate", "WorkingEnd");
}, 1000);
}
//Now i Want to stop the thread on a particler action how i can do this

You won't stop a thread, what you want to do is to cancel the execution of a timed runnable.
I think this is a method to do it.
Runnable myTask = new Runnable() {
#Override
public void run() {
myActivity.myHandler.sendEmptyMessage(myActivity.GenerateBallonsForTargetScene);
Log.i("onGenerate", "WorkingEnd");
}
// schedule the runnable
myActivity.myHandler.postDelayed(myTask, 1000);
// cancel the runnable
myActivity.myHandler.removeCallbacks(myTask);
Of course you can also prevent execution of the code:
// member variable
private boolean canceled;
Runnable myTask = new Runnable() {
#Override
public void run() {
if (!canceled){
myActivity.myHandler.sendEmptyMessage(myActivity.GenerateBallonsForTargetScene);
Log.i("onGenerate", "WorkingEnd");
}
}
// schedule the runnable
myActivity.myHandler.postDelayed(myTask, 1000);
// cancel
canceled = true;

Related

Delay crashes the app

I have this code in MainActivity:
boolean running = true;
#Override
public void onClick(View v) {
Button button = (Button)findViewById(R.id.start);
new Thread(new Runnable() {
public void run() {
int secs = 1;
while(running){
Utils.delay(secs, new Utils.DelayCallback() {
int seconds = 0;
TextView licznik = (TextView)findViewById(R.id.licznik);
#Override
public void afterDelay() {
seconds = seconds + 1;
licznik.setText(Integer.toString(seconds));
}
});
}
}
}).start();
}
and its Utils class:
import android.os.Handler;
public class Utils {
// Delay mechanism
public interface DelayCallback{
void afterDelay();
}
public static void delay(int secs, final DelayCallback delayCallback){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
delayCallback.afterDelay();
}
}, secs * 1000); // afterDelay will be executed after (secs*1000) milliseconds.
}
}
I found this method on StackOverflow, but it crashes my app after I click the button
What's wrong? Please help, if I should do another method for delay, tell me which
error:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
You are creating a Handler on a background Thread that hasn't called Looper.prepare(), and also touching a UI component off of the main thread.
Try:
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
delayCallback.afterDelay();
}
}, secs * 1000);
and see if that fixes the problem. Either way, though, you'll probably run into issues, since the while(running) call is going to trigger a lot without a sleep...

Remove callback not working in Handler

I have Handler.I call my function every 10 second.Code working perfect,but i can't stop handler.This is my source code
handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {
#Override
public void run() {
myFunction(position);
handler.postDelayed(runnable,10000);
}
};
public void myFunction(int position)
{
if(position>10)
handler.removeCallbacks(runnable);
}
I can call myfunction every 10 second,but i can't stop handler.Ho i can solve my problem?
The problem is that myFunction removes the callback, then you still call handler.postDelayed to schedule a new one. There are plenty of ways to refactor this. For example:
handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {
#Override
public void run() {
boolean reschedule = myFunction(position);
if(reschedule) {
handler.postDelayed(runnable,10000);
}
}
};
public boolean myFunction(int position)
{
if(position>10) {
return false;
}
return true;
}
You don't have to remove callbacks on the handler because a new one will not be scheduled in the first place.
You remove callback in myFunction but you postDelayed again when myFunction returns, just invert lines inside run()
#Override
public void run() {
handler.postDelayed(runnable,10000);
myFunction(position);
}

Android Runnable not stopping after removeCallbacks()

I am trying to stop Runnable using removeCallbacks, but somehow it wont stop. - here are my variables
private int mInterval = 2000; // 2 seconds by default, can be changed later
private Handler mHandler = new Handler();
and my runnable
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
try {
checkPayNow();
} finally {
// 100% guarantee that this always happens, even if
// your update method throws an exception
mHandler.postDelayed(mStatusChecker, mInterval);
}
}
};
and the method I am running untill it gives me a certain value then i stop
public void checkPayNow(){
if (!url.isEmpty()){
//url now has text
mHandler.removeCallbacks(mStatusChecker);
}else {
//no text yet
}
}
boolean stoped = false;
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
try {
checkPayNow();
} finally {
if(!stoped)
mHandler.postDelayed(mStatusChecker, mInterval);
}
}
};
Make stoped = true when you want to stop.
and remove handler from checkPayNow().
public void checkPayNow(){
if (!url.isEmpty()){
//url now has text
//mHandler.removeCallbacks(mStatusChecker);
}else {
//no text yet
}
}
You can try to do it without removeCallbacks like this:
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
if(!checkPayNow()) {
//if not ready so far, then check in some delay again
mHandler.postDelayed(mStatusChecker, mInterval);
}
}
};
public boolean checkPayNow(){
return !url.isEmpty();
}

AsyncTask not called from TimerTask android

I am developing the project which continuously get datas from server at 30secs interval.So I used Handler with Timer and called Asynctask.
But my asynctask not called.This is my code,
final Handler handler;
handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask()
{
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try
{
System.out.println("I am xxx");
LiveTrack myActivity = new LiveTrack();
AsyncTask<String, String, String> task = myActivity.new VehiclePath();
task.execute();
}
catch (Exception e)
{
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 30000);
Can anyone guide me why I am facing this?
You cannot create an AsyncTask from within a TimerTask because it runs on a spawned thread, i.e.
not the UI thread).
AsynTasks must be created and execute()-ed only on the UI thread.
Instead, use an Executor for the background processing and call runOnUiThread when it is time to update the UI.
ExecutorService executorPool = Executors.newSingleThreadExecutor();
executorPool.execute(new Runnable() {
public void run() {
// do background processing here <------------------
myActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// update ui here <--------------------
}
})
}
});

Android time delay

How to make a delay that could call a function after some time but the thread still should be running. Is there any better way than this.
new Thread(new Runnable() {
public void run(){
try{ Thread.sleep(recordtime); }
catch(Exception e){}
runOnUiThread(new Runnable() {
#Override
public void run() {
reset();
}
});
}
}).start();
To run some code on Ui thread , after some delay:
Handler h = new Handler(Looper.getMainLooper());
Runnable r = new Runnable() {
#Override
public void run() {
//--code run in Main, UI thread
}
};
h.postDelayed(r,2000); //-- run after 2 seconds
Handler require a Looper on target thread. UI thread already has it, other threads need to be configured first.
Other options are:
Timer:
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
//--code run in separate thread
}
},2000);
And ScheduledExecutorService:
ScheduledExecutorService se = Executors.newSingleThreadScheduledExecutor();
se.schedule(new Runnable() {
#Override
public void run() {
//--code run in separate thread
}
},2, TimeUnit.SECONDS);

Categories

Resources