我怎样包括HTTP标头与MediaPlayer的的setDataSource?

人气:1,068 发布:2022-09-10 标签: java android media-player android-mediaplayer

问题描述

我传递的URI setDataSource在MediaPlayer对象的方法。我针对API版本低于14,所以认为我不能使用新的方法,使被列入头。我怎么能有头(具体而言,认证头)与MediaPlayer的请求,并且仍然支持旧的Andr​​oid设备?

我的code是这样的:

  mediaPlayer.setDataSource(URL);
 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
 。媒体播放器prepareAsync();
 

解决方案

背景:

该方法setDataSource(Context的背景下,开放的URI,地图<字符串,字符串>头)已包含在SDK(标记为@hide)在相当长的时间(至少从升级Froyo 2.2.x的,API等级8),检查了改变历史:

API扩展:支持任意指定额外的请求头的地图,指定要发挥媒体数据的URI时

此外,由于冰淇淋三明治4.0.x的已取消隐藏和向公众开放,API级别14:

Unhide MediaPlayer的的setDataSource方法,它采用可选的HTTP标头传递给服务器

解决方法:

此前冰淇淋三明治4.0.x的,API级别14,我们可以使用反射调用这个隐藏API:

 开放的URI = Uri.parse(路径);
地图<字符串,字符串>标题=新的HashMap<字符串,字符串>();
headers.put(键1,值1);
headers.put(KEY2,值2);

mMediaPlayer =新的MediaPlayer();
//使用Java反射调用隐藏API:
方法方法= mMediaPlayer.getClass()实现getMethod(的setDataSource,新的等级[] {Context.class,Uri.class,Map.class})。
method.invoke(mMediaPlayer,新的对象[] {此,URI,头});
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
。mMediaPlayer prepareAsync();

......
 

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

解决方案

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

... ...

555