Android Getting public Bitmap function return before Delay ended

别等时光非礼了梦想. 提交于 2019-12-11 14:47:43

问题


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)

回答1:


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);
}



回答2:


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.



来源:https://stackoverflow.com/questions/45642180/android-getting-public-bitmap-function-return-before-delay-ended

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!