Simple Timer Example but it wont work fine
I made a simple timer example but it work as it have to be. Here is the code
public class TimerExample extends Activity {
private Timer timer;
/** Called when the activity is fi开发者_如何学JAVArst 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();
}
}
a toast have to be appeared after 10 sec but it wont happen. please suggest the correct way.
The run
method of the timers isn't ran in the UI Thread, thus you can do nothing with your UI directly. So, you can wrap the UI part with the runOnUiThread
method:
public void TimerMethod() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Hi this is piyush", Toast.LENGTH_LONG).show();
}
});
}
精彩评论