AndroidでTimerを実装してみる

俺のTimerTaskクラス

public class MyTimer extends TimerTask {
    public Context context;
    public Handler handler = new Handler();

    public MyTimer(Context context) {
        this.context = context;
    }

    @Override
    public void run() {
        handler.post(new Runnable() {
            public void run() {
                try {
                    Toast.makeText(context, "hello", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

俺の実行方法

public class MyActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // これ
        new Timer(true).schedule(new MyTimer(), 5000);
    }
}