When is the runnable content published in postdelayed actually executed on Android?

I use postdelayed and some other code executed on the main thread. I run it several times and always see the following output:

As you can see from the log output, it doesn't matter if the delay is 50 ms. the message "postdelayed" is input after about 100 ms (601-511 = 90). It seems that the delayed runnable object has been added to the end of the message queue of my UI thread. However, is there any guarantee for the exact time to type postdelayed? Can I enter it in the middle of the for loop?

package sample1.com.sample_1;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class MainActivity extends AppCompatActivity {


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

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d("MainActivity", "postDelayed");
            }
        }, 10);
        for (int i = 0; i < 10000; i++) {
            Log.d("MainActivity", "i = " + i);
        }
    }

    @Override
    protected void onResume() {
        Log.d("MainActivity", "onResume");
        super.onResume();

    }
}

resolvent:

There are also logs from other services and applications, so it will be incorrect to calculate the processor delay according to the log output. The logging mechanism on Android has its own queue, so your message may actually be delayed due to other logs in the queue

My suggestion is to use system. Nanotime() to calculate the time between handler delays. As far as I know, it provides the most accurate timer value

Finally, to answer your question, no, you can't exactly point out when to take action. There are thousands (if not millions) of different conditions that may delay the operation of your application, especially if it is asynchronous

Edit: this delay cannot guarantee an accurate 50ms delay, but it can guarantee "at least" 50ms delay

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>