Android Loop Method Every X Seconds - android

I would like to call the same method, say every 5 seconds, I am trying to create some sort of database listener that will listen for database changes. The following code does not work, I am expecting the log to print "RUNNING" every 5 seconds for testing but this only gets called once when I call the method for the first time.
private void DBListern() {
// TODO Auto-generated method stub
//accessWebService();
System.out.println("RUNNING");
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
DBListern();
}
}, 5000);
}

Take a look at java.util.concurrent.ScheduledExecutorService with its scheduleAtFixedRate you should be able to do exactly what you want!

Try to use java.util.concurrent.ScheduledExecutorService.
Example:
private final ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
private void DBListern(int delayInSeconds) {
//accessWebService();
System.out.println("RUNNING");
exec.schedule(new Runnable() {
#Override
public void run() {
DBListern();
}
}, delayInSeconds, TimeUnit.SECONDS);
}

Ok, for some reason the function cannot call itself so I created a different function called loop() which calls DBListern every 5 seconds:
private void DBListern() {
// TODO Auto-generated method stub
//accessWebService();
System.out.println("RUNNING");
}
private void loop() {
// TODO Auto-generated method stub
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
DBListern();
handler.postDelayed(this, 5000);
}
}, 5000);
}
So loop() is called first and then it calls DBListern every 5 seconds.

Related

Wait funtion in a while cycle?

Is there any way to do a wait() function, in my case, in Android Studio?
function example ()
{
while ()
{
//do something
//wait (x seconds) then go back
}
}
You may achieve this way:
//in your method, use the Timer Schedule function:
new Timer().schedule(
new TimerTask() {
#Override
public void run() {
//TODO: do something here of your interest.
}
},
2000
);
Here I have kept the delay for 2 seconds (2000 milliseconds). You may change that according to your need.
int interval = 3000;//milliseconds interval for delay
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
private void finish() {
// TODO Auto-generated method stub
}
}, interval);

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

Facing problems dealing With Google Maps Android

i am using below code to run my getLatLngWrkr(); function after 3 seconds but when timer starts and getLatLngWrkr();gets call the code which places Marker does not work.But when i run the function getLatLngWrkr() without Timer it works properly.
here is the some line to place marker to map and it does not work if i call the function through Timer
marker=googleMap.addMarker(new MarkerOptions().position(newLatLng(Double.parseDouble(lati), Double.parseDouble(longi))).title( lati+longi));
Here is Timer Function
Timer time = new Timer();
time.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
Log.e("test","tiemr");
getLatLngWrkr();
}
},0, 3000);
When you use a TimerTask the task is performed on a separate thread and not the ui thread. You need to call getLatLngWrkr using runOnUiThread:
Timer time = new Timer();
time.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
Log.e("test","tiemr");
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
getLatLngWrkr();
}
});
}
},0, 3000);
Replace MainActviity with the name of your activity.

How to implement timer in an android game

In my android game, there is an arcade mode, which runs for 60 seconds. UI has to be updated every second. Is it advisable to use CountDownTimer to implement this because as far af i know this class does not run on separate thread ? What are other ways or best way to do this without affecting user experience ?
EXACT CODE WHICH SOLVED MY PROBLEM
new Thread(new Runnable() {
// this creates timer in another thread
#Override
public void run() {
// TODO Auto-generated method stub
long starttime = System.currentTimeMillis();
time=60;
while(time>0)
{
SystemClock.sleep(1000);
long currenttime = System.currentTimeMillis();
time= (int) (60-((currenttime-starttime)/1000));
// this updates the UI
timerhandler.post(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
tv0.setText(time + " s");
}
});
}
}
}).start();
Use
new Handler().postDelayed(new Runnable(){
#Override
public void run(){
// Your code
}
}, 60*1000));
You can make use of Timer and TimerTask Class. Example (It gives the delay of 6 seconds. Its better to use seperate thread for this)
Timer timer = new Timer("My Timer");
TimerTask task = new TimerTask() {
#Override
public void run() {
System.out.println("Timer task completed .......");
}
};
System.out.println("Timer task started.......");
timer.schedule(task, 0, 6000);

display data after every 10 seconds in Android

I have to display some data after every 10 seconds. Can anyone tell me how to do that?
There is an another way also that you can use to update the UI on specific time interval. Above two options are correct but depends on the situation you can use alternate ways to update the UI on specific time interval.
First declare one global varialbe for Handler to update the UI control from Thread, like below
Handler mHandler = new Handler();
Now create one Thread and use while loop to periodically perform the task using the sleep method of the thread.
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// Write your code here to update the UI.
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
Probably the simplest thing to do is this:
while(needToDisplayData)
{
displayData(); // display the data
Thread.sleep(10000); // sleep for 10 seconds
}
Alternately you can use a Timer:
int delay = 1000; // delay for 1 sec.
int period = 10000; // repeat every 10 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
displayData(); // display the data
}
}, delay, period);
Andrahu was on the right track with defining a handler. If you have a handler that calls your update functions you can simply delay the message sent to the handler for 10 seconds.
In this way you don't need to start your own thread or something like that that will lead to strange errors, debugging and maintenance problems.
Just call:
Handler myHandler = new MyUpdateHandler(GUI to refresh); <- You need to define a own handler that simply calls a update function on your gui.
myHandler.sendMessageDelayed(message, 10000);
Now your handleMessage function will be called after 10 seconds. You could just send another message in your update function causing the whole cycle to run over and over
There is Also Another way by Using Handler
final int intervalTime = 10000; // 10 sec
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Display Data here
}
}, intervalTime);
There is a Simple way to display some data after every 10 seconds.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
ActionStartsHere();
}
public void ActionStartsHere() {
againStartGPSAndSendFile();
}
public void againStartGPSAndSendFile() {
new CountDownTimer(11000,10000) {
#Override
public void onTick(long millisUntilFinished) {
// Display Data by Every Ten Second
}
#Override
public void onFinish() {
ActionStartsHere();
}
}.start();
}
Every 10 seconds automatically refreshed your app screen or activity refreshed
create inside onCreate() method i tried this code will work for me
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
//CALL ANY METHOD OR ANY URL OR FUNCTION or any view
}
});
}
} catch (InterruptedException e) {
}
}
};t.start();

Categories

Resources