Yesterday did a demo, static registration of Broadcastrreceiver in the OnReceive method to achieve alertdialog.
However, Jian said that my this will be an error, but why did not error is very strange, I am also very strange, this morning I have studied the Alertdialog pit.
dialog is an application window of type and activity, and you can create Phonewindow instances.
Look at the dialog constructor:
Dialog (@NonNull context context, @StyleResintThemeresid,Booleancreatecontextthemewrapper) { //Ignore some codeMwindowmanager =(WindowManager) Context.getsystemservice (Context.window_service); FinalWindow W =NewPhonewindow (Mcontext); Mwindow=W; W.setcallback ( This); W.setonwindowdismissedcallback ( This); W.setwindowmanager (Mwindowmanager,NULL,NULL);//This is the sentence. W.setgravity (Gravity.center); Mlistenershandler=NewListenershandler ( This); }
Setwindowmanager (WindowManager wm, IBinder Apptoken, String appName, boolean hardwareaccelerated) The second parameter, we set to NULL. (In the activity, the token is set to the token passed over by Activitythread.) Tockon is a token used to represent a window, and only the qualifying token can be added to the app by the WMS. )
In the Show method of dialog,
Public void Show () { // ignores some code Mdecor = mwindow.getdecorview (); = mwindow.getattributes (); // Ignore some code Try { Mwindowmanager.addview (Mdecor, L);//When returning to the manager, if Tockon is not NULL, it is calledgetSystemService(),为空会报出异常。
Truefinally {}}
PublicObject getsystemservice (@ServiceName @NonNull String name) {if(Getbasecontext () = =NULL) { Throw NewIllegalStateException ("System services not available to activities before OnCreate ()"); }//because of the tocken of the context that has been passed overif(window_service.equals (name)) {returnMwindowmanager; } Else if(search_service.equals (name)) {Ensuresearchmanager (); returnMsearchmanager; } return Super. Getsystemservice (name); }
System to type_application type of window, requirements must be activity token, not the system will throw badtokenexception exception. Dialog is the application window type, token must be the activity token.
The context of Alertdialog cannot be the context of application