Android LoaderCallbacks.onLoadFinished with Fragment transaction:这是对的吗?

时间:2015-03-13 14:18:16

标签: android android-fragments loader android-handler

如果我理解正确,有人可以告诉我吗?我有什么似乎工作,但似乎比许多Loader示例更多涉及......我想知道我是否有复杂的事情。我有一个使用多个AsyncTaskLoader的活动。因此,我实现了LoaderCallbacks的内部类,而不是让活动实现LoaderCallback接口。我读到匿名内部类可以泄漏活动,所以我不得不将它创建为一个静态类,其中包含对活动的弱引用。 onLoadFinished需要执行片段事务,所以我需要一个Handler。内部类活动泄漏问题再次出现,因此Handler是一个静态类。此外,我读到可以在Activity暂停时调用handleMessage,因此我需要在Handler中实现pause和resume方法。这真的是必要的吗?

 //here are the relavent bits from my activity
private static class SessionListener implements LoaderManager.LoaderCallbacks<SessionStatus> {
    private final WeakReference<MainActivity> mTarget;

    private SessionListener(MainActivity target) {
        this.mTarget = new WeakReference<>(target);
    }

    @Override
    public Loader<SessionStatus> onCreateLoader(int id, Bundle args) {
        return  new SessionCheckLoader(mTarget.get(), args);
    }

    @Override
    public void onLoadFinished(Loader<SessionStatus> arg0, SessionStatus arg1) {
        MainActivity target = mTarget.get();

        if (arg1 == MainActivity.SessionStatus.CLOSED && target != null) {
            target.mHandler.sendEmptyMessage(MSG_SHOW_CLOSED_DIALOG);
        }
    }

    @Override
    public void onLoaderReset(Loader<SessionStatus> arg0) {


    }
};

//the handler with pause/resume
 private static class HandlerClass extends Handler {
    private final WeakReference<MainActivity> mTarget;

    public HandlerClass(MainActivity context) {
        mTarget = new WeakReference<>(context);
    }
    Stack<Message> s = new Stack<>();
    boolean is_paused = false;

    public synchronized void pause() {
        is_paused = true;
    }

    public synchronized void resume()  {
        is_paused = false;
        while (! s.empty())
        {
            sendMessageAtFrontOfQueue(s.pop());
        }
    }
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (is_paused) {
            s.push(Message.obtain(msg));
            return;
        }
        MainActivity target = mTarget.get();
        if (target != null) {
            if (msg.what == MSG_SHOW_CLOSED_DIALOG) {
                target.sessionDialog();
            }else if (msg.what == MSG_POP_STACK) {
                target.getSupportFragmentManager().popBackStack(null, 0);
            }
        }
    }
}

 private LoaderManager.LoaderCallbacks<SessionStatus> sessionCheckListener = new SessionListener(this);
private HandlerClass mHandler = new HandlerClass(this);

@Override
protected void onPause() {
    super.onPause();
    mHandler.pause();
}

@Override
protected void onPostResume() {
    super.onPostResume();
    mHandler.resume();
}

1 个答案:

答案 0 :(得分:0)

您仍然可以在Activity中实施回调。致电initLoader()时,会为每个Loader提供唯一身份证明。在每个回调中的Loader.getId()语句中使用switch来确定它是Loader