Macarse
Macarse

Reputation: 93173

Adding mp3 to the ContentResolver

I know that after downloading an mp3 from your app you need to add it to the ContentResolver to see it on the music player. I am doing it with the following code:

    private void addFileToContentProvider() {
        ContentValues values = new ContentValues(7);

        values.put(Media.DISPLAY_NAME, "display_name");
        values.put(Media.ARTIST, "artist");
        values.put(Media.ALBUM, "album");
        values.put(Media.TITLE, "Title"); 
        values.put(Media.MIME_TYPE, "audio/mp3"); 
        values.put(Media.IS_MUSIC, true);
        values.put(Media.DATA, pathToFile);

        context.getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values); 

    }

My issue is that I am willing to avoid setting DISPLAY_NAME, ARTIST, ALBUM, TITLE by hand.

Is there a way to tell Android to do it from the file? I've already used just values.put(Media.DATA, pathToFile); but it's not adding it to the player.

Is there a way to force the thread that scans the sd for music?

Upvotes: 3

Views: 3218

Answers (1)

magicman
magicman

Reputation: 1199

First try adding this:

values.put(MediaStore.Audio.Media.IS_MUSIC, true);

Then try this:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));

If that doesn't work, try this:

public MediaScannerConnection mScanner = null;

public void reScan(String filename){
    final String name = filename;
    mScanner = new MediaScannerConnection(THE_NAME_OF_YOUR_ACTIVITY.this, new MediaScannerConnection.MediaScannerConnectionClient() {
        public void onMediaScannerConnected() { 
            mScanner.scanFile(name, null); 
        } 
        public void onScanCompleted(String path, Uri uri) {
            if (path.equals(name)) {
                mScanner.disconnect(); 
            } 
        }
    }); 
    mScanner.connect(); 
}

After adding an mp3, just call this method which takes the file name as the input.

And make sure to replace THE_NAME_OF_YOUR_ACTIVITY with the name of your activity.

Upvotes: 6

Related Questions