延迟结束前,Android获取公共位图函数返回 [英] Android Getting public Bitmap function return before Delay ended

查看:77
本文介绍了延迟结束前,Android获取公共位图函数返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个公共静态位图,其中有2000密耳的延迟。我的问题是在执行被延迟的代码之前,我得到了 return

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.

我的函数结构:

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条调试消息-在延迟部分中,其中一条返回之前。

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

这是我在logcat中得到的内容:

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)


推荐答案

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

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.

简单地,在2000ms之后的某个时间,函数运行 Runnable 内的c>被调用。

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.

要掌握的核心概念是,您创建的匿名 Runnable 类中的代码不会阻止当前执行线程。

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

然后在您的调用代码中以某些方式实现WhenReady接口:

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

interface WhenReady {
     Bitmap doSomethingWithBitmap(Bitmap bitmap);
}

这篇关于延迟结束前,Android获取公共位图函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆