最近在网上看了一些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. SQLSERVER语句 in和exists哪个效率高本人测试证明
  2. Node.js开发者最常范的10个错误
  3. js 把数字转成2 ,8,16进制的方法
  4. JDBC学习1:详解JDBC使用
  5. poj 1006:Biorhythms(水题,经典题,中国剩余定理)
  6. String 与 byte[]相互转换
  7. C++ List的用法(整理)
  8. github 向导/介绍
  9. 【转】Android的材料设计兼容库(Design Support Library)
  10. spring 编程式事务管理和声明式事务管理
  11. Spring反射机制
  12. 64位gcc编译32位汇编
  13. Day07_面向对象第二天
  14. System.Web.HttpException: 无法向会话状态服务器发出会话状态请求
  15. HTTP请求WebTool
  16. 排序算法c语言描述---冒泡排序
  17. Angular2 + NativeScript 跨平台开发笔记(一)
  18. 微信iOS消息拦截插件教程-Tweak HelloWorld
  19. LibreOJ NOI Round #1 Day 1 B. 失控的未来交通工具
  20. 初学JSP

热门文章

  1. 禁用 Windows Azure 网站中的 ARR 实例关联
  2. HDU 1862 EXCEL次序 (排序水问题)
  3. STL之stack
  4. 移动端rem,scale动态设置
  5. ACE编译
  6. ITextSharp 初次接触
  7. CentOS 6 用SVN自动提交文件到web服务器
  8. JavaScript弹出框
  9. From Ontology to Semantic Web
  10. 【笨木头Lua专栏】基础补充08:协同程序之resume-yield间的数据返回