2011-02-07 48 views
1

我做了一個簡單的計時器的例子,但它的工作,因爲它必須是。 下面是代碼簡單的計時器的例子,但它不會工作正常

public class TimerExample extends Activity { 
private Timer timer; 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    timer=new Timer(); 
    timer.schedule(new TimerTask(){ 

     @Override 
     public void run() { 
      // TODO Auto-generated method stub 
      TimerMethod(); 

     } 

    }, 0, 10000); 

} 

public void TimerMethod() 
{ 
    Toast.makeText(getApplicationContext(), "Hi this is piyush", Toast.LENGTH_LONG).show(); 
} 
} 

舉杯有10秒後,將出現,但它不會發生。請建議正確的方法。

回答

2

定時器的run方法沒有在UI線程中運行,因此您可以直接對UI執行任何操作。所以,你可以用runOnUiThread方法包裹UI部分

public void TimerMethod() { 
    runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      Toast.makeText(getApplicationContext(), "Hi this is piyush", Toast.LENGTH_LONG).show(); 
     } 
    }); 
} 
+0

由於它工作正常知道:) – PiyushMishra 2011-02-07 12:45:17