I have Activities A,B,C,D… I create a countdowntimer in activity A….I want to call its methods in activities B,C,D …. how do i that…I tried making the timer variable static but it has some problems and doesn’t function properly…Also its not a good programming practice..So is there any other way to do this??
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();
}
}
probably the best approach for that will be creating a Singleton class with your Timer.
If you don’t know what the Singleton is you can find it in below sources:
http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html
http://en.wikipedia.org/wiki/Singleton_pattern