简体   繁体   English

当我更改活动以继续计算 Android Studio 中的时间时,如何让我的计时器计数?

[英]How can I let my Timer Count when I change the activity to keep counting the time in Android Studio?

I going to fix the issue about when I click the to go another activity and my timer started before, when I back to the timer count activity, the timer stopped and auto reset to 0. How can I manage the activity when I back to timer activity and keep the timer counting?我要解决当我单击 go 另一个活动并且我的计时器之前启动的问题,当我回到计时器计数活动时,计时器停止并自动重置为 0。当我回到计时器时如何管理活动活动并保持计时器计数?

Here are my code of my timer counter.这是我的计时器代码。

// TimerCount
    TextView txtvTimer;
    Button pauseStartBtn;
    Button stopFinishBtn;
    boolean timerStarted = false;
    Timer timer;
    TimerTask timerTask;
    Double time = 0.0;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timer_count);
        Log.d(TAG_LIFECYCLE, "In the activity_timer_count onCreate() event");

// timer
        txtvTimer = (TextView) findViewById(R.id.txtvTimer);
        pauseStartBtn = (Button) findViewById(R.id.btnStartPause);
        stopFinishBtn = (Button) findViewById(R.id.btnStopFinish);
        stopFinishBtn.setEnabled(false);

        timer = new Timer();

        // bottom nav
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav);

        bottomNavigationView.setSelectedItemId(R.id.timerCountActivity);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.mainActivity:
                        startActivity(new Intent(getApplicationContext(),MainActivity.class));
                        overridePendingTransition(0,0);
                        return true;
                    case R.id.mapActivity:
                        startActivity(new Intent(getApplicationContext(),MapActivity.class));
                        overridePendingTransition(0,0);
                        return true;
                    case R.id.timerCountActivity:
                        return true;
                    case R.id.userInfoActivity:
                        startActivity(new Intent(getApplicationContext(),UserInfoActivity.class));
                        overridePendingTransition(0,0);
                        return true;
                    case R.id.settingActivity:
                        startActivity(new Intent(getApplicationContext(),SettingActivity.class));
                        overridePendingTransition(0,0);
                        return true;
                }
                return false;
            }
        });
    }
    // timer reset button
    public void resetTapped(View v) {
        AlertDialog.Builder resetAlert = new AlertDialog.Builder(this);
        resetAlert.setTitle("Reset Timer");
        resetAlert.setMessage("Reset the timer?");
        resetAlert.setPositiveButton("Reset", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (timerTask != null) {
                    timerTask.cancel();
                    setButton("START", R.color.green);
                    time = 0.0;
                    timerStarted = false;
                    txtvTimer.setText(formatTime(0,0,0));
                }
            }
        });
        resetAlert.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        resetAlert.show();
    }
    // timer start pause button
    public void startPauseTapped(View v) {
        if (timerStarted == false){
            timerStarted = true;
            setButton("PAUSE", R.color.red);
            startTimer();
            onStartClicked(v);
            onLocateClicked(v);
            stopToPushData(v);
        } else {
            timerStarted = false;
            setButton("Resume", R.color.green);

            timerTask.cancel();
            onStartClicked(v);
            onLocateClicked(v);
        }
    }

    private void setButton(String start, int color) {
        pauseStartBtn.setText(start);
        pauseStartBtn.setTextColor(ContextCompat.getColor(this, color));
    }

    private void startTimer() {
        timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        time++;
                        txtvTimer.setText(getTimerText());
                    }
                });
            }
        };
        timer.scheduleAtFixedRate(timerTask,0,1000);
    }
    private String getTimerText() {
        int rounded = (int) Math.round(time);
        int seconds = ((rounded % 86400) % 3600) % 60;
        int minutes = ((rounded % 86400) % 3600) / 60;
        int hours = ((rounded % 86400) / 3600) ;

        return formatTime (seconds, minutes, hours);
    }

    private String formatTime(int seconds, int minutes, int hours) {
        return String.format("%02d",hours) + " : " + String.format("%02d",minutes) + " : " + String.format("%02d",seconds);
    }

Second, how can I get the timer to calculate the time per second?其次,如何让计时器计算每秒的时间?

Is it rounded % 86400 will be the real second I have counted?是否rounded % 86400将是我计算的真正秒数?

I think it's better to use chronometer我认为最好使用chronometer

Xml: Xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">

<Chronometer
    android:id="@+id/chronometer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Main Acitvity:主要活动:

public class MainActivity extends AppCompatActivity {

Chronometer chronometer ;
long stopTime ; // this variable will count the time when stop counting (when you have left the activity)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     chronometer = (Chronometer) findViewById(R.id.chronometer);

}

void StartCounting() {
    chronometer.setBase(SystemClock.elapsedRealtime()-stopTime); // This line will set the time to correct when you return to the activity
   chronometer.start();
}

void PauseCounting() {
    stopTime = SystemClock.elapsedRealtime()-chronometer.getBase();
    chronometer.stop();
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android:当我在另一个活动中时,如何保持倒计时计时器运行并在超时时显示消息? - Android: How to keep count down timer running and display a message when time out , while I am in another activity? 当屏幕关闭或锁定在 Java 的 Android 工作室中时,如何继续运行活动? - How can I keep running an activity when screen is off or locked in Android studio in Java? 更改布局时如何保留信息 android studio - How to keep information when I change layout android studio 如何在android中的卡片标题上显示倒数计时器? - How can i show count down timer on card title in android? 我如何在onpostexecute Android上更改活动 - How i can to change activity on onpostexecute Android 我无法在android studio中更改活动主题 - I can't change the activity theme in android studio 在游戏过程中如何更改Timer()的速度? - How can i change the speed on my Timer() during my game? Android Studio Java:如果产品已经存在于我的购物车活动中,我该如何更新我的数量? - Android Studio Java: How can I update my quantity if the product already exist's in my Cart Activity? 为什么我的计时器会在我停止时使我的 android 活动崩溃? - Why does my Timer crashes my android activity when I stop it? 如何让用户在我的 android 应用程序中保持登录状态 - How can I let users remain logged in my android app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM