Android 在延迟结束前获取 public 位图函数 return

Android Getting public Bitmap function return before Delay ended

所以,我有一个 public static Bitmap,里面有 2000 密耳的延迟。我的问题是在执行延迟的代码之前我得到 return

让您了解我的函数结构:

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

我设置了 2 条调试消息 - 在延迟部分内,一条在 return 之前。

这是我在 logcat 中得到的:

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

以及错误消息,我不确定是否相关:

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)

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

the documentation 所述,postDelayed() 不会延迟您调用它的方法。它在指定的延迟期后安排 Runnable 到 运行。 getBitmapFromWebview() 将在微秒内 return,希望如此。

当在您的处理程序上调用函数 handler.postDelayed 时,它会获取您创建的 Runnable 实例并将其存储在一个变量中。结束后,函数中的下一行将执行。

简单地说,在 2000 毫秒后的某个时间,调用 Runnable 中的函数 run

因此,您看到的顺序和结果是非常可预测的。

要掌握的核心概念是您创建的匿名 Runnable class 中的代码不会阻塞当前执行线程。稍后是运行。

这个函数理论上可以写成:

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

然后在您的调用代码中实现 WhenReady 接口:

interface WhenReady {
     Bitmap doSomethingWithBitmap(Bitmap bitmap);
}