• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 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 android.media;
18 
19 import android.compat.annotation.UnsupportedAppUsage;
20 import android.content.ComponentName;
21 import android.content.ContentProviderClient;
22 import android.content.ContentResolver;
23 import android.content.Context;
24 import android.content.ServiceConnection;
25 import android.net.Uri;
26 import android.os.Build;
27 import android.os.IBinder;
28 import android.provider.MediaStore;
29 import android.util.Log;
30 
31 import com.android.internal.os.BackgroundThread;
32 
33 import java.io.File;
34 
35 /**
36  * MediaScannerConnection provides a way for applications to pass a
37  * newly created or downloaded media file to the media scanner service.
38  * The media scanner service will read metadata from the file and add
39  * the file to the media content provider.
40  * The MediaScannerConnectionClient provides an interface for the
41  * media scanner service to return the Uri for a newly scanned file
42  * to the client of the MediaScannerConnection class.
43  */
44 public class MediaScannerConnection implements ServiceConnection {
45     private static final String TAG = "MediaScannerConnection";
46 
47     private final Context mContext;
48     private final MediaScannerConnectionClient mClient;
49 
50     private ContentProviderClient mProvider;
51 
52     @Deprecated
53     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.O)
54     private IMediaScannerService mService;
55     @Deprecated
56     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.O)
57     private boolean mConnected;
58     @Deprecated
59     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.O)
60     private final IMediaScannerListener.Stub mListener = new IMediaScannerListener.Stub() {
61         @Override
62         public void scanCompleted(String path, Uri uri) {
63         }
64     };
65 
66     /**
67      * Interface for notifying clients of the result of scanning a
68      * requested media file.
69      */
70     public interface OnScanCompletedListener {
71         /**
72          * Called to notify the client when the media scanner has finished
73          * scanning a file.
74          * @param path the path to the file that has been scanned.
75          * @param uri the Uri for the file if the scanning operation succeeded
76          * and the file was added to the media database, or null if scanning failed.
77          */
onScanCompleted(String path, Uri uri)78         public void onScanCompleted(String path, Uri uri);
79     }
80 
81     /**
82      * An interface for notifying clients of MediaScannerConnection
83      * when a connection to the MediaScanner service has been established
84      * and when the scanning of a file has completed.
85      */
86     public interface MediaScannerConnectionClient extends OnScanCompletedListener {
87         /**
88          * Called to notify the client when a connection to the
89          * MediaScanner service has been established.
90          */
onMediaScannerConnected()91         public void onMediaScannerConnected();
92     }
93 
94     /**
95      * Constructs a new MediaScannerConnection object.
96      * @param context the Context object, required for establishing a connection to
97      * the media scanner service.
98      * @param client an optional object implementing the MediaScannerConnectionClient
99      * interface, for receiving notifications from the media scanner.
100      */
MediaScannerConnection(Context context, MediaScannerConnectionClient client)101     public MediaScannerConnection(Context context, MediaScannerConnectionClient client) {
102         mContext = context;
103         mClient = client;
104     }
105 
106     /**
107      * Initiates a connection to the media scanner service.
108      * {@link MediaScannerConnectionClient#onMediaScannerConnected()}
109      * will be called when the connection is established.
110      */
connect()111     public void connect() {
112         synchronized (this) {
113             if (mProvider == null) {
114                 mProvider = mContext.getContentResolver()
115                         .acquireContentProviderClient(MediaStore.AUTHORITY);
116                 if (mClient != null) {
117                     mClient.onMediaScannerConnected();
118                 }
119             }
120         }
121     }
122 
123     /**
124      * Releases the connection to the media scanner service.
125      */
disconnect()126     public void disconnect() {
127         synchronized (this) {
128             if (mProvider != null) {
129                 mProvider.close();
130                 mProvider = null;
131             }
132         }
133     }
134 
135     /**
136      * Returns whether we are connected to the media scanner service
137      * @return true if we are connected, false otherwise
138      */
isConnected()139     public synchronized boolean isConnected() {
140         return (mProvider != null);
141     }
142 
143     /**
144      * Requests the media scanner to scan a file.
145      * Success or failure of the scanning operation cannot be determined until
146      * {@link MediaScannerConnectionClient#onScanCompleted(String, Uri)} is called.
147      *
148      * @param path the path to the file to be scanned.
149      * @param mimeType  an optional mimeType for the file.
150      * If mimeType is null, then the mimeType will be inferred from the file extension.
151      */
scanFile(String path, String mimeType)152      public void scanFile(String path, String mimeType) {
153         synchronized (this) {
154             if (mProvider == null) {
155                 throw new IllegalStateException("not connected to MediaScannerService");
156             }
157             BackgroundThread.getExecutor().execute(() -> {
158                 final Uri uri = scanFileQuietly(mProvider, new File(path));
159                 runCallBack(mContext, mClient, path, uri);
160             });
161         }
162     }
163 
164     /**
165      * Convenience for constructing a {@link MediaScannerConnection}, calling
166      * {@link #connect} on it, and calling {@link #scanFile(String, String)} with the given
167      * <var>path</var> and <var>mimeType</var> when the connection is
168      * established.
169      * @param context The caller's Context, required for establishing a connection to
170      * the media scanner service.
171      * Success or failure of the scanning operation cannot be determined until
172      * {@link MediaScannerConnectionClient#onScanCompleted(String, Uri)} is called.
173      * @param paths Array of paths to be scanned.
174      * @param mimeTypes Optional array of MIME types for each path.
175      * If mimeType is null, then the mimeType will be inferred from the file extension.
176      * @param callback Optional callback through which you can receive the
177      * scanned URI and MIME type; If null, the file will be scanned but
178      * you will not get a result back.
179      * @see #scanFile(String, String)
180      */
scanFile(Context context, String[] paths, String[] mimeTypes, OnScanCompletedListener callback)181     public static void scanFile(Context context, String[] paths, String[] mimeTypes,
182             OnScanCompletedListener callback) {
183         BackgroundThread.getExecutor().execute(() -> {
184             try (ContentProviderClient client = context.getContentResolver()
185                     .acquireContentProviderClient(MediaStore.AUTHORITY)) {
186                 for (String path : paths) {
187                     final Uri uri = scanFileQuietly(client, new File(path));
188                     runCallBack(context, callback, path, uri);
189                 }
190             }
191         });
192     }
193 
scanFileQuietly(ContentProviderClient client, File file)194     private static Uri scanFileQuietly(ContentProviderClient client, File file) {
195         Uri uri = null;
196         try {
197             uri = MediaStore.scanFile(ContentResolver.wrap(client), file.getCanonicalFile());
198             Log.d(TAG, "Scanned " + file + " to " + uri);
199         } catch (Exception e) {
200             Log.w(TAG, "Failed to scan " + file + ": " + e);
201         }
202         return uri;
203     }
204 
runCallBack(Context context, OnScanCompletedListener callback, String path, Uri uri)205     private static void runCallBack(Context context, OnScanCompletedListener callback,
206             String path, Uri uri) {
207         if (callback != null) {
208             // Ignore exceptions from callback to avoid calling app from crashing.
209             // Don't ignore exceptions for apps targeting 'R' or higher.
210             try {
211                 callback.onScanCompleted(path, uri);
212             } catch (Throwable e) {
213                 if (context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.R) {
214                     throw e;
215                 } else {
216                     Log.w(TAG, "Ignoring exception from callback for backward compatibility", e);
217                 }
218             }
219         }
220     }
221 
222     @Deprecated
223     static class ClientProxy implements MediaScannerConnectionClient {
224         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.O)
225         final String[] mPaths;
226         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.O)
227         final String[] mMimeTypes;
228         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.O)
229         final OnScanCompletedListener mClient;
230         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.O)
231         MediaScannerConnection mConnection;
232         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.O)
233         int mNextPath;
234 
235         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.O)
ClientProxy(String[] paths, String[] mimeTypes, OnScanCompletedListener client)236         ClientProxy(String[] paths, String[] mimeTypes, OnScanCompletedListener client) {
237             mPaths = paths;
238             mMimeTypes = mimeTypes;
239             mClient = client;
240         }
241 
242         @Override
onMediaScannerConnected()243         public void onMediaScannerConnected() {
244         }
245 
246         @Override
onScanCompleted(String path, Uri uri)247         public void onScanCompleted(String path, Uri uri) {
248         }
249 
250         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.O)
scanNextPath()251         void scanNextPath() {
252         }
253     }
254 
255     /**
256      * Part of the ServiceConnection interface.  Do not call.
257      */
258     @Override
onServiceConnected(ComponentName className, IBinder service)259     public void onServiceConnected(ComponentName className, IBinder service) {
260         // No longer needed
261     }
262 
263     /**
264      * Part of the ServiceConnection interface.  Do not call.
265      */
266     @Override
onServiceDisconnected(ComponentName className)267     public void onServiceDisconnected(ComponentName className) {
268         // No longer needed
269     }
270 }
271