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
Related
I want to delay seconds and show Toast,I try to SystemClock.sleep
But it only show last message("10s")...
Toast.makeText(MainActivity.this,"1s", Toast.LENGTH_SHORT).show();
SystemClock.sleep(5000);
Toast.makeText(MainActivity.this,"5s", Toast.LENGTH_SHORT).show();
SystemClock.sleep(5000);
Toast.makeText(MainActivity.this,"10s", Toast.LENGTH_SHORT).show();
That should be displayed in sequence 1s, 5s, 10s is not it?
I also made reference to this practice, but it can not be achieved...
How to set delay in android?
So does the problem lie?
Try Handler
public void showToast(final String message, int timeInMilliSeconds, final Context context) {
Runnable runnable = new Runnable() {
#Override
public void run() {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
};
Handler handler = new Handler();
handler.postDelayed(runnable, timeInMilliSeconds);
}
Usage:
showToast("1s, 1000, this);
showToast("5s, 5000, this);
showToast("10s, 10000, this);
I need a delay for around 5 seconds. I have tried using Timer using below code :
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
Log.d(TAG,"Timer");
}
}, 4000, 5000);
When i check logs, the Timer is getting printed thrice. If I change time, sometimes it gets printed in log 4 times as well.
I have tried using Handler as well like below :
final Handler mHandler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Log.d(Utility.TAG,"Sleep::");
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
But again the log is printing multiple times. I just want to call my method once not multiple times. How can I achieve it ?
EDIT
used handler without thread as well like below :
final Handler h = new Handler();
final int delay = 3000; //milliseconds
h.postDelayed(new Runnable(){
public void run(){
//do something
h.postDelayed(this, delay);
Log.d(Utility.TAG,"Sleep ::");
}
}, delay);
But again, Log is getting printed thrice
Your third approach (no Timer, no Thread) is the closest to being correct. It's printing multiple times because the Runnable is re-posting itself every time it runs. If you only want it to run once, remove this line from the run() method:
h.postDelayed(this, delay);
I want to display two different Toast. The second one shall appear 8 seconds after the second one.
I tried to code this :
#Override
public void onReceive(Context context, Intent intent) {
Toast toast1 = new Toast(context);
Toast toast2 = new Toast(context);
//toast1
toast1.makeText(context, "First toast ", Toast.LENGTH_SHORT).show();
//wait for 8 seconds
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//toast2
toast2.makeText(context, "Toast2 ", Toast.LENGTH_SHORT).show();
Unfortunately, only the second toast appears. I don't know if the error is from my wrong use of toast or my wrong use of threads !
Thank you
You can't just stop the UI Thread.
Use a Handler (Android way) or TimerTask (Java way) for this.
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(someContext, "someText", Toast.LENGTH_SHORT).show();
}
}, 8000);
You can use Handler .
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue.
#Override
public void onReceive(Context context, Intent intent) {
Toast toast1 = new Toast(context);
Toast toast2 = new Toast(context);
toast1.makeText(context, "First toast ", Toast.LENGTH_SHORT).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
toast2.makeText(context, "Toast2 ", Toast.LENGTH_SHORT).show();
}
}, 8000);
Stopping the UI thread is not possible. You have to use some Handlers for this.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
toast1.makeText(context, "First toast ", Toast.LENGTH_SHORT).show();
}
}, 8000);
I Simply Put
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"First",Toast.LENGTH_LONG).show();
try{
Thread.sleep(2000);
}catch(Exception e){
}
Toast.makeText(context,"Second",Toast.LENGTH_LONG).show();
}
And it Worked...
But My suggestion is you should not stop UI Thread, Use Handler as #IntelliJ Amiya said.
Modify your code with this:
#Override
public void onReceive(Context context, Intent intent) {
Toast toast1 = new Toast(context);
Toast toast2 = new Toast(context);
//toast1
toast1.makeText(context, "First toast", Toast.LENGTH_SHORT).show();
//toast2
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
toast2.makeText(context, "Second toast", Toast.LENGTH_SHORT).show();
}
}, 8000);
}
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 want to present bitmap images from a internetstream. Every 500 millisec i get a new image and i want to present this image to the user. What is the best way to do this? Can i use an image view and chenge the image every 500 millisec?
I tried to do this in an timer task like this:
timer.schedule(new TimerTask() {
public void run() {
if(flag){
Bitmap bmp = null;
Log.i(APPID, "New frame");
try {
bmp = session.getImage();
setImage(bmp);
} catch (Exception e) {
e.printStackTrace();
}
} else {
timer.cancel();
}
}
}, 500, 500);
But this does not work.
Updating the UI from a thread other than the UI/main thread will fail as Android does not allow it. Try using a Handler to post messages back to the UI thread. You could do something like this.
final Handler h = new Handler();
timer.schedule(new TimerTask() {
public void run() {
if(flag){
h.post(new Runnable() {
public void run() {
Bitmap bmp = null;
Log.i(APPID, "New frame");
try {
bmp = session.getImage();
setImage(bmp);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
timer.cancel();
}
}
}, 500, 500);
Timer task runs on a different thread. you need to update ui on the ui thread. You should use runOnUiThread or Handler
runOnUiThread(new Runnable() //run on ui threa
{
public void run()
{
// update ui here
}
});
Handler
Handler m_handler;
Runnable m_handlerTask ;
m_handler= new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
// do soemthing
m_handler.postDelayed(m_handlerTask, 1000);
// change 1000 to whatever you want
}
};
m_handlerTask.run();
When you wan to cancel call this m_handler.removeCallbacks(m_handlerTask).