Android: Listen for the Audio file deleted

1.2k views Asked by At

I'm using android MediaStore to get the list of audio files on my music app and these files can be added to playlist. If the file gets deleted from the device memory, the file information need to be deleted from playlist.

Is there any listener/receiver to listen when the audio files are deleted from the device internal/external memory?

I know we can use FileObserver for any file change. But this required a background service to always run and listen for the file changed. I want to avoid having a service for this. Is there any other way?

2

There are 2 answers

1
Eric Maxi On

Try registering ContentObserver with context.getContentResolver.registerContentObserver(args). I do this in onResume(). get current number of tracks in device memory. I do this in onCreate(). also get current number of tracks in the onchanged method of the ContentObserver in onResume(). If the figures don't match, refresh your current list. You can also register your ContentObserver in service for consistent results. Also don't forget to unregister ContentObserver in onPause() and onDestroy() using context.getContentResolver.unregisterContentObserver(args). works like charm. I will post the code once I retrieve it. Happy coding!

0
uptoNoGood On

You can register a BroadcastReceiver for MediaScanner events, and refresh your list whenever you receive Intent.ACTION_MEDIA_SCANNER_FINISHED intent.

IntentFilter scanFileReceiverFilter= new IntentFilter();
scanFileReceiverFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
scanFileReceiverFilter.addDataScheme("file");

BroadcastReceiver scanFileReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            if(intent.getAction().equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
                Uri uri = intent.getData();
                String path = null;
                if (uri != null) {
                    path = uri.getPath();
                }
                //TODO:refresh list in path

            }
        }
    };
getActivity().registerReceiver(scanFileReceiver, scanFileReceiverFilter);

Any app which is deleting local data is expected to run Media scanner after changes, to sync the media DB, so you should receive this.

But this works only while your application is running. For background deleting, you should register one in manifest.

If you are using DB to store playlists entries, then this will be efficient as you can check all files with path LIKE path received for refreshing.

Please note that sometimes this event might be received late due to huge amount of content present in device.

You can also use ContentObserver calling registerContentObserver with uri MediaStore.Audio.Media.getContentUri("external"). Since all Media Providers have Audio view, this should work efficiently.