开发者

Simple Timer Example but it wont work fine

开发者 https://www.devze.com 2023-02-09 14:38 出处:网络
I made a simple timer example but it work as it have to be. Here is the code public class TimerExample extends Activity {

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();
        }
    });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号