简体   繁体   English

当我第一次运行我的应用程序时,您是否认为 runTimer() 方法会无限运行,因此永远不会调用 onStart() 方法?

[英]When I run my app for the first time, don't you think runTimer() method will run infinitely and so the onStart() method will never get called?

My OnStart() method should not get called because my onCreate() method will run infinitely.我的 OnStart() 方法不应被调用,因为我的 onCreate() 方法将无限运行。 When OnCreate method runs, the runTimer() method gets called.当 OnCreate 方法运行时,会调用 runTimer() 方法。 This runTimer method will run infinitely because of handler.postDelayed.由于 handler.postDelayed,此 runTimer 方法将无限运行。 How is it that Android Studio is able to finish the infinite loop of the runTimer() method and then call OnStart() method? Android Studio 是如何完成 runTimer() 方法的无限循环,然后调用 OnStart() 方法的?

    // MY STOPWATCH APP        
    


    public class MainActivity extends AppCompatActivity {
    private int seconds = 0;
    private boolean running;
    private boolean wasRunning;

    @Override
    // ON RUNNING MY APP FOR THE FIRST TIME THIS METHOD WILL GET CALLED FIRST.
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState != null) {
            seconds = savedInstanceState.getInt("seconds");
            running = savedInstanceState.getBoolean("running");
            wasRunning = savedInstanceState.getBoolean("wasRunning");
        }
        
        runTimer();
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putInt("seconds", seconds);
        savedInstanceState.putBoolean("running", running);
        savedInstanceState.putBoolean("wasRunning", wasRunning);
    }

    @Override
    protected void onStop() {
        super.onStop();
        wasRunning = running;
        running = false;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (wasRunning) {
            running = true;
        }
    }

    //Start the stopwatch running when the Start button is clicked.
    public void onClickStart(View view) {
        running = true;
    }

    //Stop the stopwatch running when the Stop button is clicked.
    public void onClickStop(View view) {
        running = false;
    }

    //Reset the stopwatch when the Reset button is clicked.
    public void onClickReset(View view) {
        running = false;
        seconds = 0;
    }

    //Sets the number of seconds on the timer.
    private void runTimer() {
        final TextView timeView = (TextView)findViewById(R.id.tv_time_view);
        final Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                int hours = seconds/3600;
                int minutes = (seconds%3600)/60;
                int secs = seconds%60;
                String time = String.format(Locale.getDefault(),
                        "%d:%02d:%02d", hours, minutes, secs);
                timeView.setText(time);
                if (running) {
                    seconds++;
                }
                handler.postDelayed(this, 1000);
            }
        });
    }
}

Why do you think that runTimer() will run indefinitely?为什么您认为runTimer()会无限期地运行?

handler.post() and handler.postDelayed() add an object (your new Runnable() {} ) to the message queue so the objects run() method can be executed some time later. handler.post()和 handler.postDelayed handler.postDelayed()添加一个 object (你的new Runnable() {} )到消息队列,这样对象的run()方法可以稍后执行。

handler.post() returns after adding the object to the message queue and therefore the runTimer() and onCreate() methods finish normally. handler.post()在将 object 添加到消息队列后返回,因此runTimer()onCreate()方法正常完成。


Why "Message Queue"?为什么是“消息队列”? Because the documentation says so:因为文档是这样说的:

https://developer.android.com/reference/android/os/Handler : https://developer.android.com/reference/android/os/处理程序

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue Handler 允许您发送和处理与线程的 MessageQueue 关联的 Message 和 Runnable 对象

https://developer.android.com/reference/android/os/Handler#post(java.lang.Runnable) : https://developer.android.com/reference/android/os/Handler#post(java.lang.Runnable)

Causes the Runnable r to be added to the message queue.导致将 Runnable r 添加到消息队列中。 The runnable will be run on the thread to which this handler is attached. runnable 将在此处理程序附加到的线程上运行。

https://developer.android.com/reference/android/os/Handler#postDelayed(java.lang.Runnable,%20long) : https://developer.android.com/reference/android/os/Handler#postDelayed(java.lang.Runnable,%20long)

Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses.导致将 Runnable r 添加到消息队列,在指定的时间过后运行。

The whole point of using a Handler is to allow the Runnable s that are post() ed to execute at some later point in time so that the current thread can continue its work.使用Handler的全部意义在于允许post() ed 的Runnable在稍后的某个时间点执行,以便当前线程可以继续其工作。

If the handler would execute the code within the Runnable directly (and blocking) then you could have written your code as new Runnable() { /*...*/ }.run();如果处理程序将直接执行Runnable中的代码(并阻塞),那么您可以将代码编写为new Runnable() { /*...*/ }.run();

The handler.post will execute the Runnable on the handler thread, so runTimer() will exist after the call to handler.post() handler.post 将在处理程序线程上执行 Runnable,因此 runTimer() 将在调用 handler.post() 之后存在

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

相关问题 没有主要方法时,程序如何运行 - How does my program run when I don't have a main method 为什么 onStart() 方法在我的 android 项目中的 onCreate 之前运行? - why does onStart() method run before onCreate in my android project? Thread.start()方法永远不会调用run() - run() is never called by Thread.start() method 当我第一次运行我的应用程序并授予权限时,它不会加载歌曲 - When i run my app for the first time and give permissions it doens't load the songs 如何定义第一次调用我的 @Scheduled 方法的时间? - How to define when my @Scheduled method should be called first time? JSP文件方法似乎从未在首次运行后被调用 - JSP file method seems like never gets invoked after first time run 为什么我运行时重复我的方法 - Why is my method repeating when I run 为什么我的主类没有运行我调用的方法? - Why doesnt my main class run the method i called? 我可以配置 Spring MVC 应用程序,以便在我运行应用程序时,控制器或任何方法都应该被自动调用 - Can i configure the Spring MVC application so that when ever i run the application, the controller or any method should be called automatically 当我运行应用程序时,活动 xml 的更改不会出现在我的设备上 - The changes of the activity xml don't appear on my device when I run the app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM