android.view.WindowManager$BadTokenException

Я настраиваю уведомление в приложении, используя оконный менеджер для добавления.

android.view.WindowManager$BadTokenException: невозможно добавить окно -- токен android.os.BinderProxy@74b2eff недействителен; ваша активность запущена? в android.view.ViewRootImpl.setView(ViewRootImpl.java:685) в android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:319) в android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85) в com.zuck3. petpolar.manager.InboxNotificationManager.showInboxNotification(InboxNotificationManager.java:82) в com.zuck3.petpolar.activity.Inbox.InboxActivity.onCreate(InboxActivity.java:66) в android.app.Activity.performCreate(Activity.java:6376) в android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113) в android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2519) в android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654) в android.app. ActivityThread.-wrap11(ActivityThread.java) в android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488) в android.os.Handler.dispatchMessage(Handler.java:111) в android.os.Looper.loop( Looper.java:207) В/С ystem.err: в android.app.ActivityThread.main(ActivityThread.java:5728) W/System.err: в java.lang.reflect.Method.invoke(собственный метод) W/System.err: в com.android. internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) W/System.err: в com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) W/libEGL: [ANDROID_RECORDABLE] формат: 1

InboxNotificationManager.java

public class InboxNotificationManager {
private static InboxNotificationManager instance;
private WindowManager mWindowManager;
private WindowManager.LayoutParams mWindowParams;
private InboxNotificationView notificationView;
private Runnable runnable;
private Handler handler = new Handler(Looper.getMainLooper());
private Animation.AnimationListener animationListener = new Animation.AnimationListener() {
    @Override
    public void onAnimationStart(Animation animation) {

    }

    @Override
    public void onAnimationEnd(Animation animation) {
        hideInboxNotification();

    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }
};


public static InboxNotificationManager Instance(Context context) {
    if (instance == null) {
        instance = new InboxNotificationManager(context);
    }
    return instance;

}

public InboxNotificationManager(Context context) {
    notificationView = new InboxNotificationView(context);
    mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    mWindowParams = new WindowManager.LayoutParams();
    mWindowParams.gravity = Gravity.TOP | Gravity.RIGHT;
    mWindowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
    mWindowParams.width = WindowManager.LayoutParams.MATCH_PARENT;
    mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
    mWindowParams.format = PixelFormat.TRANSLUCENT;
    runnable = new Runnable() {
        @Override
        public void run() {
            notificationView.stopAnimation(animationListener);

        }
    };


}

public void setTextMeesage(String meesage) {
    notificationView.setTextMessage(meesage);
    //  Toast.makeText(InboxNotificationManager.this, "", Toast.LENGTH_SHORT).show();


}

public void showInboxNotification(String message) {
    if (notificationView.getWindowToken() == null) {
        mWindowManager.addView(notificationView, mWindowParams);
        notificationView.startAnimation();
        setTextMeesage(message);

    } else {
        // mWindowManager.setText(count);

    }
    notificationView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            notificationView.stopAnimation(animationListener);

        }
    });

    handler.removeCallbacks(runnable);
    handler.postDelayed(runnable, 3000);


}

public void hideInboxNotification() {
    if (notificationView.getWindowToken() != null) {
        mWindowManager.removeView(notificationView);
    }


}

И когда я использую этот класс

InboxNotificationManager.Instance(BaseActivity.this).showInboxNotification("Hello world");

Спасибо и извините за мой плохой английский.


person Wuttipong Khemphetjetsada    schedule 22.07.2016    source источник
comment
Вы проверили другие ответы, связанные с этой ошибкой, здесь, на SO? Я нашел 2-3. Поделитесь своим onCreate методом, пожалуйста.   -  person Vucko    schedule 22.07.2016
comment
Если ваша деятельность завершается, и в это время добавляется представление, оно выдает это исключение. Поэтому, прежде чем показывать представление/диалог, проверьте if(!isFinishing()) в действии.   -  person Akshay Bhat 'AB'    schedule 22.07.2016
comment
Спасибо за ответ. Но я хочу показать свое собственное представление о каждом действии, которое я хочу, например, Toast.   -  person Wuttipong Khemphetjetsada    schedule 22.07.2016


Ответы (1)


Убедитесь, что ваша активность запущена, используйте

if(mActivity != null && !mActivity.isFinishing())

Проверять

person RedWolf    schedule 27.06.2017