【发布时间】:2016-05-12 09:17:38
【问题描述】:
我目前正在制作一个播放现场广播的应用。我在我的 MainActivity 类中创建了一个按钮,它像这样启动播放服务:
Intent intent = new Intent(MainActivity.this, StreamRadio.class);
startService(intent);
这是我的 StreamRadio 类中的代码。
public class StreamRadio extends Service implements MediaPlayer.OnErrorListener {
private static final String TAG = "Information progress";
public MediaPlayer mediaPlayer;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource("http:/xx.xx.xxx.xxx:xxxx/");
Log.d(TAG, "Connected to http:/xx.xx.xxx.xxx:xxxx");
mediaPlayer.prepareAsync();
Log.d(TAG, "Preparing Async");
} catch (IOException e) {
Log.e("TAG", "IOException");
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "Mediaplayer prepared");
mediaPlayer.start();
}
});
Log.d(TAG, "Nearly finished");
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Service is destroyed");
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
}
}
当再次点击MainActivity中的按钮时,服务停止。
服务在点击时启动和销毁。这是 logcat 输出(物理设备):
02-03 09:42:05.719 9318-9318/ D/Information progress: Connected to http:/81.18.165.234:8361
02-03 09:42:05.719 9318-9318/ D/Information progress: Preparing Async
02-03 09:42:05.719 9318-9318/ D/Information progress: Nearly finished
02-03 09:42:05.729 9318-9318/ E/MediaPlayer: Error (1,-1)
在模拟器上出现此错误:
02-03 10:08:26.054 2797-2797/ D/Information progress: Connected to http:/81.18.165.234:8361
02-03 10:08:26.055 2797-2797/ D/Information progress: Preparing Async
02-03 10:08:26.056 2797-2797/ D/Information progress: Nearly finished
02-03 10:08:26.060 2797-2808/ E/MediaPlayer: error (1, -2147483648)
02-03 10:08:26.060 2797-2797/ E/MediaPlayer: Error (1,-2147483648)
所以我想我的问题如下: 为什么 prepareAsync 不能正常工作,因为没有 logcat 消息“Mediaplayer Prepared”,我该如何解决这个问题? 我在清单中授予了应用程序互联网权限。 SO上的其他问题似乎和我的不一样。
提前致谢!
【问题讨论】:
标签: java android service android-mediaplayer audio-streaming