views:

2313

answers:

5

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 hook into to get realtime notifications.

A: 

Yes i had noticed that Intent and was planning on using it for something else. But the user could decide not to keep the pic so although it would definitely be more efficient. It wouldn't be 100% reliable.

What i need to capture is events of actually writing media to the storage.

That Intent also only solves part of the puzzle. I need to be informed of audio media from the mic also.

Declan Shanaghy
+1  A: 

Aha!

A content observer is what i need!

Here's where i found out about it

Declan Shanaghy
+3  A: 

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.

Reto Meier
A: 

I test this code to detect new media and my receiver does not detect new media. Have you an explanation? Thank you for your help.

A: 

Declan,

did you manage to get some sort of notification or callback whenever "something" writes a file to the SD-card

thanks, Peter