2011-11-21 87 views
0

在我的应用程序中,我使用计时器和timerTask来重复执行某个任务。定时器正在服务中使用。当我运行定时器TimerTask的不叫延迟一定时间后我的代码是计时器无法正常工作android

`

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是一个静态长变量。请帮帮我。在ocCreate调用函数反复 declear

回答

1

使用处理器()

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

创建功能取决于您的要求

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; 
    } 
+0

这不是我看到我的[提问](HTTP工作: //stackoverflow.com/questions/14924295/service-of-an-app-not-running-when-phone-is-not-charged)ragarding to this – HiB