newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);
還要加權限:
<uses-permission android:name="android.permission.SHUTDOWN" />
此方法有些版本不合適
2:
Intent newIntent = new Intent(Intent.ACTION_SHUTDOWN);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);
這種方法筆者試過,運行時出錯
3:
try {
//獲得ServiceManager類
Class<?> ServiceManager = Class
.forName("android.os.ServiceManager");
//獲得ServiceManager的getService方法
Method getService = ServiceManager.getMethod("getService", java.lang.String.class);
//調用getService獲取RemoteService
Object oRemoteService = getService.invoke(null,Context.POWER_SERVICE);
//獲得IPowerManager.Stub類
Class<?> cStub = Class
.forName("android.os.IPowerManager$Stub");
//獲得asInterface方法
Method asInterface = cStub.getMethod("asInterface", android.os.IBinder.class);
//調用asInterface方法獲取IPowerManager對象
Object oIPowerManager = asInterface.invoke(null, oRemoteService);
//獲得shutdown()方法
Method shutdown = oIPowerManager.getClass().getMethod("shutdown",boolean.class,boolean.class);
//調用shutdown()方法
shutdown.invoke(oIPowerManager,false,true);
} catch (Exception e) {
Log.e("shutdown", e.toString(), e);
}
利用反射調用oIPowerManager方法,此種方法在有些機型上是可以的,但有些機型上在Method shutdown = oIPowerManager.getClass().getMethod("shutdown",boolean.class,boolean.class);時會報出java.lang.NoSuchMethodException: shutdown [boolean, boolean] 錯誤,可能是這些機型不存在此方法
4:
Intent intent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
// 源碼中"android.intent.action.ACTION_REQUEST_SHUTDOWN“ 就是 Intent.ACTION_REQUEST_SHUTDOWN方法
intent.putExtra("android.intent.extra.KEY_CONFIRM", false);
// 源碼中"android.intent.extra.KEY_CONFIRM"就是 Intent.EXTRA_KEY_CONFIRM方法
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
這種方法筆者試過適用於大部分機型