user2879697
user2879697

Reputation: 69

How to shut down android device programatically using Intent or PowerManager API?

I am trying to shutdown my custom android device programatically. I am using the below code to do the same, but it is restarting again.I want the device to be completely shut down.

Intent intent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
            intent.putExtra("android.intent.extra.KEY_CONFIRM", false);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

How to achieve complete shut down i,e avoid auto restart?

Note: I have signed app with platform signatures. Placed it in /system/app Added <uses-permission android:name="android.permission.SHUTDOWN" /> permission in manifest.

Upvotes: 0

Views: 4093

Answers (4)

Mark Lane
Mark Lane

Reputation: 214

None of these solutions actually work. You do not need to be a Device Owner app but you must have a Firmware Signed app to have the appropriate permissions. Below works for Android 8.1. It must be a Request_Shutdown without user interaction and created as a PendingIntent launched by the AlarmManager.

  Intent intent = new Intent("com.android.internal.intent.action.REQUEST_SHUTDOWN"); 
            intent.PutExtra("android.intent.extra.KEY_CONFIRM", false);
          
            intent.AddFlags(ActivityFlags.ClearTop
                            | ActivityFlags.ClearTask
                            | ActivityFlags.NewTask);
            PendingIntent pendingIntent = PendingIntent.GetActivity(Application.Context, 0, intent, PendingIntentFlags.OneShot);
            AlarmManager _alarmManager = (AlarmManager)Application.Context.GetSystemService(Context.AlarmService);
            long milliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();
            _alarmManager.Set(AlarmType.Rtc, milliseconds + 5000, pendingIntent);

Upvotes: 0

Renan Eberle Costella
Renan Eberle Costella

Reputation: 117

If your device is rooted, you can use this code for shutdown

Java.Lang.Runtime.GetRuntime().Exec(new String[] { "/system/xbin/su", "-c", "reboot -p" });

and use this code for Reboot

Java.Lang.Runtime.GetRuntime().Exec(new String[] { "/system/xbin/su", "-c", "reboot now" });

I use this on Xamarin.Android

Upvotes: 1

Manish Singh Rana
Manish Singh Rana

Reputation: 872

Intent i = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
i.putExtra("android.intent.extra.KEY_CONFIRM", true);
startActivity(i);

Upvotes: 0

Mande Kira
Mande Kira

Reputation: 190

Try this code, it might help.

try {
    Process p = Runtime.getRuntime().exec(new String[]{ "su", "-c", "reboot" });
 p.waitFor();
} catch (Exception ex) {
    ex.printStackTrace();
}

Upvotes: 0

Related Questions