我在Android应用程序中对用户进行身份验证的方式存在问题,我现在就是这样做的:
按下“登录”按钮时:
// Get user's email and password from the input
val user = User()
user.email = emailInput?.text.toString()
user.password = passwordInput?.text.toString()
// Execute sign in request
if (userService.signIn(user)) {
Log.d("HTTP", "Success, switching to profile")
// Login success, show profile page
errorText?.text = ""
val profileFragment = ProfileFragment()
fragmentManager.beginTransaction()
.add(R.id.fragment_container, profileFragment).addToBackStack("profile fragment").commit()
} else {
// Login failed, show error message
errorText?.text = "Login Error"
}
这是我的Fuel POST请求:
fun signIn(user: User): Boolean {
val url = "$ENDPOINT/signin"
var success = false
val json = JSONObject()
json.put("email", user.email).put("password", user.password)
val (request, response, result) = Fuel.post(url).body(json.toString()).responseJson()
Log.i("Login", "Request to sign in user ${user.email}...")
result.success { jsonRes: Json ->
Log.i("Login", "Got response $jsonRes")
val code: String = jsonRes.obj().getString("code")
if (code == "200") {
success = true
}
}
result.failure {
Log.d("HTTP", "FAILURE : $result")
}
return success
}
正如您所看到的,我的请求正在阻止(感谢Fuel),因为我想返回一个布尔值来确认登录是否成功,但是这会导致
NetworkOnMainThreadException
例外。
是否有更好/更常见的方式以异步方式处理登录?如何在不等待另一个线程的请求的情况下告诉我的Fragment登录是否成功?