Android root poweroff

2019-04-07 02:50发布

问题:

On my android app for root user, I perform a shutdown with

su reboot -p

It works ok, but I noticed that the phone is shutdown almost instantly (as opposed from showing the shutdown animation, and probably doing other stuff).

Is this the correct way to shutdown an android phone programmatically? Are there some critical code that requires to be executed before shutdown?

回答1:

In the Android source code, you can find the following:

/**
 * Low-level function turn the device off immediately, without trying
 * to be clean.  Most people should use
 * {@link android.internal.app.ShutdownThread} for a clean shutdown.
 *
 * @deprecated
 * @hide
 */
@Deprecated
public static native void shutdown();

I think that this native function corresponds to your su reboot -p. Moreover, you can see from the quoted code comment that you should use ShutdownThread to do a clean shutdown.

In ShutdownThread, Android does a bunch of things.

  • It shuts down ActivityManager. I think shutting down ActivityManager means that all activities will pass necessary lifecycle and, thus, the states of activities will be stored. But I'm not sure. I did not check.
  • Then, Android turns off the cellular radio interface.
  • After that, it turns off Bluetooth.
  • Finally, it tries to shut MountService down.

Thus, you can see that it's wrong to do su reboot -p.



回答2:

If your app is rooted, then run the following as root:

am start -a android.intent.action.ACTION_REQUEST_SHUTDOWN



回答3:

See here: http://developer.android.com/reference/android/os/PowerManager.html

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
pm.reboot("Because I want you to reboot!")

This should work.



回答4:

On Android 4.3 or later, there's probably a better way to shut the device down.

Your app doesn't need to be installed as a system app, but it must have root privileges. You can simply run this one command as root in order to shut the device down:

svc power shutdown

I thank Firelord for his answer elsewhere which inspired me to discover the existence of this shell command.

I think this will do a graceful shutdown, but I'm not sure. Maybe it will do an abrupt shutdown. Please test, and then edit this answer to clarify.

Also, the above shell command does not work in Android 4.2.2 or earlier. The help text doesn't mention it. svc rejects the command as invalid and shows some help text in order to try to be helpful.