Android中消息队列postDelay+Dialog引起的窗体泄露的主要原因是,当床窗体压入栈或者finish掉后,Activity由于需要处理postDelay而不能及时销毁,因此造成了一个问题,当dialog触发show方法时,由于window和activity已经分开了,因此便会造成窗体泄露。
1.WindowManager$BadTokenException
错误描述:android.view.WindowManager$BadTokenException: Unable to add window -- token [email protected] is not valid; is your activity running?
2.解决办法是,使用一个变量检测当前activity是否处于活动状态
private boolean isActive = true; public void onResume() { super.onResume(); isActive = true; } public void onPause() { super.onPause(); isActive = false; } public boolean activityIsActivity() { return isActive; } public void showAlertDialog() { if(activityIsActive()) //只有窗体处于活动状态时执行此程序 { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle("hello world") .setCancelable(false) .setMessage("Hello"); builder.create().show(); } }
时间: 2024-10-11 10:10:40