Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'd use MarvinLabs approach, but implement the while cycle in a different way:</p> <pre><code>public class Locate extends MapActivity { // ... private MyLooper mLooper; public void onCreate(Bundle savedInstanceState) { //... mLooper = new MyLooper(); mLooper.start(); } public void onDestroy() { // Don't forget to stop the thread here and release the reference // held by the activity (else you will leak memory) mLooper = null; } private class MyLooper extends Thread { public void run() { while (true) { // Your code here //After executing your code, sleep for 1000ms try { Thread.sleep(1000); } catch (InterruptedException ex) { //Treat the exception } } } } } </code></pre> <p>Also, instead of while(true) you can have a variable that would serve has a flag to inform the while cycle when to stop. That would make things easier when it's time to stop the thread.</p> <p>That would be something along these lines: <strong>Modified to use Handler</strong></p> <pre><code>public class Locate extends MapActivity { // ... private MyLooper mLooper; public void onCreate(Bundle savedInstanceState) { //... mLooper = new MyLooper(new Handler()); mLooper.start(); //When it's time to stop mLooper.setKeepRunningFalse(); } public void onDestroy() { // Don't forget to stop the thread here and release the reference // held by the activity (else you will leak memory) mLooper = null; } private class MyLooper extends Thread { //Your flag private boolean keepRunning; private Handler locateHandler; public MyLooper(Handler locateHandler) { this.locateHandler = locateHandler; } public void run() { while (keepRunning) { //When you want to execute some code that accesses Locate objects do this locateHandler.post(new Runnable() { @Override public void run() { //Your code here //This code will be executed by the thread that owns the objects, thus not throwing an exception. } }); //After executing your code, sleep for 1000ms try { Thread.sleep(1000); } catch (InterruptedException ex) { //Treat the exception } } } //Method to change the flag to false public void setKeepRunningFalse() { this.keepRunning = false; } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload