Repeat a Method for specific times in android - android

Here is a code which I want to repeat 50 times after every 3 seconds. if I am calling this function with 'for' loop or 'while' loop it is not working properly Please give me suggestion.
for (int i = 0; i < 50; i++) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Generate_Ballon();
}
}, delay);
}

You can use CountDownTimer
See Example,
new CountDownTimer(150000, 3000)
{
public void onTick(long millisUntilFinished)
{
// You can do your for loop work here
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Here onTick() method will get executed on every 3 seconds.

You should use Handler's postDelayed function for this purpose. It will run your code with specified delay on the main UI thread, so you will be able to update UI controls.
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
#Override
protected void onCreate(Bundle bundle) {
...
mHandler = new Handler();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
updateStatus(); //this function can change value of mInterval.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}

private int count = 50;
private Handler handler = new Handler();
private Runnable r = new Runnable() {
public void run() {
Generate_Ballon();
if (--count > 0) {
handler.postDelayed(r, delay);
}
}
};
handler.postDelayed(r, delay);

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

Sequence of actions with delays android

I'm trying to get my app to display a sequence of images, 1 second after the other. Currently my java looks like this:
arrow1.setVisibility(View.VISIBLE);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
arrow1.setVisibility(View.INVISIBLE);
arrow2.setVisibility(View.VISIBLE);
}
}, 1000);
handler.postDelayed(new Runnable() {
public void run() {
arrow2.setVisibility(View.INVISIBLE);
arrow3.setVisibility(View.VISIBLE);
}
}, 1000);
I'm not getting any errors, but it's also not working as I intended. Arrow2 is not displaying at all, the app is going straight from arrow1 to arrow3 with a slight delay. Is my second handler.postDelayed(new Runnable() function being overriden? How should I best go about having a delay in this scenario?
You can try like this,
private static final int TotalLoopCount = 2;
private int count = 0;
private int mCurrentLoopCount = 0;
Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Your code
}
#Override
protected void onResume() {
super.onResume();
handler.postDelayed(runnable, 0);
}
#Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(runnable);
}
Runnable runnable = new Runnable() {
#Override
public void run() {
arrow1.setVisibility(View.INVISIBLE);
arrow2.setVisibility(View.INVISIBLE);
arrow3.setVisibility(View.INVISIBLE);
if(count == 0) {
arrow1.setVisibility(View.VISIBLE);
} else if(count == 1) {
arrow2.setVisibility(View.VISIBLE);
} else {
arrow3.setVisibility(View.VISIBLE);
}
count++;
if(count == 3) {
count = 0;
mCurrentLoopCount++;
}
if(mCurrentLoopCount < TotalLoopCount) {
handler.postDelayed(runnable, 3000);
}
}
};
You can also use CountDownTimer as below. See official doc for more details.
Set millisInFuture to countDownInterval*3 for 3 images and set countDownInterval for delay between images.
long countDownInterval = 1000; // 1sec interval
long millisInFuture = countDownInterval*10; // 10sec total time
new CountDownTimer(millisInFuture, countDownInterval) {
public void onTick(long millisUntilFinished) {
arrow1.setVisibility(millisUntilFinished < millisInFuture ? View.VISIBLE:View.INVISIBLE);
arrow2.setVisibility(millisUntilFinished > 0 ? View.VISIBLE:View.INVISIBLE);
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();

Call method every 30 second is not working

I want to update user location in every 30 second for which i am using volley request with Service.
The code in bellow:
public class CarLocationUpdateService extends Service {
Context context;
long delay = 1000; // delay for 1 sec.
long period = 10000; // repeat every 10 sec.
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
context = this;
Handler ha=new Handler();
ha.postDelayed(new Runnable() {
#Override
public void run() {
//call function
CarLocationUpdateVolleyClass carLocationUpdateVolleyClass=new CarLocationUpdateVolleyClass(context);
carLocationUpdateVolleyClass.carLocationRequest();
}
}, delay);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
use JobScheduler with firbaseJobDispatcher
https://developer.android.com/topic/performance/scheduling.html
You can use fused location service to get location updates.I have created a service to get location updates.This code will give you the location in onLocationChanged method.
Check out my answer here here
try this :
mHandler = new Handler();
Runnable r = new Runnable() {
#override
public void run() {
f();
mHandler.postDelayed(this, 30000);
}
};
mHandler.postDelayed(r, 30000);
you have to call the handler.postDelayed() method again inside the runnable because it´s executed only once, that´s a normal behaviour. Seperate the runnable from the handler like this:
Handler ha = new Handler();
private Runnable yourRunnable = new Runnable() {
#Override
public void run() {
CarLocationUpdateVolleyClass carLocationUpdateVolleyClass=new CarLocationUpdateVolleyClass(context);
carLocationUpdateVolleyClass.carLocationRequest();
ha.postDelayed(yourRunnable, 30000);
}
};
ha.post(yourRunnable);
by the way, your question tells us something about 30 seconds, but you just call it every 10 seconds.
Try this it works
public void doWork(){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// insert your data to db here
// close this activity
doWork();
Toast.makeText(MainActivity.this, "LOL", Toast.LENGTH_SHORT).show();
}
}, TIME_OUT);
}
And then simple call this method in onStartCommand()
doWork();
final Handler ha=new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
// ...
ha.postDelayed(this,30000);
}
};
ha.post(runnable);

Handler postDelayed - print every second something

I want to print the current second using a handler. I record a video for exactly 10 seconds and want to set the text of a TextView every second.
Recording 10 seconds works like that:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stopRecordingVideo();
}
}, 11000); // don't know why 11000 but it only works this way
After the 10 seconds the method stopRecordingVideo() gets executed. So how can I change the text every second of the TextView?
Working answer:
int t = 0;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
t++;
textView.setText(getString(R.string.formatted_time, t));
if(t<10) {
handler.postDelayed(this, 1000);
}
}
}, 1000);
Where formatted_time is something like that:
<string android:name="formatted_time">%d seconds</string>
To print text every second, you can use CountDownTimer. But if you want to achieve this with try below code:
void startTime(){
//Post handler after 1 second.
handler.postDelayed(runnable, 1000);
}
int totalDelay=0;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
totalDelay++;
if(totalDelay<=10){
//If total time is less then 10 second execute handler again after 1 second
handler.postDelayed(runnable, 1000);
}
textView.setText(totalDelay+" Second");
}
};
Try this, basically do the increment in a worker thread, but updating the text view is done by main's thread handler.
Thread worker= new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
// stop recording after 10 seconds
if (i == 9) {
handler.post(new Runnable() {
#Override
public void run() {
stopRecordingVideo();
}
});
}
else{
// set text for each second
handler.post(new Runnable() {
#Override
public void run() {
textView.setText(String.valueOf(i+1));
}
});
}
}//ends for()
worker.start()

Handler Timer is not working

I tried to create a small timer for my programm but this code below is not working and i cant find the issue
private int mInterval = 5000;
private Handler mHandler;
// at the bottom of my onCreate() methode:
mHandler = new Handler();
startRepeatingTask();
}
// on create ends here
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
myview.loadUrl(readFromFile());
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
I really would appreciate your help.
Something like this should work :)
//set variables
private int mInterval = 5000;
private Handler handler = new Handler();
//start runnable
runme.run();
private Runnable runme = new Runnable()
{
public void run()
{
//repeat after 5000 milliseconds
handler.postDelayed(this, mInterval );
}
};
//stop runnable
handler.removeCallbacks(runme);
try this..
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
// do something here...
handler.postDelayed(this, 5000); // for interval...
}
};
handler.postDelayed(runnable, 2000);
Try this
private int mInterval = 5000;
private Handler mHandler;
// at the bottom of my onCreate() methode:
mHandler = new Handler();
mHandler.postDelayed(mStatusChecker,mInterval);
}
// on create ends here
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
myview.loadUrl(readFromFile());
//if you want to repeat the thread infinitely,then add below code also. Else remove it
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
Use Handler.post() or Handler.postDelayed() to start a Handler.
private int mInterval = 5000;
private Handler mHandler;
// at the bottom of my onCreate() methode:
mHandler = new Handler();
mHandler.post(mStatusChecker);
//mHandler.postDelayed(mStatusChecker, mInterval);//or use this method
//startRepeatingTask();
// on create ends here
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
myview.loadUrl(readFromFile());
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
//void startRepeatingTask() {
// mStatusChecker.run();
//}
You may need to add android.permission.WRITE_EXTERNAL_STORAGE for read file in storage, and android.permission.INTERNET for load url.

Categories

Resources