最近在网上看了一些Android下实现自动关机的方法,有的不行,有的只适用一些机型,有的适用于大部分机型,笔者在此总结一下

法一:

Intent newIntent = new Intent(Intent.ACTION_SHUTDOWN);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);

这种方法笔者试过,运行时出错

法二:

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] 错误,可能是这些机型不存在此方法

法三:

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);

这种方法笔者试过适用于大部分机型

更多相关文章

  1. Mac完整卸载Android(安卓)Studio的方法
  2. 查看Android(安卓)ADT Plugin版本的方法
  3. 【Android】Android处理Home键方法小结
  4. 在Android中实现全屏显示的方法
  5. Android常用方法——获取系统信息
  6. Android(安卓)DEX 方法超过64K限制
  7. Activity详解 Intent显式跳转和隐式跳转, 及多个Activity之间传
  8. 浅谈Java中Collections.sort对List排序的两种方法
  9. Python list sort方法的具体使用

随机推荐

  1. Android Studio中的六种依赖
  2. 如何让你的手机屏幕固定横屏和竖屏
  3. Android 中文API (92) —— MenuInflater
  4. 腾讯微博java(android) sdk 标签相关api
  5. Android下intent的setdata、settype和set
  6. Android 开发环境的搭建 个人笔记
  7. 4412开发板Android和LinuxQT烧写方法
  8. Fedora17 64位 android "failed to creat
  9. 朝花夕拾----新组件的学习和使用
  10. 【ALearning】第二章 Android工程相关知