2012-08-07 163 views
0

我有一個每秒更新一次textview的runnable計時器,當活動處於onStop(或稱爲後臺)計時器繼續運行時。我遇到的問題是,當我重新啓動活動時,它會再次啓動相同的計時器,因此數字會以其應有的速度提高兩倍。我把它編碼,這樣它會在重新啓動它們之前殺死兩個計時器,但我相信當活動再次啓動時,計時器不會被殺死。下面是我的代碼示例:計時器在活動關閉並重新啓動後不會停止

t.cancel(); 
    cd.cancel(); 
    t = new Timer(); 
    t.schedule(new TimerTask() { 

     @Override 
     public void run() { 
      runOnUiThread(new Runnable() { 

       public void run() { 

那只是一小部分,但它應該終止計時器(t.cancel();),然後開始一個新的,當活動停止這只是發生和然後重新啓動。請幫助這個問題讓我絕對瘋了。

============================================== ===========

對於願意讀很多的勇敢的靈魂,這裏要說的是我有問題我的整個活動:

public class PayTracker extends Activity { 
    private static double Reserve; 
    private static int Reserve1; 
    public static double money; 
    public static double counter; 
    private static int go; 
    private static int countdown; 
    public static int convert; 
    public static double HW; 
    public static double OTW; 
    public static double HPD; 
    public static double DPPS; 
    public Timer t = new Timer(); 
    public Timer cd = new Timer(); 
    public static String mcountdown = "Time till overtime"; 
    public static String mmoney = "total cash"; 
    public static String mcounter = "ticks"; 
    public static String mReserve = "building total"; 
    public static String mReserve1 = "building total 2"; 
    public static String mHW; 
    public static String mOTW; 
    public static String mHPD; 
    public static String mDPPS; 
    public static String mgo; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_pay_tracker); 
     getActionBar().setDisplayHomeAsUpEnabled(true); 
    // Receive messages from options page 
     double pHW, pOTW, pHPD; 
     Intent intent = getIntent(); 
     pHW = intent.getDoubleExtra(Options.MESSAGE_HW, 0); 
     pOTW = intent.getDoubleExtra(Options.MESSAGE_OTW, 0); 
     pHPD = intent.getDoubleExtra(Options.MESSAGE_HPD, 0); 
     if(pHW != 0){ 
      HW = pHW; 
      OTW = pOTW; 
      HPD = pHPD; 
     } 
    // Color buttons 
     Button buttonc = (Button) findViewById(R.id.clockin); 
     buttonc.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY); 
     Button buttond = (Button) findViewById(R.id.clockout); 
     buttond.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY); 

//  go = 0; 
     // Calculate pay per second 
     final double PPS = (HW/3600); 
     DPPS = (PPS/50); 
     final double OTPPS = (OTW/3600); 
     final double DOTPPS = (OTPPS/50); 
     final double HPDPS = (HPD*3600); 
     final double DHPDPS = (HPDPS*50); 
     // Display 

     final TextView t1 = (TextView) findViewById(R.id.yourpay); 
     t1.setTextColor(Color.parseColor("#008000")); 
     final TextView t2 = (TextView) this.findViewById(R.id.payper); 
     final String result2 = String.format("%.8f", OTPPS); 
     final String result = String.format("%.8f", PPS); 

     // if(go != 1){ 
     // go = 1; 
     // if(go == 1){ 
     t.cancel(); 
     cd.cancel(); 
     // go = 0; 
     // } 
     // if(go == 0){ 
     // go = 1; 
     t = new Timer(); 
     t.schedule(new TimerTask() { 

      @Override 
      public void run() { 
       runOnUiThread(new Runnable() { 

        public void run() { 
         if(DHPDPS==0){ 
          money = (DPPS+Reserve); 
          Reserve = (money); 
          String end = String.format("%1f", money); 
          t1.setText("$" + end); 
         }else if(counter > DHPDPS && DOTPPS != 0 && DHPDPS != 0){ 
          money = (DOTPPS+Reserve); 
          Reserve = (money); 
          String end = String.format("%1f", money); 
          t1.setText("$" + end); 
         } else{ 

          money = (DPPS+Reserve); 
          Reserve = (money); 
          String end = String.format("%1f", money); 
          t1.setText("$" + end); 
         } 
         counter++; 
         //if(counter == 3000) 
         // t.cancel(); 

         // Display pay per second 
         if(counter <= DHPDPS || DHPDPS == 0){ 
         t2.setText("Your pay per second is: $"+result); 
         }else{ 
          t2.setText("Your pay per second is: $"+result2); 
         } 
        } 
       }); 
      } 
     }, 20, 20); 

    // Make countdown to overtime display 

     final Intent intent1 = new Intent(this, PayTracker.class); 
    // Create the notification 
     final Notification notification = new Notification(R.drawable.ic_launcher, "Click here to check your pay!", System.currentTimeMillis()); 
     // Create an Intent for the notification to launch 
     // Create a PendingIntent for the associated Intent 
     final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent1, 0); 
     cd = new Timer(); 
     final TextView count = (TextView) findViewById(R.id.countdown); 
     convert = (int)HPDPS; 
     cd.schedule(new TimerTask() { 
      @Override 
      public void run() { 
       runOnUiThread(new Runnable() { 
        public void run(){ 
         countdown = (convert - Reserve1); 
         int hours = (countdown/3600); 
         if(OTPPS != 0 && HPDPS != 0){ 
           count.setText("Seconds Remaining to Overtime: " + countdown + "\nAbout " + hours + " Hours"); 
           Reserve1++; 
          } 

         // Set the notification's details 
         final String end = String.format("%.6f", money); 
         notification.setLatestEventInfo(getApplicationContext(), "Your Current Pay:", "$"+end, pendingIntent); 
         // Submit the notification to the system 
         ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification); 
        } 
       }); 
      } 

     }, 1000, 1000); 
     // } 
     // } 


     final Button b = (Button) findViewById(R.id.clockout); 
     b.setOnClickListener(new OnClickListener() { 
      public void onClick(View v) { 
       if(go == 1) 
        go = 0; 
       if (t != null){ 
        t.cancel(); 
        cd.cancel(); 
       } 
       } 
     }); 

    } 

    public void onRestoreInstanceState(Bundle savedInstanceState) { 
     // Always call the superclass so it can restore the view hierarchy 
     super.onRestoreInstanceState(savedInstanceState); 
      // Restore value of members from saved state 
      countdown = savedInstanceState.getInt(mcountdown); 
      Reserve = savedInstanceState.getInt(mReserve); 
      money = savedInstanceState.getInt(mmoney); 
      counter = savedInstanceState.getInt(mcounter); 
      Reserve1 = savedInstanceState.getInt(mReserve1); 
      HW = savedInstanceState.getInt(mHW); 
      OTW = savedInstanceState.getInt(mOTW); 
      HPD = savedInstanceState.getInt(mHPD); 
      DPPS = savedInstanceState.getInt(mDPPS); 
      go = savedInstanceState.getInt(mgo); 
    } 

    @Override 
    public void onStart(){ 
     super.onStart(); 


    } 



    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_pay_tracker, menu); 
     return true; 
    } 


    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
      case android.R.id.home: 
       NavUtils.navigateUpFromSameTask(this); 
       return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    public void sendMessage(View view) { 
     // Calculate pay per second 
     final double PPS = (HW/3600); 
     DPPS = (PPS/50); 
     final double OTPPS = (OTW/3600); 
     final double DOTPPS = (OTPPS/50); 
     final double HPDPS = (HPD*3600); 
     final double DHPDPS = (HPDPS*50); 
     // Display 

     final TextView t1 = (TextView) findViewById(R.id.yourpay); 
     t1.setTextColor(Color.parseColor("#008000")); 
     final TextView t2 = (TextView) this.findViewById(R.id.payper); 
     final String result2 = String.format("%.8f", OTPPS); 
     final String result = String.format("%.8f", PPS); 

     //if(go != 1){ 
     // go = 1; 
      t.cancel(); 
      cd.cancel(); 
     t = new Timer(); 
     t.schedule(new TimerTask() { 

      @Override 
      public void run() { 
       runOnUiThread(new Runnable() { 

        public void run() { 
         if(DHPDPS==0){ 
          money = (DPPS+Reserve); 
          Reserve = (money); 
          String end = String.format("%1f", money); 
          t1.setText("$" + end); 
         }else if(counter > DHPDPS && DOTPPS != 0 && DHPDPS != 0){ 
          money = (DOTPPS+Reserve); 
          Reserve = (money); 
          String end = String.format("%1f", money); 
          t1.setText("$" + end); 
         } else{ 

          money = (DPPS+Reserve); 
          Reserve = (money); 
          String end = String.format("%1f", money); 
          t1.setText("$" + end); 
         } 
         counter++; 
         if(counter == 3000) 
          t.cancel(); 

         // Display pay per second 
         if(counter <= DHPDPS || DHPDPS == 0){ 
         t2.setText("Your pay per second is: $"+result); 
         }else{ 
          t2.setText("Your pay per second is: $"+result2); 
         } 
        } 
       }); 
      } 
     }, 20, 20); 

    // Make countdown to overtime display 

     final Intent intent1 = new Intent(this, PayTracker.class); 
    // Create the notification 
     final Notification notification = new Notification(R.drawable.ic_launcher, "Click here to check your pay!", System.currentTimeMillis()); 
     // Create an Intent for the notification to launch 
     // Create a PendingIntent for the associated Intent 
     final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent1, 0); 
     cd = new Timer(); 
     final TextView count = (TextView) findViewById(R.id.countdown); 
     convert = (int)HPDPS; 
     cd.schedule(new TimerTask() { 
      @Override 
      public void run() { 
       runOnUiThread(new Runnable() { 
        public void run(){ 
         countdown = (convert - Reserve1); 
         int hours = (countdown/3600); 
         if(OTPPS != 0 && HPDPS != 0){ 
           count.setText("Seconds Remaining to Overtime: " + countdown + "\nAbout " + hours + " Hours"); 
           Reserve1++; 
          } 

         // Set the notification's details 
         final String end = String.format("%.6f", money); 
         notification.setLatestEventInfo(getApplicationContext(), "Your Current Pay:", "$"+end, pendingIntent); 
         // Submit the notification to the system 
         ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification); 
        } 
       }); 
      } 

     }, 1000, 1000); 

     //} 
    } 



    @Override 
    public void onSaveInstanceState(Bundle savedInstanceState) { 
     // Save the user's current game state 
     savedInstanceState.putInt(mcountdown, countdown); 
     savedInstanceState.putDouble(mReserve, Reserve); 
     savedInstanceState.putDouble(mmoney, money); 
     savedInstanceState.putDouble(mcounter, counter); 
     savedInstanceState.putDouble(mReserve1, Reserve1); 
     savedInstanceState.putDouble(mHW, HW); 
     savedInstanceState.putDouble(mOTW, OTW); 
     savedInstanceState.putDouble(mHPD, HPD); 
     savedInstanceState.putDouble(mDPPS, DPPS); 
     savedInstanceState.putInt(mgo, go); 

     // Always call the superclass so it can save the view hierarchy state 
     super.onSaveInstanceState(savedInstanceState); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 

     if(t != null) 
      t.cancel(); 
     if(cd != null) 
      cd.cancel(); 
    } 

} 
+0

運行中是否存在while循環? – 2012-08-07 20:23:34

+0

@Andi Jay no theres不是 – Hockeyman271 2012-08-07 20:24:49

+0

你能不能在'onStop()'中調用'Timer.cancel()'? – 2012-08-07 20:25:04

回答

1

這是獲得一種方式在那附近。

static Timer mTimer = null; 

onCreate() { 
    if (mTimer == null) 
     mTimer = new Timer(); 
    } else { 
     // You shouldn't have to do nothing because your timer should be running 
    } 
} 

請注意,這裏一般有幾個問題。靜態基本上只是說創建該對象的一個​​實例。作爲副作用,它也試圖回收相同的內存地址。無論哪種方式,一旦你的應用程序在後臺,它可以在任何時候由系統清理,所以你不能保證讓你的定時器回來。還有其他一些方法可以解決這個問題,但這個問題超出了範圍。

+0

您能解釋一些其他方式來解決在後臺有計時器嗎?我知道它不是針對這個問題,但它會幫助我很大程度上與我的項目,即時通訊新的android編程,所以即時通訊仍然試圖學習 – Hockeyman271 2012-08-07 20:50:39

+0

張貼的問題,併發送給我的鏈接 – 2012-08-07 20:51:41

+0

我會盡快我有時間,但我試過這種方法和它的工作原理,唯一的問題是現在我的用戶界面不會在活動重新啓動時更新?我可以在我的通知欄中看到計時器仍在運行,但用戶界面不會填充 – Hockeyman271 2012-08-07 20:59:33