Handler postDelayed doesn't post on delayed? - android

I want to change some values onBackPressed method... And i override it like this:
#Override
public void onBackPressed() {
final Handler backHandler = new Handler();
backHandler.postDelayed(new Runnable() {
public void run() {
exitCount = 0;
Log.d("exitCount", "exitCount: " + exitCount);
}
}, Toast.LENGTH_SHORT);
}
But the problem is handler posts immediately... There's no delay. Where am i doing wrong?
Sorry if this is a lame question, i'm pretty new on Android. Thanks in advance.

That is because Toast.LENGTH_SHORT value is zero. Try declaring your constant with a delay value you choose. see here

Make the handler part of an activity (or part of a thread you are posting a message to if its not for the UI thread), and use a millisecond delay rather than Toast.LENGTH_SHORT which has a value of zero so it will happen instantly.
public class SomeActivity extends Activity {
private Handler mHandler = new Handler();
#Override
public void onBackPressed() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
Log.d("tag", "Hello, Handler!");
}
}, 1000); // one second
}
}

Use belo code I hope it will work.
runOnUiThread(new Runnable() {
#Override
public void run() {
backHandler.postDelayed(new Runnable() {
public void run() {
exitCount = 0;
Log.d("exitCount", "exitCount: " + exitCount);
}
}, Toast.LENGTH_SHORT);
}
});

Related

How to update a textview frequently with a spesific time delay?

I need to update a TextView frequently with a specific time delay in the android studio. The code is below. Thank you.
Edit: I also need to end the loop with a button click or with an "if" control.
//INFLATION CALCULATION !!!
/**
* This method calculates Inflation value.
*/
public void calculateInflation() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
inflation = (cpi-cpiIni)/cpiIni*100;
displayInflation();
cpiIni = cpi;
}
}, delay*12);
}
Call the same method inside the runnable in order to keep the loop going
Use a flag in order to be able to stop the loop: shouldCalculate
private boolean shouldCalculate = true; // set to false when you want to end the loop
public void calculateInflation() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (shouldCalculate) {
inflation = (cpi-cpiIni)/cpiIni*100;
displayInflation();
cpiIni = cpi;
calculateInflation();
}
}
}, delay*12);
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
inflation = (cpi-cpiIni)/cpiIni*100;
displayInflation();
cpiIni = cpi;
customHandler.postDelayed(this, 0);
}
};
public void startTimer() {
//timer
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
public void stopTimer() {
//timer stops
customHandler.removeCallbacks(updateTimerThread);
//timer ends
}
make a reference of runnable thread , start it using startTimer() and remove thread using stopTimer() as you said on a button click or up on a specific conditions .Also you can change the postDelayed milliseconds as ur wish
Try below code. This will do the trick. If you find any problem please let me know.
public void calculateInflation() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
inflation = (cpi-cpiIni)/cpiIni*100;
displayInflation();
cpiIni = cpi;
if(shouldRepeat)
calculateInflation();
}
}, delay*12);
}
And second approach can be CountDownTimer. Make a method as shown in below code
public void timerTask(final int loopTime){
//Loop time is the actual time for repeatation
new CountDownTimer(loopTime, 1000) {
public void onTick(long millisUntilFinished) {
//this tells you one second is passed
}
public void onFinish() {
//here on time finish you need to define your task
inflation = (cpi-cpiIni)/cpiIni*100;
displayInflation();
cpiIni = cpi;
//call the same method again for looping
timerTask(loopTime);
}
}.start();
}
Simplest way. Here updateRunnable calls itself with delay. Make updateRunnable as global variable to access from anywhere.
Runnable updateRunnable = new Runnable() {
#Override
public void run() {
inflation = (cpi-cpiIni)/cpiIni*100;
displayInflation();
cpiIni = cpi;
handler.postDelayed(this, UPDATE_TIME);
}
};
Start handler. Here we start handler immediately without delay.
handler.postDelayed(updateRunnable, 0)
Stop handler
handler.removeCallbacks(updateRunnable)
By the way don't forget to stop handler on onDestroy()

Show Toast in a Thread of a Service

Hi i know there are lot of answers to this topic. But I tried a lot and it doesn't work. I want to show a toast inside a thread of a service. How can i solve this problem. Using getApplicationContext() etc. doesn't work.
I start the Service from an Activity (no bounding).
public class CarDataService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
startThreadUpdatingDatabase();
Toast.makeText(this, message, Toast.LENGTH_LONG).show(); //it works
}
private void startThreadUpdatingDatabase(){
Log.d("Database", "startThreadUpdatingDatabase(was called)");
new Thread(new Runnable() {
public void run(){
..
// here i want to use a toast!!!
}
}).start();
}
}
Thank you!
You have to start the thread:
new Thread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Your message",Toast.LENGTH_LONG).show();
}
}).start();
public Contect context;
member variable
onStartCommand(){
context = getApplicationContext)
}
acquivre reference to the context before you start the thread
new Thread(new Runnable() {
#Override
public void run() {
Toast.makeText(context,"Your message",Toast.LENGTH_LONG).show();
}
}).start();
and there you go
use AsyncTask instead that helps in context management
http://www.androidsnippets.com/use-toast-wherever-you-want
Handler h = new Handler(context.getMainLooper());
h.post(new Runnable() {
#Override
public void run() {
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
});
see if this works out
Show your Toast using UI-Thread
new Thread(new Runnable() {
#Override
public void run() {
// SHOW TOAST
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(yourContext, "Hello from UI-thread", Toast.LENGTH_SHORT).show();
}
});
//... start DB work
}
}).start();
If you have no access to an activity, so do it this way:
new Thread(new Runnable() {
#Override
public void run() {
// no activity, so use Handler & mainlooper
new Handler(Looper.getMainLooper()).post(
new Runnable() {
public void run() {
// yourContext is Activity or Application context
Toast.makeText(yourContext, "Hello from UI-thread", Toast.LENGTH_SHORT).show();
}
}
);
//... start DB work
}
}).start();
Look at this: Static Way to get Context on android?

Updating UI using a Handler freezes my app

I am trying to make a clock, using a TextView :)
Someone here told me that I couldn't use normal threads to change the UI, but Handler or AsyncTask. I managed to get it working a few days ago, but was not a consistent thread.
Now what I want is a consistent thread that is always changing the text of my Textview. I tried using this, but didn't work, any help?
private void startClock() {
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
while (true) {
final long millis = System.currentTimeMillis() - MainActivity.startedAt;
clock.setText("" + millis);
runOnUiThread (new Runnable() {
#Override
public void run() {
clock.setText("" + millis);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, 2000);
}
you should get rid of:
while(true) {
....
sleep(1000);
...
}
because this get your thread stuck forever. your program should work like this:
private Handler mHandler = new Handler();
#Override
public void onResume() {
super.onResume();
mHandler.removeCallbacks(mUpdateClockTask);
mHandler.postDelayed(mUpdateCLockTask, 100);
}
#Override
public void onPause() {
super.onPause();
mHandler.removeCallbacks(mUpdateClockTask);
}
private Runnable mUpdateClockTask = new Runnable() {
public void run() {
updateClock();
mHandler.postDelayed(mUpdateClockTask, 2000);
}
};
and inside updateClock() you do all your UI updates.
Look here for an example https://stackoverflow.com/a/11140429/808940
Also note that you have a duplicate line in your code:
clock.setText(""+millis);
It appears both in the runOnUiThread and in the main handler, it should only appear in the runOnUiThread runnable

Timer and TextView

I'm trying to understand how to use a timer.
In my MainActivity.class, inside on create method, i have this code
Timer timer = new Timer();
TimerTask updateM = new GestioneSlide();
timer.scheduleAtFixedRate(updateM , 1000, 5000); // i want to do a thing every second for 5 seconds
then i have another class where i override the method run, and where i want to write something in a texview that is in my MainActivity.class
class GestioneSlide extends TimerTask {
#Override
public void run() {
MainActivity.TextViewName.setText("bla bla");
}
}
My app crash, if i delete the MainActivity.TextViewName.setText("bla bla"); i have no problem. Probably i can't write in that textview that way
What did i do wrong?
The timer does not fire its actions in GUI thread. Use runOnUiThread to switch into it. Assuming GestioneSlide is the inner class of your Activity, write
class GestioneSlide extends TimerTask {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
MainActivity.TextViewName.setText("bla bla");
}
}
}
Make a Handler and show msg inside handler.
private class mainTask extends TimerTask
{
public void run()
{
toastHandler.sendEmptyMessage(0);
}
}
private final Handler toastHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show();
}
};

Delay actions in android

I want to change the image in imageView after 5 seconds from app start.
This is the code that I tried so far:
public class MainActivity extends Activity {
ImageView screen;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen=(ImageView)findViewById(R.id.imageView1);
screen.setImageResource(R.drawable.ic_launcher);
}
}
You can use a Handler, such as:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// change image
}
}, 5000); // 5000ms delay
As Sam says in the comments, you could also do this (because all Views have their own handler):
screen.postDelayed(new Runnable() {
#Override
public void run() {
// change image
}
}, 5000); // 5000ms delay
See the Handler Documentation.
you can try thread like this:
new Thread(){
public void run(){
//sleep(5000);
//refreshSthHere();
}
}.start();
You can use Handler like Tom Leese said or Java Timer
new Timer().schedule(new TimerTask() {
#Override
public void run() {
// this code will be executed after 2 seconds
}
}, 2000);

Categories

Resources