正确处理从异步任务片段相互作用 [英] Correctly handling fragment interactions from an Async-Task

查看:228
本文介绍了正确处理从异步任务片段相互作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修改我的片段重code。与安全的异步任务,我注意到一些偶然崩溃。现在我我注意到我的主要问题是从异步任务本身内部访问活动或片段变量的一些搜索后我稍微好一点的教育。

I am trying to refactor my fragment-heavy code with safer async tasks as I had noticed some occasional crashes. Now I am slightly better educated after some searches I've noticed my main problem is accessing activity or fragment variables from within the async task itself.

我把每个异步任务为单类,实现接口回调到称他们的片段或活动。例如:

I am separating each async task into single classes, which implement interface callbacks to the fragment or activity which called them. For example:

public class LoginFragment extends Fragment implements RequestForgotPassword {

...
//On Forgot Password click
new AsyncForgotPassword(LoginFragment.this, mEmail).execute();
...

@Override
public void onForgotPasswordResult(Result result)
{
    if(isAdded())
    {
        if (result == Result.SUCCESS)
            Toast.makeText(getActivity(), "An email has been sent to your account to assist in recovering your password", Toast.LENGTH_LONG).show();
        else
            Toast.makeText(getActivity(), "We don't have any record of that registered email, sorry! Please try again", Toast.LENGTH_LONG).show();
    }
}

...

}

OnTaskCompleted.java

OnTaskCompleted.java

public interface OnTaskCompleted {
    enum Result{SUCCESS, FAILURE};
}

RequestForgotPassword.java

RequestForgotPassword.java

public interface RequestForgotPassword extends OnTaskCompleted {
    void onForgotPasswordResult(Result result);
}

AsyncForgotPassword.java

AsyncForgotPassword.java

public class AsyncForgotPassword extends AsyncTask<Void, Void, JSONObject> {

    private RequestForgotPassword mRequest;
    private String mEmail;

    public AsyncForgotPassword(RequestForgotPassword request, String email)
    {
        mRequest = request;
        mEmail = email;
    }

    @Override
    protected JSONObject doInBackground(Void... params) {
        ServerFunctions serverFunctions = new ServerFunctions();
        return serverFunctions.forgotPassword(mEmail);
    }

    @Override
    protected void onPostExecute(JSONObject obj) {
        try {
            JSONObject json1 = obj.getJSONObject("response");
            if (json1.getString("success").matches("1")) {
                mRequest.onForgotPasswordResult(OnTaskCompleted.Result.SUCCESS);
            } else {
                mRequest.onForgotPasswordResult(OnTaskCompleted.Result.FAILURE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

所以基本上我认为这将是很好的,如果大多数异步任务会被写成这样。许多将有进展的对话和可能会长时间运行,或设有呼叫片段等有意义的互动,我已经遇到了一些非常有趣的讨论<一个href=\"http://stackoverflow.com/questions/3357477/is-asynctask-really-conceptually-flawed-or-am-i-just-missing-something?rq=1\">here, <一href=\"http://stackoverflow.com/questions/9963691/android-asynctask-sending-callbacks-to-ui\">here, <一href=\"http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a\">here和<一个href=\"http://stackoverflow.com/questions/11631408/android-fragment-getactivity-sometime-returns-null\">here这些都导致了我处理这个设置。

So basically I think it would be good if most async tasks will be written like this. Many will feature progress dialogs and could be long running, or feature meaningful interactions with the calling fragment etc. and I've come across some very interesting discussions here, here, here and here which have led me to approach this set-up.

我在第一个链接的答复(书面方式早在2010年),戴安娜的code的理解是,它保证了活动永远不会为空从异步任务访问时。我的应用程序只有一对夫妇的活动,和许多片段,我真的不能看到这种方法会为今天很好地工作。我不得不换用碎片任务异步等在过去的问题,并希望确保我不会得到任何更多的空的上下文相关的问题。

My understanding of Dianne's code in that first link's answer (written way back in 2010) was that it ensures the activity will never be null when accessed from an async task. My app has only a couple of activities and many fragments so I can't really see how this approach would work as nicely today. I have had problems swapping fragments with async tasks etc. in the past and want to make sure that I won't get any more null Context related problems.

所以,如果我检查 isAdded()异步任务已经完成后,就是一个片段中 getActivity()保证是非空?我应该叫executePendingTransactions()<一href=\"http://stackoverflow.com/questions/22485899/fragment-isadded-returns-false-on-an-already-added-fragment\">just事先的每次只是为了确保?这是所有矫枉过正?

So if I check isAdded() within a fragment after an async task has complete, is getActivity() guaranteed to be non-null? Should I call executePendingTransactions() just beforehand everytime just to make sure? Is this all overkill?

三江源的任何反馈!

推荐答案

从DOC:

public final boolean isAdded ()

Return true if the fragment is currently added to its activity.

所以活动可能不能为空。

So the activity could not be null.

编辑:

要实现长期运行的任务,我建议你使用的 IntentService (如果任务做复杂的本地操作,否则的AsyncTask是确定),保存数据的 DB (或在其它形式的,例如,在共享preferences如果它是信息的一个小块)和使用的 LocalBroadcast 传播的逻辑。你也可以管理检查的onCreate()片段的回调,所以如果它被分离时的任务到期,它可以检索数据持久化和妥善管理他们。在这之后,你可以pviously刷新数据存储$ P $。

To achieve a long running task I recommend you to use an IntentService (if the task do complex local operations, otherwise an AsyncTask is ok), save data in DB (or in other forms, for example in SharedPreferences if it is a small chunk of informations) and propagate the logic using a LocalBroadcast. You could also manage a check in onCreate() callback of the fragment so if it was detached when the task was expired, it could retrieve the data persisted and manage them properly; after that, you could flush the data stored previously.

这篇关于正确处理从异步任务片段相互作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆