Android - Loop Part of the Code Every 5 Seconds

Android - loop part of the code every 5 seconds

Using a CountDownTimer as in one of the other answers is one way to do it. Another would be to use a Handler and the postDelayed method:

private boolean started = false;
private Handler handler = new Handler();

private Runnable runnable = new Runnable() {
@Override
public void run() {
final Random random = new Random();
int i = random.nextInt(2 - 0 + 1) + 0;
random_note.setImageResource(image[i]);
if(started) {
start();
}
}
};

public void stop() {
started = false;
handler.removeCallbacks(runnable);
}

public void start() {
started = true;
handler.postDelayed(runnable, 2000);
}

Here's an example using a Timer and a TimerTask:

private Timer timer;
private TimerTask timerTask = new TimerTask() {

@Override
public void run() {
final Random random = new Random();
int i = random.nextInt(2 - 0 + 1) + 0;
random_note.setImageResource(image[i]);
}
};

public void start() {
if(timer != null) {
return;
}
timer = new Timer();
timer.scheduleAtFixedRate(timerTask, 0, 2000);
}

public void stop() {
timer.cancel();
timer = null;
}

Execute function after 5 seconds in Android

You can use the Handler to add some delay.Call the method displayData() as below so that it will be executed after 5 seconds.

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
displayData();
}
}, 5000);

Note : Do not use the threads like Thread.sleep(5000); because it will block your UI and and makes it irresponsive.

How to run a method every X seconds

The solution you will use really depends on how long you need to wait between each execution of your function.

If you are waiting for longer than 10 minutes, I would suggest using AlarmManager.

// Some time when you want to run
Date when = new Date(System.currentTimeMillis());

try {
Intent someIntent = new Intent(someContext, MyReceiver.class); // intent to be launched

// Note: this could be getActivity if you want to launch an activity
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0, // id (optional)
someIntent, // intent to launch
PendingIntent.FLAG_CANCEL_CURRENT // PendingIntent flag
);

AlarmManager alarms = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE
);

alarms.setRepeating(
AlarmManager.RTC_WAKEUP,
when.getTime(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent
);
} catch(Exception e) {
e.printStackTrace();
}

Once you have broadcasted the above Intent, you can receive your Intent by implementing a BroadcastReceiver. Note that this will need to be registered either in your application manifest or via the context.registerReceiver(receiver, intentFilter); method. For more information on BroadcastReceiver's please refer to the official documentation..

public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
System.out.println("MyReceiver: here!") // Do your work here
}
}

If you are waiting for shorter than 10 minutes then I would suggest using a Handler.

final Handler handler = new Handler();
final int delay = 1000; // 1000 milliseconds == 1 second

handler.postDelayed(new Runnable() {
public void run() {
System.out.println("myHandler: here!"); // Do your work here
handler.postDelayed(this, delay);
}
}, delay);

Android loop service every 5 seconds and boot on startup

Use Handler.postDelayed(Runnable r, long delayMillis). You don't need timers or the alarm manager to do what you want. Stay simple.

Android Studio - Need help looping code every second

I think you can use CountDownTimer, something like this:

// Do something each second in a time frame of 60 seconds.
CountDownTimer countDownTimer = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
// For every second, do something.
doSomething();
}

public void onFinish() {
countDownTimer.start(); // restart again.
}
}.start();

Run loop every second java

You code is failed because you perform sleep in background thread but display data must be performed in UI thread.

You have to run displayData from runOnUiThread(Runnable) or define handler and send message to it.

for example:

(new Thread(new Runnable()
{

@Override
public void run()
{
while (!Thread.interrupted())
try
{
Thread.sleep(1000);
runOnUiThread(new Runnable() // start actions in UI thread
{

@Override
public void run()
{
displayData(); // this action have to be in UI thread
}
});
}
catch (InterruptedException e)
{
// ooops
}
}
})).start(); // the while thread will start in BG thread


Related Topics



Leave a reply



Submit