java - 从另一个函数调用的改造任务(执行)不会等到任务完成

标签 java android asynchronous

从我的登录 Activity (打开的第一个 Activity )中,我总是检查 token 在我的服务器上是否仍然处于 Activity 状态,这是通过对服务器进行 API 调用的异步任务完成的。

这是来自 LoginActivity 的代码:

 private void checkIfAuthenticated(){
    SharedPreferences reader_auth = getSharedPreferences(getString(R.string.auth_preferences), MODE_PRIVATE);

    String auth_key = reader_auth.getString(getString(R.string.auth_access_key),null);
    String mobile_token = reader_auth.getString(getString(R.string.auth_mobile_token),null);

    if (auth_key != null) {
        //THIS PART RUNS THE TOKEN CHECK TO SERVER
        authGlobal = new AuthenticationGlobal(this);
        // I WANT THIS FUNCTION TO FINISH FIRST BEFORE IT GOES TO THE NEXT PART OF THE CODE
        authGlobal.runAuthenticationCheck(auth_key,mobile_token);


        String Auth_Key = reader_auth.getString(getString(R.string.auth_access_key),null);

        Log.d("Auth Key Check 0",Auth_Key);
        if (Auth_Key != null) {
            Log.d("Auth Key Check 1",Auth_Key);
            MoveToDashboardActivity();
        }

    }
}

runAuthenticationCheck(String,String) 代码位于另一个类上(因为它是一个全局函数,可以从任何 Activity 的任何函数调用)

runAuthenticationCheck 位于 AuthenticationGlobal 类中,代码如下:

public void runAuthenticationCheck (String mobile_token, String Access_token) {
    checkAuthTask = new checkAuthenticationTask(mobile_token, Access_token);
    checkAuthTask.execute((Void) null);
}

public class checkAuthenticationTask extends AsyncTask<Void, Void, Boolean> {


    private GetDataService service;
    private String mobile_token;
    private String access_token;
    checkAuthenticationTask( String Access_token,String Mobile_token) {
        /*Create handle for the RetrofitInstance interface*/
        mobile_token = Mobile_token;
        access_token = Access_token;

        service = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class);
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        // TODO: attempt authentication against a network service.
        try {
            Call<CheckAuthenticationResponse> call = service.checkAuthentication(access_token,mobile_token);

            Response<CheckAuthenticationResponse> CheckAuthenticationResponse = call.execute();

            if (CheckAuthenticationResponse.code() == 200){


            } else{
                //clear shared preferences
                clearAuthentication();
                Log.e("AuthKey Global","Expired0");
            }

        } catch (IOException ea) {
            clearAuthentication();
            Log.e("AuthKey Global","Expired1");
            Log.e("AuthenticationResponseError Global","Network Went Wrong");
            ea.printStackTrace();
        }
        return true;
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        //mAuthTask = null;
        //showProgress(false);
        if (success) {
            Log.e("AuthKey Global","Done");
        } else {
           // mPasswordView.setError(getString(R.string.error_incorrect_password));

            clearAuthentication();
            Log.e("AuthKey Global","Expired2");
        }
    }

    @Override
    protected void onCancelled() {
        //mAuthTask = null;
        //showProgress(false);
    }

有 2 个类/Activity :“LoginActivity”和“AuthenticationGlobal”。

有3个功能:

  1. checkIfAuthenticated => 位于 LoginActivity 中,这实际上又调用另一个类中的另一个函数(函数编号 2:“runAuthenticationCheck”)
  2. runAuthenticationCheck => 位于 AuthenticationGlobal。其中通过 .execute(...) 命令调用 AsyncTask。
  3. checkAuthenticationTask => 位于 AuthenticationGlobal 中。它实际上对服务器进行 API 调用。

从“LoginActivity”中,我运行一个函数“checkIfAuthenticated”=>,它调用位于“AuthenticationGlobal”=>的函数“runAuthenticationCheck”,该函数运行一个任务“checkAuthenticationTask”,该任务对服务器进行 API 调用并执行其他操作。

问题是,当我调用第一个函数时,代码不会等到函数“checkIfAuthenticated”/“checkAuthenticationTask”完成。有没有办法让我的应用程序等到任务/功能先完成?

谢谢

更新: 我只需要在 .execute() 末尾添加 .get() 并将其包装在 try catch 中。

public void runAuthenticationCheck (String mobile_token, String Access_token) {
        checkAuthTask = new checkAuthenticationTask(mobile_token, Access_token);
        try {
            checkAuthTask.execute((Void) null).get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

最佳答案

嗯。我只需要在execute() 上添加一个.get() 并将其包装在try catch 中。

一个愚蠢的错误。

这是更新后的代码:

public void runAuthenticationCheck (String mobile_token, String Access_token) {
        checkAuthTask = new checkAuthenticationTask(mobile_token, Access_token);
        try {
            checkAuthTask.execute((Void) null).get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

关于java - 从另一个函数调用的改造任务(执行)不会等到任务完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58152491/

相关文章:

java - 为什么选择排序比冒泡排序更快?

java - 我在类(class)概述中做错了什么?

java - 尝试让 Cherokee Alphabet 显示在 Android Studio 中

android - AutofillManager NPE : trying to invoke virtual method containsKey(java. lang.String)' 在空对象引用上崩溃

javascript - 计算地理位置时无法设置外部(全局?)变量

java - JMS 可以用于所有需要异步消息传递的情况吗?

android - 在 Android Marshmallow 中遍历文件系统

Delphi TParallel.For 比经典 for 慢

javascript - 有条件地在 Controller 中接收同步或异步对象( Angular 、 ionic )

android - 使用 'kotlin-kapt' 插件,Android Studio 不提供有关 Dagger 2 的特定错误