Android implementation shutdown and restart of several ways (recommended) _android

Source: Internet
Author: User
Tags stub

Let's look at how Android can shut down, reboot, and in Android, which often requires an administrator level, or root

There are several ways to implement Android:

The default SDK does not provide the application developer direct Android system shutdown or restart API interface, generally speaking, the implementation of the Android system shutdown or reboot, requires higher privileges (System permissions or even root permissions). Therefore, in the General app, if you want to implement shutdown or restart functions, either declare the system permissions in the app, or through some kind of "indirect" way, such as broadcast or reflection, to indirectly implement the system shutdown or reboot. In addition, it is to put in the source environment for the compilation, this has the advantage of, that is, can directly invoke the android in the Non-public API, this is ECLIPSE+SDK not achieve the effect. Here are some of the ways I've tried myself:

I. Send a broadcast mode

Broadcast is one of the four basic components of Android, which we often call broadcasting. The Android system itself contains many broadcasts, always listening to every broadcast registered in the system and ready to respond. Among them, there are broadcasts 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 reboot operations. Action_request and Action_reboot are Intent.java are declared two 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 under the source/frameworks/base/core/java/android/content/intent.java. The implementation method is as follows

Broadcast mode shutdown 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);
Where false to True, will eject the Shutdown confirmation window
intent.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

The points to be noted are:

First, as mentioned earlier, you need to elevate the app to system permissions by adding the following code to the Androidmenifest.xml

Android:shareduserid= "Android.uid.system"

Second, you also need to add shutdown permissions

Third, in Eclipse, the Intent.action_request_shutdown and intent.extra_key_confirm in the code do the error in the Eclipse IDE or, as previously said, these two properties are not open to the upper level, If you put the project in the source code for compilation, can be compiled through.

Four, because need to compile project in source code, so need to write Mk file for project, add android.mk file under Project root directory, the content is as follows:

Local_path:= $ (call My-dir)
include $ (clear_vars)
local_module_tags: = Optional
Local_src_files: = $ (call All-java-files-under, SRC)
local_package_name: = Poweractiondemo
local_certificate: = Platform
include $ (Build_package)

Finally, the generated APK file will be compiled and the functionality can be validated by the ADB push onto the machine.

Two. Start system service through init.rc to run SH file

The first application invoked after Android started the filesystem is/init, a very important part of this file is parsing the init.rc and init.xxx.rc, and then performing the parsed task. And init.rc, you can do some simple initialization during the initialization of the system. With this, you can write a simple shutdown or restart of the sh script file, through System init resolution, to perform the appropriate shutdown or restart operation.

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

Restart the script system_reboot.sh, as follows:

#!/system/bin/sh
Reboot

Shutdown Scripts system_shutdown.sh

#!/system/bin/sh
Reboot-p

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

2. Write android.mk compilation script, the purpose is to compile the source code, the two sh files together into the/system/bin directory

Local_path: = $ (call My-dir)

Include $ (clear_vars)
local_prebuilt_executables: = system_shutdown.sh system_reboot.sh
local_module_tags: = optional
include $ (build_multi_prebuilt)

3. Init.rc add shutdown and restart services, open the Init.rc file, add the following on the last side:

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

The oneshot option means that the service is only started once, and if the oneshot option is not available, the executable will always exist-if the executable is killed, it will be restarted.

Disabled indicates that the service is disabled and will not start automatically when it is powered on, but it can be started manually in the application.

4. Create a new directory, such as Poweraction, will be above the android.mk, system_shutdown.sh, system_ Reboot.sh in this directory, and then copy the Poweraction directory to the Android system, such as the device path below. Then, compile the Android source code, after compiling the source code, to see if the generated Out/.../system/bin below contains system_shutdown.sh, system_reboot.sh two sh files, and if so, compile successfully.

5. Finally, start the system service to shutdown or reboot.

Start the system service to shutdown 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

Three. Runtime Call Linux-shell

We know that runtime this Java class can be used to invoke and execute shell commands, while the Android virtual machine supports the Linux-shell language, and based on this, runtime can be used to perform shutdown or restart shell commands. This is roughly the same as the method described above. The functional code is as follows:

Runtime execution Linux-shell case
r.id.shutdown_btn3:
try{
log.v (TAG, "root Runtime->shutdown");
Process proc =runtime.getruntime (). EXEC (new string[]{"Su", "-C", "Shutdown"}); Shutdown
Process proc =runtime.getruntime (). EXEC (new string[]{"Su", "-C", "Reboot-p"});//Shutdown
proc.waitfor ();
} catch (Exception e) {
e.printstacktrace ();
}
break;
Case R.ID.REBOOT_BTN3:
try { 
log.v (TAG, "root runtime->reboot");
Process proc =runtime.getruntime (). EXEC (new string[]{"Su", "-C", "reboot"}); Shutdown
proc.waitfor ();
} catch (Exception ex) {
ex.printstacktrace ();
}
Break

Using this method, it is important to note that ordinary users do not have permission to perform reboot and shutdown, and that it is not automatically possible to shut down or reboot. The Android device that you use must already be root, and the code above adds the SU command in order to get administrator privileges. Another point to note is that the method works if you have reboot and shutdown files in the System/bin directory of your Android system (in fact, the same as the above, the call to the file in the bin directory), I heard that most of the equipment exists reboot and shutdown these two files, the use of the Android system is not shutdown files, so, can not directly use

Runtime.getruntime (). EXEC (new string[]{"Su", "-C", "Shutdown"})

You can only perform the following command to shutdown (good Magic p parameters)

Runtime.getruntime (). EXEC (new string[]{"Su", "-C", "Reboot-p"});

Four. PowerManager reboot and reflection call Powermanagerservice shutdown

1. PowerManager provides reboot interface, therefore, the use of PowerManager to achieve a reboot, it is relatively simple.

PowerManager pmanager= (PowerManager) Getsystemservice (Context.power_service); Reboot to FastBoot mode
Pmanager.reboot ("");

2. The PowerManager class does not provide a shutdown interface for shutdown, but rather communicates with the Powermanagerservice class by ibinder the unique mode of communication in this Android. Powermanagerservice is a concrete implementation of the interface defined in the PowerManager class and further invokes the power class to communicate with the next layer. The shutdown interface is implemented in Powermanagerservice, and the power service realizes the shutdown function.
The PowerManager implementation invokes the interface of the power service through Ipowermanager. Ipowermanager is a class that is automatically generated by aidl files and facilitates remote communication. Ipowermanage.aidl file Directory

Framework/base/core/java/android/os/ipowermanage.aidl

Ipowermanager implements the shutdown interface, so if we can get the ibinder of the power service, we can call the shutdown method through reflection to realize the shutdown function.

It should be noted that ServiceManager manages the system's service program, which holds the ibinder of all services, and obtains the ibinder of the service through the service name.

But the ServiceManager class is also hide and requires reflection to be invoked. Two times, through two reflection calls, can invoke power service implementation of the shutdown function.

 try {//Get ServiceManager class class> ServiceManager = Class. forname ("Android.os.Service
Manager ");
The GetService method for obtaining servicemanager is GetService = Servicemanager.getmethod ("GetService", Java.lang.String.class);
Call GetService to get remoteservice Object Oremoteservice = Getservice.invoke (Null,context.power_service);
Get Ipowermanager.stub class class> cstub = Class. forname ("Android.os.ipowermanager$stub");
Obtain Asinterface Method asinterface = Cstub.getmethod ("Asinterface", Android.os.IBinder.class);
Call the Asinterface method to get the Ipowermanager object oipowermanager = Asinterface.invoke (null, oremoteservice);
Gets the shutdown () method shutdown = Oipowermanager.getclass (). GetMethod ("Shutdown", boolean.class,boolean.class); 
Call the Shutdown () method Shutdown.invoke (Oipowermanager,false,true); 
catch (Exception e) {log.e (TAG, e.tostring (), E); }

The above is a small set of Android to introduce the implementation of shutdown and restart of several ways (recommended), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.