Delay is not working after 1 hour - java

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);

Related

Why is there no delay on Handler?

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);

Can I use startForeground(id, notification) in a service to update notification progress bar properly?

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!

how to fix Timertask is running only once?

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

Auto updating UI with a different thread

I have an Android App which constantly auto updating a list of data from the App's SQLite which an ArrayAdapter is used for handling the data, So for this I've made another thread or handler from the onCreate method of the Acitivity, and inside it's code there's a continuous loop for updating then waiting (or sleeping the thread for a moment, ex/ 10 sec), There are two problems involved:
1- Only the UI thread can touch it's views (though I only touched ArrayAdapter if it counts as a View).
2- Once the other thread starts to run, The UI thread seems to stuck in it, and won't update even the first UI update (complete white).
codes for the autoUpdate() method: (which is called on the last line of the UI onCreate method):
public void startAutoUpdateLogData(final int milliseconds){
continueAutoUpdate = true;
new Thread(){
#Override
public void run() {
while(continueAutoUpdate){
try{
Log.v("updating..", "");
updateLogFromDatabase();
Thread.sleep(milliseconds);
}catch(Exception e){
e.printStackTrace();
}
}
}
}.start();
}
OR:
public void startAutoUpdateLogData2(final int milliseconds){
continueAutoUpdate = true;
runOnUiThread(new Runnable() {
#Override
public void run() {
while(continueAutoUpdate){
try{
Log.e("updating...", "");
updateLogFromDatabase();
Thread.sleep(milliseconds);
}catch(Exception e){
e.printStackTrace();
}
}
}
});
}
OR
public void startAutoUpdateLogData3(final int milliseconds){
continueAutoUpdate = true;
final Handler handler = new Handler();
runOnUiThread(new Runnable() {
#Override
public void run() {
while(continueAutoUpdate){
try{
handler.postDelayed(new Runnable(){
public void run(){
Log.e("updating...", "");
updateLogFromDatabase();
}
}, milliseconds);
}catch(Exception e){
e.printStackTrace();
}
}
}
});
}
Neither of these work.
You can do many ways. But this one will be more closer solution to what you have done.
private void runThread() {
new Thread() {
public void run() {
while (continueAutoUpdate) {
try {
handler.postDelayed(new Runnable(){
public void run(){
Log.e("updating...", "");
updateLogFromDatabase();
}
}, milliseconds);
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
After trying various stuff, I finally found the solution: Anytime you have some long-run tasks to perform, you can assign a new Java thread to execute it, but when there's a need to update the UI from that thread, which can't be directly accessing any components of the UI, So in that case you only need to wrap the code with runOnUiThread() inside the other thread. ex/
private void startAutoUpdateLogData(final int milliseconds) {
final Handler handler = new Handler();
continueAutoUpdate = true;
new Thread() {
public void run() {
while (continueAutoUpdate) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("updating...", "");
updateLogFromDatabase();
}
});
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}

Enable and Disable Button using Timer in Android

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

Categories

Resources