我有活动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();
}
}
答案 0 :(得分:0)
可能最好的方法是使用你的Timer创建一个Singleton类。
如果你不知道Singleton是什么,你可以在以下来源找到它: http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html http://en.wikipedia.org/wiki/Singleton_pattern