getActivity / Toaster

Android 吐司框架,专治 Toast 各种疑难杂症
Apache License 2.0
3.25k stars 406 forks source link

双击退出,发生WindowManager: android.view.WindowLeaked: #9

Closed lcf687619 closed 5 years ago

lcf687619 commented 5 years ago

private long duration; private final int SPACE_TIME = 3000; @Override public void onBackPressed() { long now = System.currentTimeMillis(); if (now - duration > SPACE_TIME) { duration = now; ToastUtils.show("再按一次返回键关闭程序!"); return; } super.onBackPressed(); } 这么调用后发生了WindowManager: android.view.WindowLeaked:

lcf687619 commented 5 years ago

WindowManager: android.view.WindowLeaked: Activity com.***.app.ui.main.MainActivity has leaked window android.widget.LinearLayout{7b64701 V.E...... ......ID 0,0-668,141} that was originally added here at android.view.ViewRootImpl.(ViewRootImpl.java:501) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:346) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93) at com.core.wigets.toast.ToastHelper.show(ToastHelper.java:77) at com.core.wigets.toast.SupportToast.run(SupportToast.java:37) at android.os.Handler.handleCallback(Handler.java:789) at android.os.Handler.dispatchMessage(Handler.java:98) at android.os.Looper.loop(Looper.java:171) at android.app.ActivityThread.main(ActivityThread.java:6699) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:246) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)

getActivity commented 5 years ago

你好,这个问题已经被修复好,更新一下版本即可

lcf687619 commented 5 years ago

可以现在告诉我下怎么修复的么

getActivity commented 5 years ago

复制一下来自WindowHelper类中的代码:

// A跳转B页面的生命周期方法执行顺序:
// onPause(A)->onCreate(B)--->onStart(B)--->onResume(B)--->onStop(A)--->onDestroyed(A)

@Override
public void onActivityPaused(Activity activity) {
    // 取消这个吐司的显示
    mToastHelper.cancel();
    // 不能放在 onDestroyed 方法中,因为此时新的 Activity 已经创建完成
    // 调用取消显示会直接新的 Activity 的 onCreate 调用显示吐司可能显示不出来的问题(立马显示然后立马消失的效果)
}
lcf687619 commented 5 years ago

发现你新写的这个有问题,AActivity-->BActivity,点击按钮Button,跳转到CActivity,然后进行操作登录,返回到BActivity,再次点击BActivity中的Button,吐司不显示,因为在WindowHelper中记录的Activity不存在,返回在回到AActivity,同样不显示Toast内容

getActivity commented 5 years ago

只要Activity没有被销毁,WindowHelper记录的Activity一定存在

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    mCurrentTag = getObjectTag(activity);
    mActivitySet.put(mCurrentTag, activity);
}

@Override
public void onActivityStarted(Activity activity) {
    mCurrentTag = getObjectTag(activity);
}

@Override
public void onActivityResumed(Activity activity) {
    mCurrentTag = getObjectTag(activity);
}

@Override
public void onActivityDestroyed(Activity activity) {
    // 移除对这个 Activity 的引用
    mActivitySet.remove(getObjectTag(activity));
    // 如果当前的 Activity 是最后一个的话
    if (getObjectTag(activity).equals(mCurrentTag)) {
        // 清除当前标记
        mCurrentTag = null;
    }
}