Android launching music player using intent

Solution 1:

I found one way to do this.

Intent intent = new Intent();  
intent.setAction(android.content.Intent.ACTION_VIEW);  
intent.setDataAndType(Uri.parse(YOUR_SONG_PATH), "audio/*");  
startActivity(intent);

Solution 2:

To simply launch the music player do:

Intent intent = new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER);
startActivity(intent);

Solution 3:

There are number of way by which you can achieve default audio player but those are device and OS specific.

With this code snippet you can get default audio player.

try
    {
    Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
    File file = new File("audiofilepath"); 
    String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
    String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    myIntent.setDataAndType(Uri.fromFile(file),mimetype);
    startActivity(myIntent);
    }
    catch (Exception e) 
    {
         e.printStackTrace();
    }

Solution 4:

This works for older versions and you May get FileUriExposed Exception due to the security Update in the latest Versions. To avoid that use the following code

 try{
        File file = new File(filepath);
        String mimeType = "audio/*";
        Uri fileURI = FileProvider.getUriForFile(
                getApplicationContext(),
                getApplicationContext()
                        .getPackageName() + ".provider", file);
        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(fileURI, mimeType);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
    }catch (Exception e){
        Log.e(TAG,"-------------------------------------------------------FAILED TO PLAY SONG "+e);
    }

Add the Following in AndroidManifest.xml

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
</provider>

Create a file provider_paths.xml under res/xml/

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
    name="external_files"
    path="."/>
</paths>