Из моего входа в систему (первое действие открыто) Я всегда проверяю, активен ли токен на моем сервере, что выполняется с помощью асинхронной задачи, которая выполняет 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) находится в другом классе (поскольку это была глобальная функция, которую можно вызывать из любой функции в любом действии)
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 класса / действия: «LoginActivity» и «AuthenticationGlobal».
Есть 3 функции:
- checkIfAuthenticated =>, расположенный в LoginActivity, который, в свою очередь, фактически вызывает другую функцию из другого класса (функция номер 2: "runAuthenticationCheck")
- runAuthenticationCheck => находится в AuthenticationGlobal.который вызывает AsyncTask с помощью команды .execute (...).
- checkAuthenticationTask => находится в AuthenticationGlobal.Который фактически выполняет API-вызов к серверу.
Из «LoginActivity» я запускаю функцию «checkIfAuthenticated» =>, которая вызывает функцию «runAuthenticationCheck», расположенную в «AuthenticationGlobal» =>, которая запускает задачу «checkAuthenticationTask»"который делает API Call to server и делает вещи.
Проблема в том, что когда я вызывал первую функцию, код не ждет, пока не будет выполнена функция "checkIfAuthenticated" / "checkAuthenticationTask".Есть ли способ заставить приложение ждать, пока задача / функция не завершится первой ??
Спасибо
ОБНОВЛЕНИЕ: Я ТОЛЬКО ДОЛЖЕН ДОБАВИТЬ .get () в конце .execute () и оберните его внутри 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();
}
}