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);
Related
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);
}
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 am writing a Location Service, with a update Interval to send the Location updates to the server.
But I trying to update this interval variable in the service via user input(AlertDialog). It works perfectly fine when hard coded.
I am using this code to get the interval variable from the AlertDialog class, in the onCreate() of the service.
public void onCreate() {
super.onCreate();
final boolean tr=true;
new Thread(new Runnable() {
public void run() {
while (tr) {
//check your static variable here
updateInterval=ShowCurInterval.loadCurInterval(getApplicationContext());//ShowCur Interval is the Alert Dialog calss
Log.d(" INTERVAL ","Interval "+ updateInterval);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}}
).start();
startLocationListener(updateInterval);
}
And I can also see the new updateInterval value in Log ( which is added from the Alert Dialog). But requestLocationUpdates() still uses the pre defined updateInterval value.
Here is the startLocationListener() method:
public void startLocationListener(int updateInterval) {
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locManager.removeUpdates(locListener);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, updateInterval, updateDistance, locListener);
Log.d(getClass().getSimpleName(), "Loclistener started, Updatetime: " + updateInterval);
Toast.makeText(getApplicationContext(), "UPDATE INTERVAL"+updateInterval,Toast.LENGTH_SHORT );
preInterval = updateInterval;
}
Does anyone have any suggestions how can I update this variable?
#binW
Edited part with exception:
Handler mhandler = new Handler ();
mhandler.postDelayed( new Runnable(){
public void run(){
Looper.prepare();
updateInterval=SingletonManager.getInstance().loadCurInterval(getApplicationContext());
SingletonManager.getInstance().saveCurInterval(getApplicationContext(), updateInterval);
startLocationListener(updateInterval);
Log.d(" INTERVAL ","Interval "+ updateInterval);
//startChecking();
}
}, 2000);
Exception:
04-17 03:18:55.250: E/AndroidRuntime(2146): java.lang.RuntimeException: Only one Looper may be created per thread
Thank You in advance.
you are calling startLocationListener() in onCreate() and not in the thread that you created for getting the new value of updateInterval. But the call to startLocationListener(updateInterval); gets executed before the new thread executes and hence you get the old value of updateInterval. I believe you should change your code to following:
public Handler handler;
public void onCreate() {
super.onCreate();
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
startLocationListener(updateInterval);
}
};
final boolean tr=true;
new Thread(new Runnable() {
public void run() {
while (tr) {
//check your static variable here
updateInterval=ShowCurInterval.loadCurInterval(getApplicationContext());//ShowCur Interval is the Alert Dialog calss
handler.sendEmptyMessage(1);
Log.d(" INTERVAL ","Interval "+ updateInterval);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}}
).start();
}
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);
I have a service B that sends a specific number of messages in a fixed interval.
this service is called from another service A.
the code used in service A is
#Override
public void onStart (Intent intent,int startid)
{
Toast.makeText(this, "Service A Running onStart", Toast.LENGTH_LONG).show();
Thread MessagesThread = new Thread(new Runnable()
{
public void run()
{
ApplicationPreferences AppPrefs = new ApplicationPreferences(getApplicationContext());
int NumberOfMessagesToSend = Integer.parseInt(AppPrefs.getNumberOfMessagesToSend());
int NumberOfSentMessages;
for (NumberOfSentMessages = 0 ; NumberOfSentMessages < NumberOfMessagesToSend; NumberOfSentMessages++ )
{startServiceB();
}
}
});
MessagesThread.start();
}
public void startServiceB()
{
final Intent sendingMessages = new Intent(this, ServiceB.class);
startService(sendingMessages);
}
the toasts are to keep track of what is happening
The code in service B is as follow
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Toast.makeText(getApplicationContext(), "Service B at start ", Toast.LENGTH_LONG).show();
new CountDownTimer(30000,1000)
{
public void onTick (long millisUntilFinished) {}
public void onFinish()
{
showToast();
}
}.start();
}
the showToast() function is as follow
public void showToast()
{
Toast.makeText(getApplicationContext(), "Service B in timer", Toast.LENGTH_LONG).show();
}
As I said I am using the toasts to keep track of what's happening. the problem is when running it, i am getting the first toast (service B at start) 10 times consequently then the second one (service B in timer) 10 times consequently with no time between them.
how do i make each of this toasts appear once every 30 seconds?
Ok, so the final answer could be something like this:
Call only once the B service and in it we will have the handler that will loop at an interval of 30 seconds..
Service B code:
int loop = 5;
int counter = 0;
Handler myHandler;
Runnable run;
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Toast.makeText(getApplicationContext(), "Service B at start ", Toast.LENGTH_LONG).show();
myHandler = new Handler();
run = new Runnable()
{
public void run()
{
if (counter<loop){
showToast();
counter++;
} else {
myHandler.removeCallbacks(run);
}
}
};
myHandler.postDelayed(run, 30000);
}
I hope this helps someone else too!
If you want to make a toast every 30 seconds than you can do it by using a handler:
Handler myHandler = new Handler();
Runnable run = new Runnable()
{
public void run()
{
showToast();
}
};
myHandler.postDelayed(run, 30000);
If you have problem with this just post here and I will try to help you..