1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.documentsui;
18
19import android.content.AsyncTaskLoader;
20import android.content.Context;
21
22import com.android.documentsui.DocumentsActivity.State;
23import com.android.documentsui.model.RootInfo;
24
25import java.util.Collection;
26
27public class RootsLoader extends AsyncTaskLoader<Collection<RootInfo>> {
28    private final ForceLoadContentObserver mObserver = new ForceLoadContentObserver();
29
30    private final RootsCache mRoots;
31    private final State mState;
32
33    private Collection<RootInfo> mResult;
34
35    public RootsLoader(Context context, RootsCache roots, State state) {
36        super(context);
37        mRoots = roots;
38        mState = state;
39
40        getContext().getContentResolver()
41                .registerContentObserver(RootsCache.sNotificationUri, false, mObserver);
42    }
43
44    @Override
45    public final Collection<RootInfo> loadInBackground() {
46        return mRoots.getMatchingRootsBlocking(mState);
47    }
48
49    @Override
50    public void deliverResult(Collection<RootInfo> result) {
51        if (isReset()) {
52            return;
53        }
54        Collection<RootInfo> oldResult = mResult;
55        mResult = result;
56
57        if (isStarted()) {
58            super.deliverResult(result);
59        }
60    }
61
62    @Override
63    protected void onStartLoading() {
64        if (mResult != null) {
65            deliverResult(mResult);
66        }
67        if (takeContentChanged() || mResult == null) {
68            forceLoad();
69        }
70    }
71
72    @Override
73    protected void onStopLoading() {
74        cancelLoad();
75    }
76
77    @Override
78    protected void onReset() {
79        super.onReset();
80
81        // Ensure the loader is stopped
82        onStopLoading();
83
84        mResult = null;
85
86        getContext().getContentResolver().unregisterContentObserver(mObserver);
87    }
88}
89