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);
}
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);
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
Is there any way to show a toast when the service is running on a separate thread?
I use the code below.
public void onStart(Intent intent, int startid){
final String name = intent.getStringExtra("name");
Log.d(TAG,"onStart()");
new Thread(new Runnable() {
public void run() {
try
{
Toast.makeText(getApplicationContext(), "Ashish 1",Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Log.d(TAG,"Exception....."+e);
}
}
}).start();
}
Toast messages can only shown on uithread. But if you want to use on another thread, you can implement it like this.
yourActivityObject.runOnUiThread(new Runnable() {
public void run()
{
Toast.makeText(yourContextObject, "some text",Toast.LENGTH_LONG).show();
}
});
I'm trying to send a toast notification of an error in a thread. The thread is started in a service that is called from the main thread. I've tried several things with View.post and some weird handler stuff, but nothing seems to work. An excerpt of the thread is as follows:
public int onStartCommand(Intent intent, int flags, int startId)
{
new Thread(new Runnable(){
public void run() {
boolean bol = true;
while (bol)
{
try
{
//Some socket code...
}
catch (Exception e)
{
//Where I want the toast code.
}
}
}
}).start();
return START_STICKY;
}
Try following inside the thread in the service:
Handler h = new Handler(context.getMainLooper());
// Although you need to pass an appropriate context
h.post(new Runnable() {
#Override
public void run() {
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
});
Taken from answer given by #Alex Gitelman here on Android: How can i show a toast from a thread running in a remote service? . This might help somebody as it helped me.
Toast can be shown only from UI Thread (Main Thread). To show Toast from some other threads you have to use Handler.
Threads, Handlers and AsyncTask
Yes you should use a Handler, and bind you Activity to your Service
Once the Handler is set, here is what you should do,
Message msg = Message.obtain(null, MyActivity.TOAST);
Bundle bundle = new Bundle();
bundle.putString(MyActivity.TOAST_MSG, "Toast message");
msg.setData(bundle);
try {
myActivityMessenger.send(msg);
} catch (RemoteException e) {
if (D) Log.w(TAG, "Unable to send() the toast message back to the UI.");
e.printStackTrace();
}
myActivityMessenger is set with the Handler of your MyActivity and sent to the Service when you bind MyActivity to it.
However displaying a Toast with a Service as context should work (but it's not the best way), so maybe it's because you try to make it from a new Thread. What is your code for making the Toast ?
new Thread(){
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
_dialog.dismiss();
Toast.makeText(LatestNewsActivity.this, "NO Internet Connection Available", Toast.LENGTH_LONG).show();
}
});
}
}.start();