1

I have a thread with an infinite loop inside like the following

private Thread mThread = new Thread(){
    while(true){
        Looper.prepare();
        Toast.makeText(context, "test", Toast.LENGTH_LONG).show();
        Looper.loop();
        Thread.sleep(15000); 
    }
};

I had the code without Looper.prepare and loop but it didn't compile. After adding the Looper code my thread gets executed one time. Of course I want the code to execute every 15 seconds. Is there any way to solve this?

YoloQ
  • 45
  • 5

3 Answers3

1

Try doing it like this:

Declare a global variable for the handler like this:

Handler gHandler = new Handler();

Then declare a new thread:

 new Thread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                try {
                    Thread.sleep(15000); 
                    gHandler.post(new Runnable() {

                        @Override
                        public void run() {

                            // HERE WRITE YOUR CODE :)
                        }
                    });
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
    }).start();

Although there are other solutions for this, but this is how I do it. Hope it helps you.

JLONG
  • 805
  • 10
  • 20
  • This is interesting. Any resources for other solutions. It looks like a hack. – YoloQ Dec 04 '14 at 10:17
  • This is another one: http://stackoverflow.com/questions/21726055/android-loop-part-of-the-code-every-5-seconds – JLONG Dec 04 '14 at 11:00
0

Something like this worked for me

private Thread mThread = new Thread(){
    Looper.prepare();
    while(true){
        Toast.makeText(context, "test", Toast.LENGTH_LONG).show();
        Thread.sleep(15000); 
    }
};

For some reason it is not necesary to call Looper.loop()

Kanabos
  • 420
  • 4
  • 11
0

Thread.sleep(15000); makes the execution bit slower so I will recommend you to use handler.postDelayed(runnable, 15000);, it will optimize your code

Handler handler = new Handler();
handler.postDelayed(new Runnable() {        
    @Override
    public void run() {
        while(true){
            Looper.prepare();
            Toast.makeText(context, "test", Toast.LENGTH_LONG).show();
            Looper.loop(); 
        }
    }
}, 15000);        
Apurva
  • 7,871
  • 7
  • 40
  • 59