【发布时间】:2016-07-05 22:30:53
【问题描述】:
我正在开发一个 Android 应用程序,现在我正在为登录系统编写一些方法。我正在尝试创建一个 boolean 方法,该方法根据服务器的响应返回 true 或 false。这是我的代码:
public static boolean login(final String name, final String password) {
final boolean result;
Thread nt = new Thread() {
@Override
public void run() {
URL url;
HashMap<String, String> postDataParams = new HashMap<String, String>();
postDataParams.put("name", name);
postDataParams.put("password", password);
try {
url = new URL("");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
e.printStackTrace();
}
}
};
nt.start();
}
问题是每个返回语句都被突出显示,因为cannot return a value from a method with void result type,这是我无法理解的,因为它被明确定义为boolean 方法。我想,这与我创建的新线程有关,但由于此应用程序将在 Android 设备上运行,因此我必须在单独的线程中运行我的查询。
提前致谢!
【问题讨论】:
-
也许你可以尝试等待线程完成,并从线程中将局部变量更改为函数
boolean login并在函数通过等待语句后返回
标签: java android multithreading return boolean