Several implementation methods for shutting down or restarting the Android system

Source: Internet
Author: User

Several implementation methods for shutting down or restarting the Android system

Some modifications were made to the Android system shut down or restarted some time ago, so I made some attempts and collected some information. Now I will sort out the information and make some summary, easy to learn or work in the future.

The default SDK does not provide an API for application developers to directly shut down or restart the Android system. Generally, the Android system is shut down or restarted, requires High permissions (system permissions or even Root permissions ). Therefore, in a general APP, if you want to enable the shutdown or restart function, either declare system permissions in the App, or in some "indirect" way, such as broadcast or reflection, to indirectly shut down or restart the system. In addition, it is compiled in the source code environment. One advantage of this is that you can directly call APIs not made public in Android, which is not achieved by Eclipse + SDK. Below are several methods I have tried:

I. Sending broadcast methods

Broadcast is one of the four basic components of Android, which we often call Broadcast. The Android system itself contains a lot of broadcasts, which constantly listen to every broadcast registered in the system and are ready to respond to the operation at any time. Here, there is a broadcast about shutdown or restart: Intent. ACTION_REQUEST_SHUTDOWN and Intent. ACTION_REBOOT. By sending these two broadcasts, Android can automatically receive broadcasts and respond to shutdown or restart operations. ACTION_REQUEST and ACTION_REBOOT are Intent. java are two declared string constants.

   public static final String ACTION_REBOOT =              "android.intent.action.REBOOT";   public static final String ACTION_REQUEST_SHUTDOWN = "android.intent.action.ACTION_REQUEST_SHUTDOWN";

Intent. java is located in the source code/frameworks/base/core/java/android/content/Intent. java. The specific implementation method is as follows:

// Broadcast mode shutdown and restart case R. id. shutdown_btn1: Log. v (TAG, "broadcast-> shutdown"); Intent intent = new Intent (Intent. ACTION_REQUEST_SHUTDOWN); intent. putExtra (Intent. EXTRA_KEY_CONFIRM, false); // Replace "false" with "true". The intent Confirmation window is displayed. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK); startActivity (intent); break; case R. id. reboot_btn1: Log. v (TAG, "broadcast-> reboot"); Intent intent2 = new Intent (Intent. ACTION_REBOOT); intent2.putExtra ("nowait", 1); intent2.putExtra ("interval", 1); intent2.putExtra ("window", 0); sendBroadcast (intent2); break;

Note the following:

First, as mentioned above, you need to escalate the APP to system permissions by adding the following code to AndroidMenifest. xml:

android:sharedUserId="android.uid.system"

Second, you also need to add the shutdown permission

 

Third, in Eclipse, Intent. ACTION_REQUEST_SHUTDOWN and Intent. EXTRA_KEY_CONFIRM returns an error in Eclipse IDE, which is the same as previously mentioned. These two attributes are not open to the upper layer. If you compile the project in the source code, it can be compiled.

Fourth, because you need to compile the project in the source code, you need to write the mk file for the project and add the Android. mk file under the project root directory. The content is as follows:

LOCAL_PATH:= $(call my-dir)include $(CLEAR_VARS)LOCAL_MODULE_TAGS := optionalLOCAL_SRC_FILES := $(call all-java-files-under, src)LOCAL_PACKAGE_NAME := PowerActionDemoLOCAL_CERTIFICATE := platforminclude $(BUILD_PACKAGE) 
Finally, you can verify the function by pushing the compiled apk file to the machine through adb.


Ii. Run the sh file through init. rc to start the System Service

After Android starts the file system, the first application called is/init. An important part of this file is the parsing of init. rc and init. xxx. rc, and then execute the parsed task. However, init. rc can perform some simple initialization operations during system initialization. By using this, you can write a simple sh script file for shutdown or restart, and perform corresponding shutdown or restart operations through system init parsing.

1. First, write the sh script for shutdown and restart. For example, create

Restart the script system_reboot.sh. The content is as follows:

#!/system/bin/sh  reboot
Shutdown script system_shutdown.sh

#!/system/bin/sh  reboot -p

Note: The shutdown command is not shutdown, but reboot-p.

2. Compile the Android. mk compilation script to compile the two sh files together in the/system/bin directory during source code compilation.

LOCAL_PATH := $(call my-dir)include $(CLEAR_VARS)LOCAL_PREBUILT_EXECUTABLES := system_shutdown.sh system_reboot.shLOCAL_MODULE_TAGS := optionalinclude $(BUILD_MULTI_PREBUILT)

3. Add the shutdown and restart services to init. rc, open the init. rc file, and add the following content at the end:

service system_shutdown /system/bin/system_shutdown.sh        oneshot        disabled service system_reboot /system/bin/system_reboot.sh        oneshot        disabled

The oneshot option indicates that the service is started only once. If the oneshot option is not available, the executable program will always exist. If the executable program is killed, it will be restarted.

Disabled indicates that the service is disabled. The service is not automatically started when it is started, but it can be manually started in the application.


4. Create a directory, such as poweraction. Put the preceding Android. mk, system_shutdown.sh, and system_reboot.sh in the directory, and copy the poweraction directory to the Android system, such as the device path. Then, compile the Android source code. After the source code is compiled, view the generated out /... the/system/bin file contains two sh files: system_shutdown.sh and system_reboot.sh. If yes, the compilation is successful.

5. Finally, start the system service and shut down or restart it.

// Start the system service to shut down or restart case R. id. shutdown_btn2: Log. v (TAG, "system service-> shutdown"); SystemProperties. set ("ctl. start "," system_shutdwon "); break; case R. id. reboot_btn2: Log. v (TAG, "system service-> reboot"); SystemProperties. set ("ctl. start "," system_reboot "); break;

3. Runtime calls Linux-shell

We know that the Java class Runtime can be used to call and execute shell commands, while the Android Virtual Machine supports the Linux-shell language. Based on this, you can use Runtime to execute shell commands for shutdown or restart, which is roughly the same as method 2 described above. The function code is as follows:

// Run linux-shellcase R. id. shutdown_btn3: try {Log. v (TAG, "root Runtime-> shutdown"); // Process proc extends runtime.getruntime(cmd.exe c (new String [] {"su", "-c", "shutdown "}); // shut down Process proc restart runtime.getruntime(cmd.exe c (new String [] {"su", "-c", "reboot-p"}); // shut down proc. waitFor ();} catch (Exception e) {e. printStackTrace ();} break; case R. id. reboot_btn3: try {Log. v (TAG, "root Runtime-> reboot"); Process proc extends runtime.getruntime(.exe c (new String [] {"su", "-c", "reboot "}); // shut down proc. waitFor ();} catch (Exception ex) {ex. printStackTrace ();} break;

When using this method, you must note that normal users do not have the permission to execute reboot and shutdown, and naturally cannot shut down or restart the system. The Android device used must have been root. The above code and the su command are used to obtain administrator permissions. In addition, it should be noted that the premise for this method to work is that the reboot and shutdown files exist in the system/bin directory of your android system (in fact, the same principle as above, it is also a file called in the bin directory). I heard that most devices have the reboot and shutdown files. The available Android system does not have the shutdown file, so it cannot be used directly.

Runtime.getRuntime().exec(new String[]{"su","-c","shutdown"})

You can only run the following command to shut down the server (amazing p parameter)

Runtime.getRuntime().exec(new String[]{"su","-c","reboot -p"});

4. PowerManager reboot and reflection call PowerManagerService shutdown

1. PowerManager provides interfaces such as reboot. Therefore, it is relatively simple to restart with PowerManager.

PowerManager pManager = (PowerManager) getSystemService (Context. POWER_SERVICE); // restart to fastboot mode pManager. reboot ("");

2. The PowerManager class does not provide the shutdown interface for shutdown. Instead, it communicates with the PowerManagerService class through IBinder, a special communication mode in Android. PowerManagerService is the specific implementation of interfaces defined in the PowerManager class, and further calls the Power class to communicate with the next layer. The shutdown interface is implemented in PowerManagerService, and the power Service implements the shutdown function.
The implementation of PowerManager calls the Power service interface through IPowerManager. IPowerManager is a class automatically generated by AIDL files to facilitate remote communication. IPowerManage. aidl file directory

framework/base/core/java/android/os/IPowerManage.aidl 

IPowerManager implements the shutdown interface. Therefore, if we can obtain the IBinder of the Power service, we can call the shutdown method through reflection to implement the shutdown function.
It should be noted that ServiceManager manages the system's service programs. It stores the IBinder of all services and can obtain the IBinder of the service through the service name.
However, the ServiceManager class is also HIDE and needs reflection for calling. Two reflection calls can call the power Service's shutdown function.

Try {// get ServiceManager Class
 ServiceManager = Class. forName ("android. OS. serviceManager "); // obtain ServiceManager's getService Method getService = ServiceManager. getMethod ("getService", java. lang. string. class); // call getService to obtain RemoteService Object oRemoteService = getService. invoke (null, Context. POWER_SERVICE); // obtain IPowerManager. stub Class
 CStub = Class. forName ("android. OS. IPowerManager $ Stub "); // obtain the asInterface Method asInterface = cStub. getMethod ("asInterface", android. OS. IBinder. class); // call the asInterface method to obtain the IPowerManager Object oIPowerManager = asInterface. invoke (null, oRemoteService); // obtain the shutdown () Method shutdown = oIPowerManager. getClass (). getMethod ("shutdown", boolean. class, boolean. class); // call the shutdown () method. invoke (oIPowerManager, false, true);} catch (Exception e) {Log. e (TAG, e. toString (), e );}







Related Article

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.