Facing problems dealing With Google Maps Android - 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.

Related

Android Loop Method Every X Seconds

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.

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

Android timer fires only once

I have this code where I want to try to send an e-mail report every hour (in the example to every second). If there is no coverage, try again within an hour etc. Somehow I managed to break the timer in sendUnsendedReports(): it fires only once. If I remove the call to sendUnsendedReports() than the timer is working perfectly. Even with the try-catch block around it, the timer only fires once. Please advice.
private void createAndScheduleSendReport() {
delayedSendTimer = new Timer();
delayedSendTimer.schedule(new TimerTask() {
#Override
public void run() {
Log.w("UrenRegistratie", "Try to send e-mail...");
try{
sendUnsendedReports();
}
catch(Exception e){
// added try catch block to be sure of uninterupted execution
}
Log.w("UrenRegistratie", "Mail scheduler goes to sleep.");
}
}, 0, 1000);
}
It seems that sometimes timer doesn't works well as it should be. The alternative of this is use of Handler instead TimerTask.
You can use it like :
private Handler handler = new Handler();
handler.postDelayed(runnable, 1000);
private Runnable runnable = new Runnable() {
#Override
public void run() {
try{
sendUnsendedReports();
}
catch(Exception e){
// added try catch block to be sure of uninterupted execution
}
/* and here comes the "trick" */
handler.postDelayed(this, 1000);
}
};
Check out this link for more detail. :)
schedule() can be called in various ways, depending on if you want the task to execute once, or periodically.
To execute the task only once:
timer.schedule(new TimerTask() {
#Override
public void run() {
}
}, 3000);
To execute the task every second after 3 s.
timer.schedule(new TimerTask() {
#Override
public void run() {
}
}, 3000, 1000);
More example usages can be found in the method headers
public void schedule(TimerTask task, Date when) {
// ...
}
public void schedule(TimerTask task, long delay) {
// ...
}
public void schedule(TimerTask task, long delay, long period) {
// ...
}
public void schedule(TimerTask task, Date when, long period) {
// ...
}
It is clearly that you hit the exception and get out of the Timer run method, thus interrupting the timer restart.

Creating a service with repetitive method

I am trying to create a service which does something every 5 seconds.
The problem is the moment I put the while(true) it gives me an error.
I imagine this is just not allowed. If so, what is a better way to implement a repetitive method?
public class repService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
while(true){
Thread timer = new Thread(){
public void run(){
try {
sleep(5000);
// do something
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// do something
}
}
};
timer.start();
}
}
You cannot put statements outside of a method to run. Put the while loop inside onCreate or onStartCommand methods of your service. These methods are guaranteed to called once your service is launched.
And for implementing a repetitive task, use HandlerThread, Looper, Handler and handler's postDelayed method to make good use of it.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// do something
}
}, 0, 5000);
which every 5 seconds does something
You can use Timer().schedule to repeat task every 5 seconds.
new Timer().schedule(new TimerTask() {
#Override
public void run() {
//Do your task here
}
}, System.currentTimeMillis(), 5000);
If you need to modify or play on UI part then make sure to write than code in runOnUiThread

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