gpt4 book ai didi

android - 如何将异步任务的结果返回到android中的 Activity ?

转载 作者:行者123 更新时间:2023-11-29 15:24:01 25 4
gpt4 key购买 nike

我创建了一个登录 Activity ,它使用另一个类 - LoginService,它是一个用于网络通信的 AsyncTask。

 public void onClick(View view) {

if (editTextPassword.getText().toString() != null & editTextUsername.getText().toString() != null){

new LoginService(editTextUsername.getText().toString(), editTextPassword.getText().toString()).execute();

if(loginSuccess!=false){
//Used to move to the Cases Activity
Intent casesActivity = new Intent(getApplicationContext(), CasesActivity.class);
startActivity(casesActivity);
}else{
Toast.makeText(getApplicationContext(),"Incorrect Details", Toast.LENGTH_LONG).show();
}
}
else{
//Display Toaster for error
Toast.makeText(getApplicationContext(),"Please enter your details", Toast.LENGTH_LONG).show();
}
}

在 LoginService 完成执行之前, Activity 已经通过 Intent 变量移动到另一个 Activity 。我不懂为什么。 LoginService 的想法是验证用户的凭据。如果它返回 true,那么它可以切换到另一个 Activity 。

最佳答案

您不希望以这种方式执行此操作。 .execute() 将尽快开始,但不能保证(并且可能保证不会)它会让您的loginSuccess 值(value)及时回馈给您。

new LoginService(...).execute(); 之后的所有内容都应移至 onPostExecute() 中:

private Context mContext = null;
public void setContext(Context context) {
mContext = context;
}
@Override
protected void onPostExecute(Void result) {
if(loginSuccess!=false){
//Used to move to the Cases Activity
Intent casesActivity = new Intent(mContext, CasesActivity.class);
startActivity(casesActivity);
}else{
Toast.makeText(mContext,"Incorrect Details", Toast.LENGTH_LONG).show();
}
}

然后,您必须像这样调用 setContext():

LoginService service = new LoginService(editTextUsername.getText().toString(), editTextPassword.getText().toString());
service.setContext(getApplicationContext());
service.execute();

关于android - 如何将异步任务的结果返回到android中的 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14843850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com