0

我有活动 A、B、C、D ......我在活动 A 中创建了一个倒数计时器......我想在活动 B、C、D 中调用它的方法......我该怎么做......我试过了使计时器变量静态,但它有一些问题并且不能正常工作......这也不是一个好的编程习惯......那么还有其他方法可以做到这一点吗?

public class CountTime extends Activity {

    static MyCount count;
    Button clickBtn;
    TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.customanim); // 5000 is
                                                                // the
                                                                // starting
                                                                // number
                                                                // (in
                                                                // milliseconds)
        // 1000 is the number to count down each time (in milliseconds)
        count = new MyCount(5000, 1000);
        count.start();
        tv = (TextView) findViewById(com.example.sample.R.id.textView1);

        clickBtn = (Button) findViewById(R.id.button1);
        clickBtn.setText("Click me");
        clickBtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Intent my = new Intent(getApplicationContext(),
                        MainActivity.class);
            //my.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(my);
            }
        });
    }

    @Override
    public void onUserInteraction() {
        // TODO Auto-generated method stub
        super.onUserInteraction();
        //count.start();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        count.cancel();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        count.start();
    }

    // countdowntimer is an abstract class, so extend it and fill in methods
    public class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            tv.setText("done!");
            Toast.makeText(getApplicationContext(), "Finsihed", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tv.setText("Left: " + millisUntilFinished / 1000);
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }
}
4

1 回答 1

0

可能最好的方法是用你的 Timer 创建一个 Singleton 类。

如果您不知道 Singleton 是什么,您可以在以下来源中找到它: http: //www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html http://en.wikipedia .org/wiki/Singleton_pattern

于 2012-12-06T10:30:42.900 回答