i have a function To run messages in a queue. But when I run this the last handler gets executed only, not the first one! Help!
void functionShow()
{
button.setVisibility(View.INVISIBLE);
txt.setText("Generating Unique ID ... Please Wait ");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
txt.setText("Sending SMS ... Please Wait");
}
}, 10000);
Handler handler1 = new Handler();
handler1.postDelayed(new Runnable () {
public void run()
{
txt.setText("Done");
}
}, 10000);
}
All i am trying to do is: First text should come as "Generating Unique ID ... " Then after 10 secs "Sending SMS ... " Then again after 10 secs "Done"
Both have the same delay... I guess the first one is being executed and a couple of milliseconds after that the second one is executed; so it looks like the second one is the only that is being executed.
The ugly way:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
txt.setText("Sending SMS ... Please Wait");
postDelayed(new Runnable () {
public void run(){
txt.setText("Done");
}
}, 10000);
}
}, 10000);
The cool way:
private static final int SENDING = 1;
private static final int DONE = 2;
Handler handler = new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
case SENDING:
txt.setText("Sending SMS");
sendEmptyMessageDelayed(DONE, 10000);
break;
case DONE:
txt.setText("Done");
break;
}
}
};
handler.sendEmptyMessageDelayed(SENDING, 10000);
Related
thread = new Thread() {
public void run() {
super.run();
System.out.println("run:" + Thread.currentThread().getName());
Looper.prepare();
handler = new Handler();
Looper.loop();
};
};
thread.start();
And then
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MActivity.this,Thread.currentThread().getName(),0).show();
}
});
the code run correct.
but the toast shows :"Thread-217"
that means the toast shows from a non-uithread.
why?
I am so sorry. I know answer. Toast is a special UI element. It can be showed from any thread. But the other UI elements ,such as Button TextView must only be touched in the UI-thread.
So,my code runs correct,but when you change the toast to Button ,is crashed.
You are trying to show toast in a UI thread using runnable thats why its going wrong
Thread background = new Thread(new Runnable() {
public void run() {
// Send message to handler
handler.sendMessage(msgObj);
}
};
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
//Catch the response and show the toast
String aResponse = msg.getData().getString("message");
Toast.makeText(getBaseContext(),"Not Got Response From Server.",
Toast.LENGTH_SHORT).show();
}
};
You must create the Handler in UiThread. The handler send the message to thread where it was created.
handler = new Handler();
thread = new Thread() {
public void run() {
super.run();
System.out.println("run:" + Thread.currentThread().getName());
Looper.prepare();
Looper.loop();
};
};
thread.start();
I am using a toast for Count Down Timer, so the toast should change it's text in every second. I use this to display the toast for exactly 1 second but i want the toast to repeat itself. Hope i make you understand.
toast = Toast.makeText(getApplicationContext(), text.getText().toString(), Toast.LENGTH_SHORT); toast.show();
Handler handler = new Handler();
handler.postDelayed
(new Runnable() {
#Override
public void run() {
toast.cancel();
}
}, 1000);
This will show a new toast every second for exactly one second.
int count = 100; //Declare as inatance variable
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
final Toast toast = Toast.makeText(
getApplicationContext(), --count + "",
Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toast.cancel();
}
}, 1000);
}
});
}
}, 0, 1000);
run() is called after every second. so show toast there.
Handler handler = new Handler();
handler.postDelayed
(new Runnable() {
#Override
public void run() {
toast.cancel();
toast = Toast.makeText(getApplicationContext(), text.getText().toString(),Toast.LENGTH_SHORT);
toast.show();
}
}, 1000);
This page describes a way to keep the toast be shown indefinitely. So when you have the text view of the toast on hand, you may change the text as you like.
you have to learn more about android srvices
create java class extends from IntentService
override this function
#Override
protected void onHandleIntent(Intent intent) {
try {
Toast.makeText(context,"Click on Location button to find your bus !",Toast.LENGTH_LONG).show();
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
go to manifest an type
go to your launcher java class and
Intent intent = new Intent(this, Service_toast.class);
startService(intent);
====>> for more information about services vist android devloper :
https://developer.android.com/guide/components/services.html
i want to do some stuff on every few seconds in my app, for that purpose , i have implemented HandlerThread & handler via following code
handlerThread = new HandlerThread(getClass().getSimpleName());
handlerThread.start();
handler = new Handler(handlerThread.getLooper(), new Callback() {
#Override
public boolean handleMessage(Message msg) {
//my code here
return l.this.handleMessage(msg);
}
});
I initiate this handler by sending message from onCreate()
I handle the message as follows :
private boolean handleMessage(Message msg) {
switch (msg.what) {
default:
return false;
case MY_MESSAGE:
if(handler_stop==0)
{
checkLauncher();
sendMessage(MY_MESSAGE); // I Send the message from here to make //this continuous
}
}
return true;
}
It's Working fine but it Sends message too fast , i mean constantly , instead i want this message to be sent after 2 or 3 seconds , In Short , i want to repeat task every 2-3 seconds.
How can i do this on above code ? please some one help
First declare one global varialbe for Handler to update the UI control from Thread, like below:
Handler mHandler = new Handler();
Now create one Thread and use while loop to periodically perform the task using the sleep method of the thread.
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);// change the time according to your need
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// Write your code here to update the UI.
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
Else just add this in your code:
handler.postDelayed(new Runnable(){
public void run() {
// do something
}}, 20000);
Why not to use Handler.sendMessageDelayed? It allows you to schedule your message to be delivered to the Handler with delay that you specify. So your code will look like this:
private boolean handleMessage(Message msg) {
switch (msg.what) {
default:
return false;
case MY_MESSAGE:
if(handler_stop == 0) {
checkLauncher();
sendMessageDelayed(MY_MESSAGE, 2000); // Send message everytime with 2 seconds delay
}
}
return true;
}
hi i have an simple way for doing this
try this
Runnable runnable;
final Handler handler = new Handler();
runnable = new Runnable() {
public void run() {
// HERE I AM CHANGING BACKGROUND YOU CAN DO WHATEVER YOU WANT
_images[i].setBackgroundResource(imageArray[0]);
i++;
handler.postDelayed(this, 1000); // for interval...
}
};
handler.postDelayed(runnable, 1000); // for initial delay..
worked for me hope you will also find it working
thanks
Vote Up if find usefull.
I have a HandlerThread, to which I keep posting a runnable every 5 seconds. Something like this:
HandlerThread thread = new HandlerThread("MyThread");
thread.start();
Handler handler = new Handler(thread.getLooper());
handler.post(new Runnable() {
public void run() {
//...
handler.postDelayed(this, 5000);
}
});
I need to quit the looper at some point, after 60 seconds or something like that.. so I write:
mainHandler = new Handler(Looper.myLooper()); //main thread's
mainHandler.postDelayed(new Runnable() {
#Override
public void run() {
thread.getLooper().quit();
}
}, 60000);
I think this causes the looper to quit abruptly, so I start getting this "warning" messages:
W/MessageQueue(3726): java.lang.RuntimeException: Handler
(android.os.Handler) {4823dbf8} sending message to a Handler on a dead
thread
I want to avoid this error msg, I thought that I could solve it by using the Looper.quitSafely() method.. but I checked the API and it's no longer available.
Does anyone know what happened to it? (It's not deprecated like some other methods).
Is there some way I can quit the looper safely? Thanks!
You could try to use a boolean to know if the code should be executed. Something like this:
private boolean runHandler = true;
...
HandlerThread thread = new HandlerThread("MyThread");
thread.start();
Handler handler = new Handler(thread.getLooper());
handler.post(new Runnable() {
public void run() {
if(runHandler){
//...
handler.postDelayed(this, 5000);
}
}
});
mainHandler = new Handler(Looper.myLooper()); //main thread's
mainHandler.postDelayed(new Runnable() {
#Override
public void run() {
runHandler = false;
}
}, 60000);
Im not Thread Guru, but this way can give you direction:
...
_thread.setRunning(true);
_thread.start();
..
public void stopThread(){
boolean retry = true;
_thread.setRunning(false);
while (retry) {
try {
_thread.join();
retry = false;
Log.e("test", "thread stopped");
} catch (InterruptedException e) {
Log.e("test", "can't stop thread, retrying...");
// we will try it again and again...
}
}
}
In your thread:
while (isRunning) {
//...
}
1st all you implement run method in loop (while(isRunnig){}).
On finish, you switch flag to false and "wait" for join.
I am scheduling a simple task that should update a text field in 4 seconds.
However everytime this is called the activity pauses and does not show the value in the text field until I restart the activity.
private void showDelayedValue() {
Runnable longRunningTask = new Runnable() {
public void run() {
int randomVal = randomNumberGenerator.nextInt(30 - -10) - 10; //random number between -10 and 30
String randomValStr = Integer.toString(randomVal);
Log.i(this.getClass().getSimpleName(),
"FIRED startScheduler: " + randomValStr);
theFieldOnScreenTV.setText(randomTempStr);
}
};
//show the value in 2 seconds
scheduledTaskExecutor.schedule(longRunningTask, 4, TimeUnit.SECONDS);
}
The log shows:
FIRED startScheduler: 4
but does not update the TextView theFieldOnScreenTV
Instead onPause is called right after Fired startScheduler: is displayed in LogCat.
Many thanks!
EDIT:
This worked for me following Alex' approach:
private void showDelayedValue() {
int randomX = randomNumberGenerator.nextInt(30 - -10) - 10;
final String randomXStr = Integer.toString(randomX);
final Runnable updateFieldR = new Runnable() {
public void run() {
theFieldOnScreenTV.setText(randomXStr);
}
};
Runnable longRunningTask = new Runnable() {
public void run() {
theFieldOnScreenTV.post(updateFieldR);
}
};
scheduledTaskExecutor.schedule(longRunningTask, 4, TimeUnit.SECONDS);
}
instead of
theFieldOnScreenTV.setText(randomTempStr);
try
theFieldOnScreenTV.post(new Runnable() { theFieldOnScreenTV.setText(randomTempStr); } );
Have a try using Handlers.
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
theFieldOnScreenTV.setText(randomTempStr);
}
});