处理程序计时器不起作用

时间:2014-08-26 10:52:57

标签: android timer

我尝试为我的程序创建一个小计时器,但下面的代码不起作用,我无法找到问题

private int mInterval = 5000; 
private Handler mHandler;

// at the bottom of my onCreate() methode:

    mHandler = new Handler();
    startRepeatingTask();
}
// on create ends here

 Runnable mStatusChecker = new Runnable() {
     @Override 
     public void run() {
         myview.loadUrl(readFromFile());
         mHandler.postDelayed(mStatusChecker, mInterval);
     }
 };

 void startRepeatingTask() {
     mStatusChecker.run(); 
 }

我真的很感激你的帮助。

4 个答案:

答案 0 :(得分:0)

使用Handler.post()Handler.postDelayed()启动处理程序。

private int mInterval = 5000; 
private Handler mHandler;

// at the bottom of my onCreate() methode:

mHandler = new Handler();
mHandler.post(mStatusChecker);
//mHandler.postDelayed(mStatusChecker, mInterval);//or use this method
//startRepeatingTask();
// on create ends here

Runnable mStatusChecker = new Runnable() {
    @Override 
    public void run() {
        myview.loadUrl(readFromFile());
      mHandler.postDelayed(mStatusChecker, mInterval);
    }
};

//void startRepeatingTask() {
//    mStatusChecker.run(); 
//}

您可能需要为存储中的读取文件添加android.permission.WRITE_EXTERNAL_STORAGE,并为加载网址添加android.permission.INTERNET

答案 1 :(得分:0)

这样的事情应该有效:)

//set variables
private int mInterval = 5000; 
private Handler handler = new Handler();
//start runnable
runme.run();

private Runnable runme = new Runnable() 
{
    public void run() 
    {
         //repeat after 5000 milliseconds
         handler.postDelayed(this, mInterval );
    }
};

//stop runnable
handler.removeCallbacks(runme);

答案 2 :(得分:0)

试试这个..

  final Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            public void run() {
                // do something here... 
                handler.postDelayed(this, 5000); // for interval...
            }
        };
        handler.postDelayed(runnable, 2000); 

答案 3 :(得分:0)

试试这个

private int mInterval = 5000; 
private Handler mHandler;

// at the bottom of my onCreate() methode:

mHandler = new Handler();
mHandler.postDelayed(mStatusChecker,mInterval);
}
// on create ends here

 Runnable mStatusChecker = new Runnable() {
     @Override 
 public void run() {
     myview.loadUrl(readFromFile());
      //if you want to repeat the thread infinitely,then add below code also. Else remove it
     mHandler.postDelayed(mStatusChecker, mInterval);
 }
 };