This article is reproduced from the Csdn jzj1993, the original connection: http://blog.csdn.net/jzj1993/article/details/39158865 Sometimes we need to use Android to achieve in the background simulation system keys, For example, adjust the volume (analog volume key), close the foreground running app (analog back button), or simulate touch screen events. However, for the native Android system, the background process to close the foreground process, or even simulate user events, and then manipulate the entire system, is not in line with the system security principle, if there is a virus or malicious software exploit, it can be very dangerous. For some special reasons, I happen to need to implement such a function without the ability to compile the Android system myself (but can take advantage of root permissions, because root access is relatively much simpler, and many users of Android devices have root). Online also see a lot of people are mentioning similar problems, many people discussed for half a day, the results are no solution. So I took a lot of energy and finally found the solution. Find a lot of information on the Internet, mainly found two ways: instrumentation and Iwindowmanager. use instrumentation interface: For non-self-compiled Android system, can not get the system signature, only in front of the simulation button, not background simulation. One is to use the instrumentation interface, which was originally used to test the software and left out. After trying, it was found that the interface can simulate keystrokes, but only if the app is in the foreground. While the application is in the foreground, the analog button is basically not much of a function (the analog key operation application itself does not seem very significant). This instrumentation interface fails when the application is in the background. The explanation on the web is that using this interface in the background requires system permissions, which means adding android:shareduserid= "Android.uid.system" to the manifest. And what is the problem? The APK that declares the system permission can be installed on the Android device only if it has the system signature, for example, the system comes with the phone, SMS, essentially the APK program, but these apps have system privileges. Android has a signature mechanism, and the APK can only be installed if it has a digital signature. Typically, when you debug, the default eclipse automatically signs it, using the debug signature. When the app is published, the developer signs the APK with its own unique digital signature file (this file can be generated with eclipse and the signature can be done by Eclipse). APK has a new version of the installation, if a signature inconsistency is detected, the system will prompt for inconsistent signatures and only uninstall the old version to install. This mechanism has avoided, to some extent, the modification of the official apk by the third party, or even the illegal implantation of the virus (of course, if the user actively uninstall the old version of the official app, install the new version of the unofficial apk is also possible). and different apps with the same signature can share some data between them. and how does the system signature get it? When compiling the Android system, a system-signed digital signature file is compiled together. For a system that has already been compiled, or to fit a different system, it is not possible to obtain the digital signature file, so the APK can not be signed system. Finally, the Uid.system property of the APK can not be installed, so the instrumentation interface Background Simulation button method, only in the case of self-compiled system can be used. invoke system Iwindowmanager with reflection method Hide API: Poor compatibility, poor stability, error prone. In addition, the actual compilation error occurred, the reason is temporarily unknown. There is also a way to online. There are some hidden APIs in the Android system, often using Java's permission restrictions, which make these APIs impossible to invoke. But by reflection, you can break through Java's permission limits. The API that simulates keystrokes and touch-screen events is hidden in Iwindowmanager. Try the online method, download to a jar file compiled by Android source code, add to the project, and then use the launch to write some code, try to invoke the hidden API. As a result, eclipse does not respond directly to the compilation, possibly because the computer is not configured enough and the jar file is too large. Tried several times without success, and considering that this method has a lot of drawbacks, and it is likely to eventually need system permissions (many of the online articles are not very clear), and then gave up this method. Summary of android analog key issues [using the Iwindowmanager.injectkeyevent method]http://blog.csdn.net/xudongdong99/article/details/ 8857173 android using the Hidden API (lots of plots) http://163liufuliang.blog.163.com/blog/static/331651862013119114431760 /  JNI Call C Program Simulation button: Still a permissions issue. referred to some of the online information on the possible ideas, found that the rest can be thought of the method is implemented with JNI, by invoking C + + program to simulateKeys. Not familiar with the Linux underlying programming, the online reference to some code, in Ubuntu under the writing of a key simulation program, a smooth compilation run through. Then began to learn the Jni method of compiling, first in the C program layer wrote a simple addition operation, compile and run the test pass, and then put the code of the analog button to paste in. Look forward to writing the Android Java layer Code, compiling, downloading, executing the program, but found completely ineffective. want to see exactly which step is wrong, in the C program inside changed, with Logcat print out the return value of the C program, found that in the opening of the key device error, it seems certainly the issue of permissions. Although the system has root,apk also allow root permissions, but root permissions can not be passed to the C program, insufficient permissions, the program cannot execute. On the Internet to find a information about Linux, Android permissions, also did not find out what train of thought. In fact, at that time very confused, in the Linux system, the root authority is the highest permissions, Android is no exception, there are articles, root privileges > System permissions > User rights. Although it is possible to get root permissions and not complete the tasks that can be done by system permissions, the total feeling should not be. Android Key Wizard: Using root privileges without system signatures, it is possible to implement events such as background simulation keys and touch screens. was desperate, feeling that it would only solve the problem by compiling the system itself. At that time, suddenly remembered the key wizard software. Used in the previous version of the computer, in the Android Market to find, sure enough also has an Android version. Download use found, the key Wizard can be implemented in the background to simulate the key operation, requires root authority, but what the principle is unknown. I want to try to decompile the source view, but there were some problems, the anti-compilation did not succeed. The principle of searching the Android Key wizard on the Internet, in addition to the previous two source-dependent environment to use the API, also did not find the results. At the very least, however, it is possible to use root privileges without the need for system signatures, to implement analog keys, and to be compatible with a large number of Android devices. finally solves the problem: using the shell to invoke the ADB instruction implementation. Continue to search the Internet for Android button simulation (in fact, do not know what keyword is good, can think of the keywords are used all the time, but the results of the search, are mentioned before the several dependent on the source code environment and System permissions of the scheme). Discover a lot of articles that introduce ADB debugging and send key events to your phone. Just before, under root permission, use Java to invoke the Linux Shell on the bottom of the Android, and then execute PM instructions to load the APK. At this point, I have a whim, can I invoke the ADB command with the shell? then tried to execute the runtime using Java.GetRuntime (). EXEC ("su"). Getoutputstream (), gets the output stream object of a process with root permission, writes a string to it that can be executed by the shell, and the ADB analog key command is " Input KeyEvent keycode ", KeyCode is the key value of the key, for example, Keyevent.keycode_volume_up indicates volume plus. After compiling the program installation execution, finally achieved the expected effect, was very happy. As for touch screen or mouse events, just call the appropriate ADB instructions. But a little bit of a problem is that the reaction speed is very slow, especially when the continuous simulation of multiple keys, even the crash. While the key wizard runs quite smoothly, I began to wonder how the key Wizard was implemented. Then finally found the reason that when simulating a button, you should not call Runtime.getruntime (). EXEC ("su"), because every time this code is called, the runtime instance is acquired and the "SU" request root permission is executed. The reaction will be slow (I understand that it is equivalent to opening a new command-line window every time), and should just be executed at the beginning and fetch an OutputStream instance, and then each time a shell instruction is executed, it is much quicker to write the corresponding string to it. Paste the available code below. Requires that the device is root and does not require any other special permissions or signatures. Because of the ADB directive, compatibility is not too much of a problem. The first time the program is run (in fact, when executing runtime.exec ("su"), the root permission is requested.
1 /**2 * Execute the shell command under Linux with root privileges3 * 4 * @authorJzj5 * @since2014-09-096 */7 Public classRootshellcmd {8 9 Privateoutputstream os;Ten One /** A * Execute shell command - * - * @paramcmd the * Instruction - */ - Public Final voidexec (String cmd) { - Try { + if(OS = =NULL) { -OS = Runtime.getruntime (). EXEC ("su"). Getoutputstream (); + } A Os.write (Cmd.getbytes ()); at Os.flush (); -}Catch(Exception e) { - e.printstacktrace (); - } - } - in /** - * Background Simulation global button to * + * @paramKeyCode - * Key Value the */ * Public Final voidSimulatekey (intkeycode) { $EXEC ("input keyevent" + keycode + "\ n"));Panax Notoginseng } -}The main purpose of writing this article is not to emphasize the difficulty of the matter, nor just to propose a solution to the problem (that is, there is no need to write so many processes ahead). It's about trying to write the whole process of my problem-solving, which is a record for me, and for the reader, maybe I can find something. After solving the problem, it was discovered unexpectedly that someone had solved the problem and made a blog. Unfortunately, the blog was buried by a large number of blogs using the first two ideas, and I didn't find it. This blog address is here: http://blog.csdn.net/aminfo/article/details/7785975 by the way, the authors of this blog mention the disadvantages: slow response. As mentioned earlier, I have also been given a solution to the same problem.
Go: Android Essay--use root permissions to enable background simulation of global keys, touch-screen event methods (similar to key wizard)