问题
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.
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.
Use a Callable instead of a
Runnable
. ACallable
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