For my iAndroidRemote project, I had to find the currently playing song/track in Android phone and the ability to change to next/previous song/track.
After some digging, I found that there is no documented way to do it. It depends on an undocumented way which may not work well in all Android phones.
I found an undocumented way which works for HTC phones and some other stock Android phones that are using the default music player.
I thought of sharing the code here, so that it would be useful for others and also I would know where to look for it when I need it for the next time.
Copying the aidl files
Any Android app, can play music by using the
com.android.music.MediaPlaybackService class. In order to find the currently playing song, we need to create a Service which will interact with this class
In order to do that, we need to copy the
IMediaPlaybackService.aidl file from the source code of the default music app. For HTC phones we need to copy the
IMediaPlaybackService.aidl file inside the
com.htc.music package and for other Android phones we have to copy it from the
Create the following packages to your android project.
Creating the ServiceConnection class
The next step is to create the
ServiceConnection class which will allow us to interact with the
Copy the following code and create the
MediaPlayerServiceConnection inside your activity as an inner class.
We are using the boolean
isHtc to determine if we are on an HTC phone. We would be using this flag before invoking the methods on the
Getting the current song
Now we can call the
getTrackName() method on the corresponding object and we can get the track information.
Playing next song
To play the next song in the track we have to just call the
next() method on the corresponding object
Playing Previous song
To play the previous song in the album we have to just call the
prev() method on the correct object
I have created a small sample project to show the entire flow in action. You can download the project from my Github page.
- Recovering Android KeyStore password
- Using WebSockets with Android to control Arduino robots
- 10 more open source Android apps which every developer must look into
- Building Robots using Android and Arduino in Google Devfestx
- Transferring data from Android using Audio
- Building Robots using Arduino and Android at DroidCon