2012-12-06 45 views
0

我有活動A,B,C,D ...我在活動A中創建了一個倒計時器....我想在活動B,C,D中調用它的方法....我該如何...我試圖使計時器變量靜態,但它有一些問題,並不能正常工作......並且它不是一個很好的編程習慣。所以有沒有其他方式來做到這一點?如何使CountDownTimer與多個活動共同使用?

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

你爲什麼不創建mycount的作爲單獨的類? –

+0

在延長服務的活動中寫入計時器的代碼..在活動A中啓動服務.. – Deepzz

+0

我無法將其創建爲新類,因爲...我想在onfinish方法中啓動一項新活動.... – Audi

回答

相關問題