简体   繁体   English

Android-获取线程的返回值

[英]Android - Getting return value of a thread

I start with Android and Java, and my English is not very good (sorry). 我从Android和Java开始,但是我的英语不太好(抱歉)。 I'm doing a application which compare 2 pictures taking by the camera and return a float value = a ratio of identical pixels in the 2 pictures. 我正在做一个比较相机拍摄的2张图片并返回float值= 2张图片中相同像素比率的应用程序。

public static float comparePic(String img_1, String img_2){
    Bitmap bitmap1 = BitmapFactory.decodeFile(img_1);
    Bitmap bitmap2 = BitmapFactory.decodeFile(img_2);
    int equ = 0;
    //get one height and one width because we assume that pictures have always same sizes
    int h = bitmap1.getHeight();
    int w = bitmap1.getWidth();
    for(int y=0;y<h;y++){
        for (int x=0;x<w;x++){
            int pixel1 = bitmap1.getPixel(x,y);
            int pixel2 = bitmap2.getPixel(x,y);
            //alpha doesn't matter, they're jpg
            int redValue1 = Color.red(pixel1);
            int redValue2 = Color.red(pixel2);
            int greenValue1 = Color.green(pixel1);
            int greenValue2 = Color.green(pixel2);
            int blueValue1 = Color.blue(pixel1);
            int blueValue2 = Color.blue(pixel2);
            if (redValue1==redValue2 && greenValue1==greenValue2 && blueValue1==blueValue2){
                equ++;
            }
        }
    }
    return (float)equ/(h*w);
}

When I execute it, I have this message : "I/Choreographer﹕ Skipped 730 frames! The application may be doing too much work on its main thread." 当我执行它时,我收到以下消息:“ I / Choreographer:跳过了730帧!该应用程序可能在其主线程上做过多的工作。” So I tried to do it with a thread, but I'm always failing because I don't know how to return the value. 因此,我尝试使用线程来执行此操作,但是我总是失败,因为我不知道如何返回值。 Futhermore, by skipping frames I guess, the ratio is not correct. 此外,我估计通过跳过帧,该比率是不正确的。 I know that it's an asynchonous work, so what can I do ? 我知道这是一项异步工作,该怎么办? Thanks ! 谢谢 !

You can simply add a public (setter-)method in your main class (or wherever you need the value). 您可以在您的主类中(或需要该值的任何地方)简单地添加一个公共(设置方法)。 When your async thread is done call the method with equ as the parameter. 完成异步线程后,以equ作为参数调用该方法。

You obviously need to care about thread-safety so consider making the method sychronized. 您显然需要关心线程安全性,因此请考虑使该方法同步。

You should give a try to AsyncTask . 您应该尝试AsyncTask It's a class specifically prepared for background processing. 这是专门为后台处理准备的类。 It has some drawbacks (it's not good idea to do networking with AsyncTask), but for some picture comparison stuff it is a great tool. 它有一些缺点(与AsyncTask建立网络不是一个好主意),但是对于某些图片比较而言,它是一个很好的工具。

Define an Asynctask with a interface and implement that interface in the main Activity. 用接口定义一个Asynctask并在主Activity中实现该接口。

That way you can notify that host activity that the background asynctask has completed. 这样,您可以通知主机活动后台异步任务已完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM