Is there any elegant way in the Android API for detecting new media when it is written to the device? I’m mainly interested in photos taken by the camera, video taken by the camera and audio recorded from the mic.
My current thinking is to periodically scan each media content provider and filter based on last scan time.
I’m just wondering if there is some service I can get realtime notifications.
There's a special broadcast Intent that should get called every time an application writes anything new to the Media Store:
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE
The Broadcast Intent includes the path to the new file, accessible through the Intent.getDataString()
method.
To listen for it, just create a BroadcastReceiver
and register it using an IntentFilter
as shown below:
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String newFileURL = intent.getDataString();
// TODO React to new Media here.
}
}, new IntentFilter(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
This will only work for files being inserted into one of the Media Store Content Providers. Also, it depends on the application that's putting it there broadcasting the intent, which all the native (Google) application do.
来源:https://stackoverflow.com/questions/230643/android-api-for-detecting-new-media-from-inbuilt-camera-mic