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:
And has been unhidden and open to public since Ice Cream Sandwich 4.0.x, API Level 14:
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();
... ...