I am trying to get my current location each 1 second. The method getlocationCoordinate allows to return my current lattitude and longitude.
So I implemented a timertask that is supposed to run every 1 second and return my current location, but the timertask is only running once, how can i fix this problem?
Timer timer= new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
Looper.prepare();
System.out.println(" show me current location " + getlocationcoordinate(getApplicationContext()));
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "current location" +getlocationcoordinate(getApplicationContext()), Toast.LENGTH_SHORT).show();
}
});
Looper.loop();
}
},0,1000);
for some reason timer does not work as we would like,You can use a Handler
private Handler handler;
private Runnable runnable;
handler = new Handler();
handler.postDelayed(runnable, 1000);
runnable = new Runnable() {
#Override
public void run() {
try{
System.out.println(" show me current location " + getlocationcoordinate(getApplicationContext()));
}
catch(Exception e){
e.printStackTrace();
}
handler.postDelayed(this, 1000); //start again
}
};
source here
Related
I have created a handler for an alert that should activate for 4 seconds, stops for 4 seconds, and activates again. When i put it in the if statement, it doesn't work; the alert keeps playing, stops for less than a second and continues activating again without the delay. Wonder if anyone knows why is it happening and what should i do to correct it. Thank you.
private Handler handler2 = new Handler();
private Runnable startalert = new Runnable() {
#Override
public void run() {
alert2.start();
handler2.postDelayed(this, 4000);
}
};
#Override
public void onLocationChanged(Location location) {
if (location == null) {
speedo.setText("-.- km/h");
}
else {
currentSpeed = location.getSpeed() * 1.85f; //Knots to kmh conversion.
speedo.setText(Math.round(currentSpeed) + " km/h");
}
if (currentSpeed <=4.99) {
background.setBackgroundColor(Color.GREEN);
handler2.removeCallbacks(startalert);
} else if(currentSpeed >=5.00 && currentSpeed <=9.99) {
background.setBackgroundColor(Color.YELLOW);
handler2.removeCallbacks(startalert);
} else if(currentSpeed >=10.00) {
background.setBackgroundColor(Color.RED);
startalert.run();
}
}
Instead of 'this', use runnable object.
private Runnable startalert = new Runnable() {
#Override
public void run() {
alert2.start();
handler2.postDelayed(startalert, 4000);
}
};
Another method:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
alert2.start();
handler.postDelayed(this, 4000);
}
}, 4000);
I have a situation where I need to update the notification progress bar after some few more milliseconds. If I use notification manager to update the progress, then the notification will show up even after calling stopForground(true) which is not what I need.
Here is the sample code using the notification manager to update.
private void doStuff() {
// starting in foreground
startForeground(123, notification.build());
final Thread thread = new Thread(new Runnable() {
#Override
public void run() {
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
timer++;
if(timer > 10){
stopForeground(true);
stopSelf();
return;
}
if(!bound){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
notificationManager.notify(123, notification.setProgress(10, timer, false).build());
}
}, 2000);
}
handler.postDelayed(this, 1000);
}
}, 1000);
}
});
thread.start();
}
otherwise, if I use startForground() way, the notification won't show up after the 2000 milliseconds and I get the desired behavior as shown below:
private void doStuff() {
// starting in foreground
startForeground(123, notification.build());
final Thread thread = new Thread(new Runnable() {
#Override
public void run() {
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
timer++;
if(timer > 10){
stopForeground(true);
stopSelf();
return;
}
if(!bound){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startForeground(123, notification.setProgress(10, timer, false).build());
}
}, 2000);
}
handler.postDelayed(this, 1000);
}
}, 1000);
}
});
thread.start();
}
My question is if there would be something wrong I'm not aware of using this way because I have never seen anyone doing it. Please help! Thanks!
I have two Buttons in main View, Button1 and Button2. How can I disable Button1 for specific time period after that time period it should Enable again.
Use a countdown Timer.
Say you have button button1 ;
button1.setEnabled(false);
new CountDownTimer(5000, 10) { //Set Timer for 5 seconds
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
button1.setEnabled(true);
}
}.start()
Aba: Applied correct View.setEnabled method.
Here is an example:
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run(){
button.setEnabled(false);
}
}, 5000);
Rest, figure out yourself.
You can call this method. Try this once
private void blink(){
final Handler handler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
int timeToBlink = 5000;
try{
Thread.sleep(timeToBlink);
}catch (Exception e) {
}
handler.post(new Runnable() {
#Override
public void run() {
if(button.isEnabled()){
button.setEnabled(false);
}else{
button.setEnabled(true);
}
blink();
}
});
}
}).start();
}
By calling this method You will get the effect you wanted
private fun initButton() {
button.setOnClickListener {
it.isEnabled = false
it.postDelayed({ it.isEnabled = true }, 3000)
//do stuff
}
}
This works in Kt, does require a handler tho
In the simplest way
yourView.setEnabled(false);
yourView.postDelayed(() -> yourView.setEnabled(true), 5000); // Wait for 5 seconds
How do i set a timer for TextView ? This code keeps crashing my app
final TextView textwel = (TextView) findViewById(R.id.welcometext);
Thread timer = new Thread() {
public void run() {
try {
// this should sleep for 4 seconds
sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
textwel.setText("Welcome");
}
};
start the timer
timer.start();
That won't work.
Since the new thread that you create is not the UI thread, you can't update the UI (setting the text of a text view) on that thread.
A better way to do this would be to use the android.os.Handler class. It has a postDelayed method that will execute a Runnable with a delay. Here is the docs.
Alternatively, you can use this Timer class I wrote, which encapsulates a Handler instance and has a simple interface:
import android.os.Handler;
public class Timer {
private Handler handler;
private boolean paused;
private int interval;
private Runnable task = new Runnable () {
#Override
public void run() {
if (!paused) {
runnable.run ();
Timer.this.handler.postDelayed (this, interval);
}
}
};
private Runnable runnable;
public int getInterval() {
return interval;
}
public void setInterval(int interval) {
this.interval = interval;
}
public void startTimer () {
paused = false;
handler.postDelayed (task, interval);
}
public void stopTimer () {
paused = true;
}
public Timer (Runnable runnable, int interval, boolean started) {
handler = new Handler ();
this.runnable = runnable;
this.interval = interval;
if (started)
startTimer ();
}
}
Gist
You would probably use it like this:
Runnable run = new Runnable() {
public void run() {
textwel.setText("Welcome");
}
};
Timer timer = new Timer(run, 4000, true);
P.S. setting the textview's text to "Welcome" every 4 seconds is pointless.
You can you use CountDownTimer api to update TextView timer which is very easy to use and convenient.
Here is the simple example:
TextView tvTime = (TextView)findViewById(R.id.tv_time);
CountDownTimer countDownTimer = new CountDownTimer((durationInMilis * 60000), 1000) {
#Override
public void onTick(long millisUntilFinished)
{
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
tvTime.setText(hms);
}
#Override
public void onFinish()
{
// Do your other task on finish
}
}.start();
This code this will update tvTime text every second and run for sepecified amount of time in durationInMilis. Output will look like hh:mm:ss e.g 01:23:57
If you don't want show anything on update then leave onTick() callback blank and update your TextView in onFinish(). Just pass value to parameter durationInMilis for which you want to run timer.
If you have any doubt please feel free to comment.
//use it, its easy and simple
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
textwel.setText("Welcome");
}
}, 4000);
why are you using textview??
Chronometer is a class provided by android that implements a simple timer so my suggestion is use it in place of textview.
here is the official link
try this , it will work 100% and also UI will not stuck
Thread timer = new Thread() {
public void run() {
try {
// this should sleep for 4 seconds
sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// after sleep call a UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
textwel.setText("Welcome");
}
});
}
};
I am using a hanfler within the service to call a method after a delay in android. Its not working for long delays but the same code works for small delay.
Handler mHandler;
Runnable runnable;
mHandler = new Handler();
runnable=new Runnable() {
#Override
public void run() {
Log.i("START SERVICE", "START SERVICE:3 Call to Check Status is called");
callToCheckStatus();
mHandler.postDelayed(this, 1000*60*60);
}
};
mHandler.postDelayed(runnable, 1000*60*60);
On some blogs i find that when device goes deep sleep then it does not work. SO whats the right way to call a method within in Android.
Try This
public static void intertiAdsStartTimer(Context cnxt) {
timer = new Timer();
initializeTimerTask(cnxt);
//timer.schedule(timerTask, delayTime, repeatedTime);
timer.schedule(timerTask, 0, Integer.parseInt("7") * 60 * 1000); //
}
public static void initializeTimerTask(final Context cnxt) {
try {
final Handler handler = new Handler(Looper.getMainLooper());
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
try {
//call your method
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
} catch (Exception e) {
e.printStackTrace();
}
}
OR
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 10s = 10000ms
}
}, 10000);