Wednesday, August 31, 2011

Android: How to start MusicPlayer without specifying any music file

Recently I needed to launch standard MusicPlayer from withing my app but without specifying any media file. The requirement was to show the MusicPlayer but not to play anything by default. User can then browse their music file and play any music they want, just as they would do if they launched the music player from home screen.

There are many resources on the web which discuss how to play media using media player. To do this you simply create an intent and add the media files URI to it as data and set the action to Intent.ACTION_VIEW. This will launch the player and play the specified media file. But if you skip adding media file to the intent, Android complains that no app can handle this intent.

So to open the player without media file, I looked at the code of Music Widget in Android source. The intent being used there to launch the player is created as follows
intent = new Intent(context, MusicBrowserActivity.class);
But this doesn't work if I use it as it is because this class, MusicBrowserActivity, can not be resolved. I know that the package for this class is but I cant import this package. After trying a lot of things, I was finally able to do this using the following code.
intent = new Intent();
ComponentName comp = new ComponentName("", "");
Hope this helps.