我有一个音频文件播放在前台服务使用MediaPlayer.当用户点击与前台服务相关联的通知时,我使用Intent启动一个Activity,如下所示:
Intent audioPlayIntent = new Intent(context,AudioPlayActivity.class); audioPlayIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); audioPlayIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent contentIntent = PendingIntent.getActivity(context,audioPlayIntent,0);
然后,此活动将绑定到服务以向用户显示MediaController.
以下是服务中的绑定代码:
public class AudioPlayerServiceBinder extends Binder{ public AudioPlayerService getAudioService(){ return AudioPlayerService.this; //this class is declared in AudioPlayerService.java,so it has access to the Service instance. } }
..和在Activity的onStart中我有一个调用这个方法:
private void bindAudioService() { Intent i = new Intent(this,AudioPlayerService.class); serviceConnection = new AudioServiceConnection(); bindService(i,serviceConnection,0); }
我在mediaController.show(5000)行下面得到一个例外:
private class AudioServiceConnection implements ServiceConnection{ AudioPlayerServiceBinder audioServiceBinder; @Override public void onServiceConnected(ComponentName name,IBinder serviceBinder) { serviceConnected = true; Log.i(TAG,"Connected to audio player service."); audioServiceBinder = ((AudioPlayerServiceBinder) serviceBinder); AudioPlayActivity.this.audioService = audioServiceBinder.getAudioService(); mediaController.show(5000); }
例外是:
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running? at android.view.ViewRoot.setView(ViewRoot.java:527) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91) at android.view.Window$LocalWindowManager.addView(Window.java:424) at android.widget.MediaController.show(MediaController.java:304) at android.widget.MediaController.show(MediaController.java:249) at com.myapp.AudioPlayActivity$AudioServiceConnection.onServiceConnected(AudioPlayActivity.java:295)
我可以重新创建相同的例外:
>点击通知打开活动
>按回来关闭活动.
>单击通知以打开新版本的活动.
这导致我相信媒体控制器以某种方式泄漏,并尝试在原始的Activity实例中显示.我找不到任何理由,因为mediaController在Activity的onCreate()中被实例化,并且只绑定到活动本身. (活动然后处理传递命令到服务).