【问题标题】:Android async callback. When exit from UI app crashesAndroid 异步回调。当退出 UI 应用程序崩溃时
【发布时间】:2016-02-10 09:19:56
【问题描述】:

我有一个带有 RecyclerView 的片段,在 RecyclerView 上我有带有 Button 的自定义项,点击时我发送带有回调的请求。 我在后端服务器上为 API 使用 retrofit2 库。

当我发送请求并从 UI 退出时出现问题,当然应用程序崩溃,因为在执行此请求后我更新 UI,并且此 UI 不存在。

我该如何解决这个问题?

我看到了两种方法,在我看来,destoy 方法尝试停止请求,或者在执行后检查 UI 是否不存在。

什么会更好?

如果是第一种方法,我该怎么做?

请求示例:

private void getStoreStatus() {
    Retrofit restAdapter = new Retrofit.Builder().baseUrl(APIURL).addConverterFactory(GsonConverterFactory.create()).build();

    mRestApi = restAdapter.create(IHansaAPI.class);

    mRestApi.getStatusStore(mStoreId).enqueue(new Callback<HansaCrawlerResponse>() {

        @Override
        public void onResponse(Response<HansaCrawlerResponse> response) {
            Log.d(LOG_TAG, response.body().getResponse().getMessage() + " " + response.body().getResponse().getCode() + " " + mCurrentStore.getId());

            switch (response.body().getResponse().getMessage()) {

                case NOT_FOUND:
                    mCurrentStore.setmStatusRegistration(0);
                    setmCurrentStatus(0, mCurrentStore.getIsClosed());
                    break;
                case IN_BASE:
                    mCurrentStore.setmStatusRegistration(2);
                    setmCurrentStatus(2, mCurrentStore.getIsClosed());
                    break;
                case PROCESSIND:
                    mCurrentStore.setmStatusRegistration(1);
                    setmCurrentStatus(1, mCurrentStore.getIsClosed());
                    break;
                default:
                    mCurrentStore.setmStatusRegistration(-1);
                    setmCurrentStatus(-1, mCurrentStore.getIsClosed());
                    break;
            }
        }

        @Override
        public void onFailure(Throwable t) {
            Log.d(LOG_TAG, "Error get Status");
        }
    });
}

对不起我的英语:(

【问题讨论】:

标签: android android-asynctask callback retrofit


【解决方案1】:

不要从后台线程更新 UI,只检查 Activity 是否没有完成更新 UI。

runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (!isFinishing()) {

            /*Update Your UI here. this way you can check if your Activity is live than can update UI. cancel network request in onDestroy will also help. */

      }
        }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    相关资源
    最近更新 更多