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.roots; 18 19import android.content.AsyncTaskLoader; 20import android.content.BroadcastReceiver; 21import android.content.Context; 22import android.content.Intent; 23import android.content.IntentFilter; 24import android.support.v4.content.LocalBroadcastManager; 25 26import com.android.documentsui.base.RootInfo; 27import com.android.documentsui.base.State; 28 29import java.util.Collection; 30 31public class RootsLoader extends AsyncTaskLoader<Collection<RootInfo>> { 32 private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 33 @Override 34 public void onReceive(Context context, Intent intent) { 35 onContentChanged(); 36 } 37 }; 38 39 private final ProvidersCache mProviders; 40 private final State mState; 41 42 private Collection<RootInfo> mResult; 43 44 public RootsLoader(Context context, ProvidersCache providers, State state) { 45 super(context); 46 mProviders = providers; 47 mState = state; 48 49 LocalBroadcastManager.getInstance(context).registerReceiver( 50 mReceiver, new IntentFilter(ProvidersAccess.BROADCAST_ACTION)); 51 } 52 53 @Override 54 public final Collection<RootInfo> loadInBackground() { 55 return mProviders.getMatchingRootsBlocking(mState); 56 } 57 58 @Override 59 public void deliverResult(Collection<RootInfo> result) { 60 if (isReset()) { 61 return; 62 } 63 64 mResult = result; 65 66 if (isStarted()) { 67 super.deliverResult(result); 68 } 69 } 70 71 @Override 72 protected void onStartLoading() { 73 if (mResult != null) { 74 deliverResult(mResult); 75 } 76 if (takeContentChanged() || mResult == null) { 77 forceLoad(); 78 } 79 } 80 81 @Override 82 protected void onStopLoading() { 83 cancelLoad(); 84 } 85 86 @Override 87 protected void onReset() { 88 super.onReset(); 89 90 // Ensure the loader is stopped 91 onStopLoading(); 92 93 mResult = null; 94 95 LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mReceiver); 96 } 97} 98