我需要的是返回token对象作为adapter.authenticate()放置在线程中的操作的结果.不知道如何从那里返回一个物体,请指教.谢谢.
public Token authenticate(final String email, final String password) {
Thread mThread = new Thread(new Runnable() {
@Override
public void run() {
try {
token = adapter.authenticate(email, password); // I need token to return with authenticate() method.
} catch (NotAuthenticatedException e) {
}
}
});
mThread.start();
}
Run Code Online (Sandbox Code Playgroud)
试试这个:
public Token authenticate(final String email, final String password) {
final Token[] tokens = new Token[1];
Thread mThread = new Thread(new Runnable() {
@Override
public void run() {
try {
tokens[0] = adapter.authenticate(email, password);
} catch (NotAuthenticatedException e) {
}
}
});
mThread.start();
mThread.join();
return tokens[0];
}
Run Code Online (Sandbox Code Playgroud)
说明:
token一个Token因为它必须final.join该线程,否则authenticate在线程设置令牌之前可能会返回tokens[0].还应该注意的是,通过这种方式使用线程,你没有取得多少成就.你正在做的事情实际上只是一种昂贵的召唤方式adapter.authenticate(email, password).
如果您的目标是在等待身份验证时避免阻止UI,则解决方案需要更复杂.基本上,您需要更改应用程序,以便需要进行身份验证的视图元素始于禁用(例如,它们是灰色的/忽略点击/无论如何).您执行身份验证是一个单独的线程,如上所述,当它完成时,您可以将事件发送到UI线程.在接收到该事件时,UI线程应该启用禁用的视图元素.
| 归档时间: |
|
| 查看次数: |
2615 次 |
| 最近记录: |