0

我有一个活动,我需要实现一个基本的 mm::ss 计时器。下面是我为它编写的代码。但是问题是,当我在模拟器中按下后退按钮并再次单击应用程序时,值变化得更快。看起来 onCreate 又被调用了。我该如何纠正这个问题?我曾尝试创建一个布尔变量,并在第一次调用任务时将其设置为 true。我仅在值为 false 时调用 startPeriodidUpdates()。但是 onCreate 再次使用 false 值创建变量。

   public class GraphicsActivity extends Activity {
static int seconds = 0;
static int minutes = 0;
public static String time_elapsed;
public static boolean clearView = true;
Handler myhandler = new Handler();
public static String min,sec;  
public static boolean running = true;


   @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
     startPeriodicUpdates();

    } 
    public void onResume(){
    super.onResume();
    } 
    public void onPause() {
    super.onPause();    
    }
   public void onStop(){
   super.onStop();
    }

   public void startPeriodicUpdates()
   {
periodicCall();
   }
   public void stopPeriodicUpdates(){ 
     myhandler.removeCallbacksAndMessages(myhandler);
   }

   public  void periodicCall()
    {

seconds++;
if(seconds ==60)
{
    seconds=0;
    minutes++;
    if(minutes==60)
    {
        seconds=0;
        minutes=0;
    }
}
// left-padding zeros to the minutes and seconds values
min = String.format("%02d",minutes);
sec = String.format("%02d",seconds);
time_elapsed =  min + ":" + sec;
time_elapsed =  min + ":" + sec + "";
myhandler.postDelayed(new Runnable(){
    public void run(){
        periodicCall();

    }
},1000);

}

4

4 回答 4

1

我认为如果您使用服务来实现您的计时器会更好。即使您按下返回按钮,服务也会继续运行。

在这里你可以看到我不久前提出的一个问题。您可以使用服务查看自定义计时器的实现。

您想要接收 Chronometer 值的活动只需要一个 BroadcastReceiver ,例如:

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        mMilis = intent.getLongExtra("milis",0);
        String time = intent.getStringExtra("tiempo");
        // Do Something with the time
    }
};
于 2012-04-24T06:46:05.787 回答
1

也许这会有所帮助:执行 peridic 任务的正确方法是在 in 中注册处理程序OnResume并在 in 中取消注册OnPause。(您可以在其他地方取消注册,但 OnPause 很重要)

于 2012-04-24T05:24:25.530 回答
0

You can use shared preference to use this method only once .

//pass true first time

 protected void storeSharedPrefs(Boolean value) {
        /*
         * Storing in Shared Preferences
         */
        editor.putString("first", value);
        editor.commit();  //Commiting changes
    } 

Check each on time application is loaded, whether its the first time and configuration details has been entered correctly by checking SharedPreferences

private boolean first_time_check() {
        /* 
         * Checking Shared Preferences if the user had pressed 
         * */
        Boolean  first = uPreferences.getString("first", false);

            return first;
    }
于 2012-04-24T06:09:08.067 回答
0

这可能不是上述问题的解决方案,但如果您只想更新视图并从给定时间计数,也许看看Chronometer。如果您想倒计时并更新视图,您可以使用CountDownTimer

于 2012-04-24T05:25:29.083 回答