Why does a BadTokenException sometimes occur when you use a non-activity to create and pop up a Dialog?

The main reason is that the non-activity Context’s WindowManger does not have ParentWindow, so there is no corresponding container on the WMS side, that is, it does not know where to place the Dialog Window.

Does finding a container still have anything to do with the Context instance? If you use a Service or Application, you cannot find the container. If you use an Activity, you can find the container.

Dialog is added to the View in the show method via WindowManager, which is obtained from the Context’s getSystemService(WINDOW_SERVICE) method.

Here’s the thing: Because the Activity overrides the getSystemService method of the Context, it returns the WindowManager object of the Activity’s main Window when it retrieves the WINDOW_SERVICE. Of course, there’s nothing special about the WindowManager object for the main Window, It just inside mParentWindow points to the main Window (other than the Activity of the Context of the WindowManager. MParentWindow default is null).

Reference:

Daily asking | Dialog constructor context must be introduced into the Activity?