android – 无法修复MediaController.show()异常

前端之家收集整理的这篇文章主要介绍了android – 无法修复MediaController.show()异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个音频文件播放在前台服务使用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()中被实例化,并且只绑定到活动本身. (活动然后处理传递命令到服务).

解决方法

在以前的活动完成生命周期之前,我认为你正在调用show()太早.可以通过延迟调用show()直到调用所有生命周期方法来避免BadTokenException.您可以为此发布延迟的可执行文件.或者你可以试试以下,
if (!((Activity)your_context).isFinishing()) {
    mediaController.show(5000);
}
原文链接:https://www.f2er.com/android/311072.html

猜你在找的Android相关文章