1 /* 2 * Copyright (C) 2017 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 package com.android.documentsui.inspector; 17 18 import android.content.ContentResolver; 19 import android.content.Context; 20 import android.net.Uri; 21 import android.os.Bundle; 22 import android.provider.DocumentsContract; 23 import android.util.Log; 24 25 import androidx.annotation.Nullable; 26 import androidx.loader.content.AsyncTaskLoader; 27 28 import java.io.FileNotFoundException; 29 30 /** 31 * Loads metadata from 32 * {@link DocumentsContract#getDocumentMetadata(android.content.ContentProviderClient, 33 * Uri)} 34 */ 35 final class MetadataLoader extends AsyncTaskLoader<Bundle> { 36 37 private static final String TAG = "MetadataLoader"; 38 39 private final Uri mUri; 40 private final ContentResolver mContentResolver; 41 42 private @Nullable Bundle mMetadata; 43 MetadataLoader(Context context, Uri uri, ContentResolver contentResolver)44 MetadataLoader(Context context, Uri uri, ContentResolver contentResolver) { 45 super(context); 46 mUri = uri; 47 mContentResolver = contentResolver; 48 } 49 50 @Override loadInBackground()51 public Bundle loadInBackground() { 52 try { 53 return DocumentsContract.getDocumentMetadata(mContentResolver, mUri); 54 } catch (FileNotFoundException | RuntimeException e) { 55 Log.e(TAG, "Failed to load metadata for doc: " + mUri, e); 56 } 57 58 return null; 59 } 60 61 @Override onStartLoading()62 protected void onStartLoading() { 63 if (mMetadata != null) { 64 deliverResult(mMetadata); 65 } 66 if (takeContentChanged() || mMetadata == null) { 67 forceLoad(); 68 } 69 } 70 71 @Override deliverResult(Bundle metadata)72 public void deliverResult(Bundle metadata) { 73 if (isReset()) { 74 return; 75 } 76 mMetadata = metadata; 77 if (isStarted()) { 78 super.deliverResult(metadata); 79 } 80 } 81 82 /** 83 * Must be called from the UI thread 84 */ 85 @Override onStopLoading()86 protected void onStopLoading() { 87 // Attempt to cancel the current load task if possible. 88 cancelLoad(); 89 } 90 91 @Override onReset()92 protected void onReset() { 93 super.onReset(); 94 95 // Ensure the loader is stopped 96 onStopLoading(); 97 98 mMetadata = null; 99 } 100 } 101