Android system principle and source code analysis: using Java reflection technology to prevent the button from closing the dialog box

Source: Internet
Author: User

Statement: This article reposted from the csdn TECHNOLOGY Article: http://blog.csdn.net/nokiaguy/archive/2010/07/27/5770263.aspx Author: nokiaguy

When you repost, please indicate the original source.

As we all know, the alertdialog class is used to display dialog boxes. The basic usage of alertdialog is not detailed here. There are many online users who can search by themselves. This article describes how to control alertdialog as you like.

Now let's take a look at the first requirement: if an application needs to pop up a dialog box. The dialog box cannot be closed when you click OK. When the work is completed successfully, the dialog box is closed. Of course, you can click the cancel button to close the dialog box.
This requirement is not complex, and it is not too complex. (although we can create an activity to complete this task, we can also put buttons on the view, but it shows that some cannons are hitting mosquitoes, if there is only one line of text in the dialog box, it is not worth the effort ). However, anyone who has used alertdialog knows that the dialog box must be closed no matter which button is clicked or whether the event is executed. That is to say, the user cannot control the closing action of the dialog box. In fact, the action to close the dialog box has been written to the android SDK, and no interfaces are left for the user. But my motto is "nothing in the universe is uncontrollable ".
To control the closing behavior of the dialog box, you must first analyze the classes and codes used to close the dialog box. Go to the source code of the alertdialog class. Alertdialog defines only one variable: malert. This variable is of the alertcontroller type. The alertcontroller class is an internal class of Android. In the com. Android. Internal. app package, it cannot be accessed in normal mode. You cannot track the source code in eclipse by pressing CTRL. However, you can find alertcontroller. Java directly in the android source code. Let's go back to the alertdialog class. The alertdialog class is actually just a shelf. Tasks such as setting buttons and titles are all completed by the alertcontroller class. Therefore, the alertcontroller class is the key.
Find the alertcontroller. Java file. Do not feel dizzy after opening the file. There are many codes in this file. However, so much code is useless to the topic of this article. The code for the control button is as follows.
The following code is displayed at the beginning of the alertcontroller class:

View. onclicklistener mbuttonhandler = new view. onclicklistener (){
Public void onclick (view v ){
Message M = NULL;
If (V = mbuttonpositive & mbuttonpositivemessage! = NULL ){
M = message. Obtain (mbuttonpositivemessage );
} Else if (V = mbuttonnegative & mbuttonnegativemessage! = NULL ){
M = message. Obtain (mbuttonnegativemessage );
} Else if (V = mbuttonneutral & mbuttonneutralmessage! = NULL ){
M = message. Obtain (mbuttonneutralmessage );
}
If (M! = NULL ){
M. sendtotarget ();
}

// Post a message so we dismiss after the above handlers are executed
Mhandler. obtainmessage (buttonhandler. msg_dismiss_dialog, mdialoginterface)
. Sendtotarget ();
}
};

From this code, we can guess that the first few lines of code are used to trigger the click events of the three buttons (positive, negative, and neutral) in the dialog box, the final code is used to close the dialog box (because we found msg_dismiss_dialog and guessed it ).

Mhandler. obtainmessage (buttonhandler. msg_dismiss_dialog, mdialoginterface)
. Sendtotarget ();

The above Code does not close the dialog box directly, but is handled by a handler. The Code is as follows:

Private Static final class buttonhandler extends handler {
// Button clicks have message. What as the button {1, 2, 3} constant
Private Static final int msg_dismiss_dialog = 1;

Private weakreference <dialoginterface> mdialog;

Public buttonhandler (dialoginterface DIALOG ){
Mdialog = new weakreference <dialoginterface> (DIALOG );
}

@ Override
Public void handlemessage (Message MSG ){
Switch (msg. What ){

Case dialoginterface. button_positive:
Case dialoginterface. button_negative:
Case dialoginterface. button_neutral:
(Dialoginterface. onclicklistener) msg. OBJ). onclick (mdialog. Get (), MSG. What );
Break;

Case msg_dismiss_dialog:
(Dialoginterface) msg. OBJ). Dismiss ();
}
}
}

From the end of the code above, you can find (dialoginterface) msg. OBJ). Dismiss ();. Now that we have read so many source codes, let's summarize the event handling process by clicking the button in the dialog box. An onclick event is added for each button in the alertcontroller processing dialog box. The object instance of this event class is the above mbuttonhandler. In this click event, the click event set for the button is called by sending a message (that is, the click event set by the second parameter of methods such as setpositivebutton ), after clicking the event of the trigger button, the dismiss method is called to close the dialog box by sending a message. The alertcontroller class defines a global mhandler variable. In the alertcontroller class, the buttonhandler class is used to assign values to mhandler. Therefore, we only need to replace buttonhandler with our own handler object to prevent the dismiss method from being called to close the dialog box. Next, create a new buttonhandler class in your own program (or another name ).

Class buttonhandler extends Handler
{

Private weakreference <dialoginterface> mdialog;

Public buttonhandler (dialoginterface DIALOG)
{
Mdialog = new weakreference <dialoginterface> (DIALOG );
}

@ Override
Public void handlemessage (Message MSG)
{
Switch (msg. What)
{

Case dialoginterface. button_positive:
Case dialoginterface. button_negative:
Case dialoginterface. button_neutral:
(Dialoginterface. onclicklistener) msg. OBJ). onclick (mdialog
. Get (), MSG. What );
Break;
}
}
}

We can see that the above class is similar to the buttonhandler class in alertcontroller, but only the last case clause (used to call the dismiss method) and related code of the switch statement are removed.
Next, we will assign a new value to mhandler in alertcontroller. Because mhandler is a private variable, you need to use Java reflection technology to assign values to mhandler. Since the malert variable in the alertdialog class is also private, you also need to use the same reflection technology to obtain the malert variable. The Code is as follows:

Create an alertdialog object first

Alertdialog = new alertdialog. Builder (this)
. Settitle ("ABC ")
. Setmessage ("content ")
. Seticon (R. drawable. Icon)
. Setpositivebutton ("OK ",
New onclicklistener ()
{
@ Override
Public void onclick (dialoginterface dialog,
Int which)
{

}
}). Setnegativebutton ("cancel", new onclicklistener ()
{

@ Override
Public void onclick (dialoginterface dialog, int which)
{
Dialog. Dismiss ();
}
}). Create ()

The preceding dialog box is common. The dialog box is closed when you click a button. Let's modify the value of an mhandler variable before calling the show method. OK. Let's witness the miracle.

Try
{

Field field = alertdialog1.getclass (). getdeclaredfield ("malert ");
Field. setaccessible (true );
// Obtain the malert variable value
Object OBJ = field. Get (alertdialog1 );
Field = obj. getclass (). getdeclaredfield ("mhandler ");
Field. setaccessible (true );
// Modify the value of the mhandler variable and use the new buttonhandler class
Field. Set (OBJ, new buttonhandler (alertdialog1 ));
}
Catch (exception E)
{
}
// Display dialog box
Alertdialog. Show ();

If a try catch statement is added, clicking the OK button in the dialog box does not close the dialog box (unless the dismiss method is called in the Code ), click the cancel button to close the dialog box (because the dismiss method is called ). If you try... Catch code segment. The dialog box will return to normal again.
Although the above Code has solved the problem, there are still a lot of code to be written. For this reason, we can also use another method to prevent closing the dialog box. This method does not need to define any classes.
This method requires some tips. Since the system calls dismiss to close the dialog box, we can make some articles on the dismiss method. When the system calls the dismiss method, it first determines whether the dialog box is closed. If the dialog box is closed, the dismiss method is exited and the dialog box is no longer closed. Therefore, we can fool the system. When calling the dismiss method, we can make the system think that the dialog box has been closed (although the dialog box has not been closed), so that the dismiss method will become invalid, in this way, the dialog box cannot be closed even if the system calls the dismiss method.
Next, let's go back to the alertdialog source code and continue to track the source code of the alertdialog parent class dialog. Find the dismissdialog method. In fact, the dismiss method closes the dialog box through the dismissdialog method. The code of the dismissdialog method is as follows:

Private void dismissdialog (){
If (mdecor = NULL ){
If (config. logv) log. V (log_tag,
"[Dialog] dismiss: already dismissed, ignore ");
Return;
}
If (! Mshowing ){
If (config. logv) log. V (log_tag,
"[Dialog] dismiss: Not showing, ignore ");
Return;
}

Mwindowmanager. removeview (mdecor );

Mdecor = NULL;
Mwindow. closeallpanels ();
Onstop ();
Mshowing = false;

Senddismissmessage ();
}

The code after this method does not need to worry about it. First look at if (! Mshowing ){... } This code. This mshowing variable is used to determine whether the dialog box is closed. Therefore, by setting this variable in the code, we can make the system think that the dialog box has been closed and will no longer close the dialog box. Because mshowing is also a private variable, reflection technology is also required to set this variable. You can set mshowing In the click event in the dialog box. The Code is as follows:

Try
{
Field field = dialog. getclass ()
. Getsuperclass (). getdeclaredfield (
"Mshowing ");
Field. setaccessible (true );
// Set the mshowing variable to false, indicating that the dialog box is closed.
Field. Set (dialog, false );
Dialog. Dismiss ();

}
Catch (exception E)
{

}

Click the button to add the above Code to the Event code, and the button will no longer be able to close the dialog box. To close the dialog box, set mshowing to true. Note that setting the mshowing variable in one button also affects the function of closing the dialog box of another button. Therefore, you need to set the mshowing variable value in the click event of each button.

It can be seen from this article that although some functions of the dialog box are controlled using common methods, reflection technology can easily achieve seemingly impossible tasks. Of course, in addition to controlling the closing function of the dialog box, you can also control other behaviors of the dialog box. The rest is mined by the reader.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.