2016-05-16 57 views
-1

我想每60秒鐘定期記錄一條消息。我想我應該使用postdelayed方法處理程序。然而,在其他問題中提出的方法對我無效。使用處理程序postdelay定期運行代碼

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    dbHandler=new DatabaseHandler(this); 
    data = dbHandler.fetchAllItemsIn(5); 
    run= new Runnable() { 
     @Override 
     public void run() { 
      String items=""; 
      for(int i=0;i<data.size();i++){ 
       items+=data.get(i).getItemName()+"\n"; 
      } 
      Log.d("items:",items); 
     } 
    }; 

} 
public void LogDatabase(View view){ 
    Handler hand=new Handler(); 

    hand.postDelayed(run,60); 
} 
+0

您是否試過'TimerTask'?檢查一下:http://developer.android.com/reference/java/util/TimerTask.html –

回答

1

,因爲你運行你Runnable一次它不爲你工作。

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    dbHandler=new DatabaseHandler(this); 
    data = dbHandler.fetchAllItemsIn(5); 
    hand = new Handler(); 

    run= new Runnable() { 
     @Override 
     public void run() { 
      String items=""; 
      for(int i=0;i<data.size();i++){ 
       items+=data.get(i).getItemName()+"\n"; 
      } 
      Log.d("items:",items); 
      hand.postDelayed(run,60); 
     } 
    }; 

} 
public void LogDatabase(View view){ 
    hand.postDelayed(run,60); 
} 
0

如果你不只想執行一次 - 你需要調用postDelayed你可運行結束時再次