To get the currently playing media on an Android device using the Java Android API, you typically interact with the MediaSessionManager and MediaController APIs. Here’s a concise guide:
Ensure your AndroidManifest.xml includes the necessary permission:
xml<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
Use MediaSessionManager to retrieve active media sessions:
javaMediaSessionManager mediaSessionManager = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE); List<MediaController> controllers = mediaSessionManager.getActiveSessions( new ComponentName(this, NotificationListener.class) );
Note: The
NotificationListener.classmust be a valid component in your app (e.g., aMediaButtonReceiver).
For each MediaController, check the playback state and metadata:
javafor (MediaController controller : controllers) { MediaMetadata metadata = controller.getMetadata(); PlaybackState state = controller.getPlaybackState(); if (state != null && state.getState() == PlaybackState.STATE_PLAYING) { String title = metadata.getString(MediaMetadata.METADATA_KEY_TITLE); String artist = metadata.getString(MediaMetadata.METADATA_KEY_ARTIST); // Use the title, artist, etc. } }
For Android 10 (API 29+) and above, you need to request the MEDIA_CONTENT_CONTROL permission at runtime:
javaif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { requestPermissions(new String[]{Manifest.permission.MEDIA_CONTENT_CONTROL}, REQUEST_CODE); }
If you want to interact with a specific app (e.g., Spotify, YouTube Music), use MediaBrowser to connect to its MediaBrowserService and retrieve the current media.