Android Getting public Bitmap function return befo

2019-08-18 15:14发布

So, I have a public static Bitmap with a delay of 2000 mils inside of it. My problem is that I get return before code that is getting delayed is executed.

To give you the idea of my function structure:

public static Bitmap getBitmapFromWebview(WebView webView){
    *******************some code here
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            ********************declaring bm bitmap
            Log.i("DelayD", "Delay");
        }
    }, 2000);


    Log.i("DelayD", "Return");
    return bm;
}

I've set up 2 debug messages - inside the delayed section, and one right before the return.

Here's what I get in the logcat:

08-11 20:45:13.520 I/DelayD: Return
08-11 20:45:16.173 I/DelayD: Delay

as well as an Error messages, which I'm not sure are relevant:

08-11 20:44:45.170 E/Sensors: new setDelay handle(0),ns(66667000)m, error(0), index(2)
08-11 20:44:48.082 E/Sensors: new setDelay handle(0),ns(66667000)m, error(0), index(2)

2条回答
干净又极端
2楼-- · 2019-08-18 15:19

My problem is that I get return before code that is getting delayed is executed.

As is covered in the documentation, postDelayed() does not delay the method in which you call it. It schedules a Runnable to run after the designated delay period. getBitmapFromWebview() will return in microseconds, hopefully.

查看更多
手持菜刀,她持情操
3楼-- · 2019-08-18 15:45

When the function handler.postDelayed is called on your handler it takes the Runnable instance you created and stores it in a variable. After that concludes then the next line in your function executes.

Simply, at a later time after 2000ms, the function run inside your Runnable is called.

Therefore the order you are seeing is very predictable and the result you are seeing.

The core concept to grasp is the fact that the code inside the anonymous Runnable class you create does not block the current thread of execution. It is run at a later time.

This function theoretically could be written:

public static void getBitmapFromWebview(WebView webView, final WhenReady callback){

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            callback.doSomethingWithBitmap(bitmap);
        }
    }, 2000);
}

Then implement the WhenReady interface some how in your calling code:

interface WhenReady {
     Bitmap doSomethingWithBitmap(Bitmap bitmap);
}
查看更多
登录 后发表回答