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