0

In my app I am using a timer and timerTask to perform a certain task repeatedly. the timer is being used in a service. when I run the timer the TimerTask is not called after a certain delay my code is

`

final Timer timer = new Timer();
 public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i(TAG, "onStart");
        Thread thread = new Thread(this);
        thread.start();
try {
    Thread.sleep(GlobalClass.time);
} catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
@Override
    public void run() {
        Log.i(TAG, "onStart");


        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                Log.i(TAG, "i am in timertask");
                try {
                    setbackground();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }, GlobalClass.time, GlobalClass.time);
    }

` GlobalClass.time is a static long variable. please help me.

Sandroid
  • 328
  • 1
  • 10
  • 19

1 Answers1

1

use handler for calling a function repeatedly declear in ocCreate()

Handler handler = new Handler(); 
handler.postDelayed(checkFunction(),1000);

create function depends on your requirement

private Runnable checkFunction(){ 
      Timer t = new Timer();
      TimerTask tt = new TimerTask() {            
          public void run() { 
              handler.postDelayed(checkFunction(),1000);
              /// write coding for your requirement here
          }          
      };          
    return tt;
    }
RajaReddy PolamReddy
  • 22,428
  • 19
  • 115
  • 166
  • this is not working for me see my [question](http://stackoverflow.com/questions/14924295/service-of-an-app-not-running-when-phone-is-not-charged) ragarding to this – laplasz Feb 17 '13 at 18:31