我试图在我的应用程序中播放音乐,当媒体播放器加载时,我希望允许用户继续使用该应用程序,但每次我开始加载媒体播放器时,应用程序都会卡住几秒钟,当媒体播放器加载完成后,应用程序才会恢复正常并重新开始工作,有时它不仅仅是卡住,它还会显示操作系统的弹出菜单,提示用户退出应用程序。
我在 Google 或 YouTube 中找不到任何解决方案,有人知道我的代码出了什么问题吗?
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
String STREAM_URL = #####; // here i put the URL of the song
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(STREAM_URL);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
} catch (NullPointerException e) {
Log.d(TAG, "run: NullPointerException = " + e.getMessage());
FirebaseCrash.log("Tag = " + TAG + "run: NullPointerException = " + e.getMessage());
}
}
}
};
handler.post(runnable);
最佳答案
即使您正在创建 Handler
,MediaPlayer
的创建仍然发生在主 UI 线程上。您应该调用 prepareAsync
或使用 AsyncTask
或其他一些方法来避免在主线程上调用 prepare
。
When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it
如果您从网络流式传输音乐,准备播放媒体尤其需要一段时间。一种选择可能是调用 prepareAsync
而不是调用 prepare
。在这种情况下,您应该设置 OnPreparedListener
,并在该回调中调用 start
。
关于java - 如何正确使用mediaPlayer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46239006/