AsyncTask已经完成了

时间:2017-10-22 14:21:00

标签: java android android-asynctask

如何捕捉AsyncTask完成时的瞬间? 我有一个ProfileUpdate类,它扩展了AsyncTask,从另一个活动我调用这个方法,然后我需要更新我的数据。怎么知道asynctask完成了? 我的asynctask方法在另一个类而不是活动类!!!

这是我在活动中的onRefresh方法:

@Override
public void onRefresh() {
    if (!AlertView.isInternetAvailable(getContext())) {
        swipeLayout.setRefreshing(false);
        Toast.makeText(getContext(), Messages.CONNECTION_ERROR + ": " + Messages.NO_INTERNET, Toast.LENGTH_SHORT).show();
    } else {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new UpdateProfile(getActivity(), swipeLayout, sharedPreferences.getString(Constants.TOKEN, ""), user.getIin()).execute(Urls.GET_USER);
            }
        });
        profileDefaults();
    }
}

这里是我的AsyncTask方法:

public class UpdateProfile extends AsyncTask <String, Void, String> {
private Activity activity;
private SwipeRefreshLayout swipeRefreshLayout;
private String token;
private String userIin;
private SharedPreferences sharedPreferences;

public UpdateProfile(Activity activity, SwipeRefreshLayout swipeRefreshLayout, String token, String userIin) {
    this.activity = activity;
    this.swipeRefreshLayout = swipeRefreshLayout;
    this.token = token;
    this.userIin = userIin;
    sharedPreferences = this.activity.getSharedPreferences(Constants.PROJECT, Context.MODE_PRIVATE);
}

@Override
protected String doInBackground(String... params) {
    URL url = null;
    try {
        url = new URL(params[0]);
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            RequestBody body = new FormBody.Builder()
                    .add("iin", userIin)
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .addHeader(Constants.AUTH_TOKEN, token)
                    .post(body)
                    .build();
            Response responses = null;
            try {
                responses = okHttpClient.newCall(request).execute();
            } catch (Exception e) {
                AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
            }

            assert responses != null;
            return responses.body().string();

        } catch (Exception e) {
            AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
        }
    } catch (Exception e) {
        AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
    }
    return null;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    try {
        JSONObject jsonObject = new JSONObject(s);
        int code = Integer.valueOf(jsonObject.getString(Constants.CODE));
        if (code == Codes.OK) {
            Toast.makeText(activity, "Данные обновлены", Toast.LENGTH_SHORT).show();

            String userHeader = jsonObject.getString("user");
            JSONObject userInfo = new JSONObject(userHeader);

            String mobilePhone = userInfo.getString(SingletonConstants.MOBILE_PHONE);
            Boolean isActive = userInfo.getBoolean(SingletonConstants.IS_ACTIVE);
            Boolean signedAgreement = userInfo.getBoolean(SingletonConstants.SIGNED_AGREEMENT);
            Boolean esfEntered = userInfo.getBoolean(SingletonConstants.ESF_ENTERED);
            String address = userInfo.getString(SingletonConstants.ADDRESS);
            String iin = userInfo.getString(SingletonConstants.IIN);
            String certExpDate = userInfo.getString(SingletonConstants.CERT_EXP_DATE);
            String firstName = userInfo.getString(SingletonConstants.FIRST_NAME);
            String middleName = userInfo.getString(SingletonConstants.MIDDLE_NAME);
            String workPhone = userInfo.getString(SingletonConstants.WORK_PHONE);
            String secondName = userInfo.getString(SingletonConstants.SECOND_NAME);
            String avatarUrl = userInfo.getString(SingletonConstants.AVATAR_URL);;
            String secondEmail = userInfo.getString(SingletonConstants.SECOND_EMAIL);
            String email = userInfo.getString(SingletonConstants.EMAIL);

            User newUser = new User(mobilePhone, isActive, signedAgreement, esfEntered, address, iin, certExpDate, firstName, middleName, workPhone, secondName, avatarUrl, secondEmail, email);

            Gson gson = new Gson ();
            String userGson = gson.toJson (newUser);
            sharedPreferences.edit().putString(SingletonConstants.USER, userGson).apply();
            swipeRefreshLayout.setRefreshing(false);

        } else {
            AlertView.showAlertView(activity, Messages.ERROR, jsonObject.getString(Constants.MESSAGE), Messages.OK);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

如何调用profileDefaults()?这是我的活动。我需要在onPostExecute之后调用它!

1 个答案:

答案 0 :(得分:1)

更简洁的方法是使用接口作为侦听器。 创建此界面:

public interface OnAsyncFinished{
    void onAsyncFinished(Object o);
}

在AsyncTaskClass构造函数中将接口添加为参数:

private OnAsyncFinished onAsyncFinished;
public UpdateProfile(..., OnAsyncFinished onAsyncFinished) {
   ...
   this.onAsyncFinished = onAsyncFinished;
}
...
@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    onAsyncFinished.onAsyncFinished(s); //This will notifiy the method on main activity, and you can now resume the work there
    ...
}

在主要活动中实施界面:

public MainActivity extends Activity implements OnAsyncFinished {
     @Override
     public void onAsyncFinished(Object o) {
         //This will get called after onPostExecute, do what u want with the object you got from onPostExecute, json or string in ur example
         profileDefaults(); //call ur function
     }
}

修改 在主要活动中创建异步任务时,在构造函数Likeo中传递this

        @Override
        public void run() {
            new UpdateProfile(..., this).execute(Urls.GET_USER);
        }