09-06 20:13:48.298: E/AndroidRuntime(11463): FATAL EXCEPTION: Thread-11
09-06 20:13:48.298: E/AndroidRuntime(11463): java.lang.IllegalStateException
09-06 20:13:48.298: E/AndroidRuntime(11463): at android.media.MediaPlayer.getCurrentPosition(Native Method)
09-06 20:13:48.298: E/AndroidRuntime(11463): at com.leranxinsheng.activity.MusicService.run(MusicService.java:236)
09-06 20:13:48.298: E/AndroidRuntime(11463): at java.lang.Thread.run(Thread.java:1019)
当从播放的界面跳到其他界面的时候,总是爆出MediaPlayer.getCurrentPosition IllegalStateException的错误。后来想了一下,是因为播放器所在的Activity已经进入OnStop状态,再让后台调整音乐进度条的服务获取进度条(MediaPlayer.getCurrentPosition)肯定不合法。
原代码如下
1 public void run() { 2 // TODO Auto-generated method stub 3 while (isRun) { 4 try { 5 Thread.sleep(200); 6 } catch (InterruptedException e) { 7 // TODO Auto-generated catch block 8 e.printStackTrace(); 9 } 10 //这段是增加判断后的代码/ 11 if (null != player) { 12 if (!player.isPlaying()) {//如果不在播放状态,则停止更新
//播放器进度条,防止界面报错 13 Log.d(strTag, "播放器停止播放,跳过获取位置"); 14 break; 15 } 16 /// 17 int position = player.getCurrentPosition(); 18 int total = player.getDuration(); 19 Intent intent = new Intent("com.leranxinsheng.progress"); 20 intent.putExtra("position", position); 21 intent.putExtra("total", total); 22 sendBroadcast(intent); 23 } 24 25 if (null != player) { 26 if (player.isPlaying()) { 27 playing = true; 28 } else { 29 Log.d(strTag, "播放器停止播放,跳过第一个if"); 30 playing = false; 31 } 32 } 33 } 34 }