I am passing a URI to the setDataSource method of the MediaPlayer object. I am targeting api version less than 14, so believe that I cannot use the new method that allows headers to be included. How can I include headers (specifically, authentication header) with the MediaPlayer request and still support older Android devices?
My code looks like:
mediaPlayer.setDataSource(url);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync();
The method setDataSource(Context context, Uri uri, Map<String, String> headers) has been included in the SDK (marked as @hide) for quite a long time (at least since Froyo 2.2.x, API Level 8), check out the change history:
API Extension: Support for optionally specifying a map of extra request headers when specifying the uri of media data to be played
And has been unhidden and open to public since Ice Cream Sandwich 4.0.x, API Level 14:
Unhide MediaPlayer's setDataSource method that takes optional http headers to be passed to the server
Prior to Ice Cream Sandwich 4.0.x, API Level 14, we can use reflection call this hide API:
Uri uri = Uri.parse(path);
Map<String, String> headers = new HashMap<String, String>();
headers.put("key1", "value1");
headers.put("key2", "value2");
mMediaPlayer = new MediaPlayer();
// Use java reflection call the hide API:
Method method = mMediaPlayer.getClass().getMethod("setDataSource", new Class[] { Context.class, Uri.class, Map.class });
method.invoke(mMediaPlayer, new Object[] {this, uri, headers});
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepareAsync();
... ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With