Returning value from thread Java/ Android

限于喜欢 提交于 2019-12-19 11:36:18

问题


I have the following thread in my android class. How can I get the value of err from the thread???

public int method(){
new Thread(new Runnable() {
        int err;

        @Override
        public void run() {
            err = device.verify(30, 5, coderChoice, detectModeChoice,
                      0, listSearch, callbackCmd, MTFPSD.this, matchingScore);
            updateView("Finger Captured Successfully", err);

        }
    }).start();

return err;
}

I want the value to be the return value of the method but for the life of me I can't get the value...


回答1:


You have two ways of achieving this.

  1. The bad way. Create a mutable object like a list of integers and let the Thread (Runnable) write into the list. You can access the value in the list in the outer class / method.

  2. Use a Callable instead of a Runnable . A Callable can return values




回答2:


Otherwise, You can use Handler to catch err value.

public void method(){
    new Thread(new Runnable() {
            int err;

            @Override
            public void run() {
                err = device.verify(30, 5, coderChoice, detectModeChoice,
                          0, listSearch, callbackCmd, MTFPSD.this, matchingScore);
                updateView("Finger Captured Successfully", err);

                mHandler.sendEmptyMessage(err);

            }
        }).start();

    return;
    }

Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        int err = msg.what;

        // something to do.

    }
};



回答3:


This is what I do when my Runnable and Handler are in different classes ^_^

public void task(final Handler h){


        Runnable r = new Runnable() {
            @Override
            public void run() {
                //Do something...

                Bundle bundle = new Bundle();
                bundle.putString("Value", "Done");
                Message toDeliver = new Message();
                toDeliver.setData(bundle);
                h.sendMessage(toDeliver);

            }
        };

        Thread thread = new Thread(r);
        thread.start();

    }



Handler h = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                Bundle bundle = msg.getData();
                String result = bundle.getString("Value");
                Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
            }
        };


来源:https://stackoverflow.com/questions/28668517/returning-value-from-thread-java-android

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