Unable to add window — token null is not valid; is your activity running?

后端 未结 8 1168
花落未央
花落未央 2020-12-01 11:45

i want to show a custom popup menu when user click on a floating icon

the float icon create with an service and i have no activity

this is my floating icon c

相关标签:
8条回答
  • 2020-12-01 12:13

    In my case, I was inflating a PopupMenu at the very beginning of the activity i.e on onCreate()... I fixed it by putting it in a Handler

      new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    PopupMenu popuMenu=new PopupMenu(SplashScreen.this,binding.progressBar);
                    popuMenu.inflate(R.menu.bottom_nav_menu);
                    popuMenu.show();
                }
            },100);
    
    0 讨论(0)
  • 2020-12-01 12:14

    I had the same problem as you, it looks like you used the tutorial from http://www.piwai.info/chatheads-basics like I did. The problem is that you cannot reliably pass the current activity to the popup window, because you have no control over the current activity. It looks like there might be a unreliable way to get the current activity, but I don't recommend that.

    The way I fixed it for my app was to not use the popup window, but instead make my own through the window manager.

    private void showCustomPopupMenu()
        {
                    windowManager2 = (WindowManager)getSystemService(WINDOW_SERVICE);
                    LayoutInflater layoutInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    View view=layoutInflater.inflate(R.layout.xxact_copy_popupmenu, null);
                    params=new WindowManager.LayoutParams(
                            WindowManager.LayoutParams.WRAP_CONTENT,
                            WindowManager.LayoutParams.WRAP_CONTENT,
                            WindowManager.LayoutParams.TYPE_PHONE,
                            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                            PixelFormat.TRANSLUCENT);
    
                    params.gravity=Gravity.CENTER|Gravity.CENTER;
                    params.x=0;
                    params.y=0;
                    windowManager2.addView(view, params);  
        }
    

    If you want this to look like a popup window, just add a transparent gray view as the background and add a onClickListener to it to remove the view from the windowManager object.

    I know this isn't as convenient as a popup, but from my experience, it is the most reliable way.

    and don't forget to add permission in your manifest file

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    
    0 讨论(0)
提交回复
热议问题