Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include http headers with MediaPlayer setDataSource?

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();
like image 421
Jim Geurts Avatar asked Jan 22 '12 05:01

Jim Geurts


1 Answers

Background:

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

Workaround:

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();

... ...
like image 197
yorkw Avatar answered Nov 15 '22 11:11

yorkw