如何在MediaPlayer setDataSource中包含http标头?

时间:2012-01-22 05:51:21

标签: java android media-player android-mediaplayer

我将URI传递给MediaPlayer对象的setDataSource method。我的目标api版本低于14,所以相信我不能使用允许包含标头的新方法。如何在MediaPlayer请求中包含标题(特别是身份验证标题),并且仍然支持较旧的Android设备?

我的代码如下:

 mediaPlayer.setDataSource(url);
 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
 mediaPlayer.prepareAsync();

1 个答案:

答案 0 :(得分:17)

背景

方法setDataSource(Context context, Uri uri, Map<String, String> headers)已包含在SDK中(标记为@hide)很长一段时间(至少从Froyo 2.2.x开始,API级别8),请查看更改历史记录:

API Extension: Support for optionally specifying a map of extra request headers when specifying the uri of media data to be played

自冰淇淋三明治4.0.x,API等级14:

以来一直未被隐藏并向公众开放

Unhide MediaPlayer's setDataSource method that takes optional http headers to be passed to the server

解决方法:

在Ice Cream Sandwich 4.0.x,API Level 14之前,我们可以使用反射调用这个隐藏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();

... ...