博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[置顶] Android下实现自动关机的方法总结
阅读量:7078 次
发布时间:2019-06-28

本文共 1663 字,大约阅读时间需要 5 分钟。

最近在网上看了一些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);

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

 

转载地址:http://qidml.baihongyu.com/

你可能感兴趣的文章
linux日志(常用命令)
查看>>
history
查看>>
Leetcode: Arranging Coins
查看>>
HttpUtil 【判断网络连接的封装类】
查看>>
【转】TCP分段与IP分片
查看>>
iOS 多线程 NSOperation、NSOperationQueue
查看>>
delphi执行查询语句时的进度条怎么做
查看>>
CF 335A(Banana-贪心-priority_queue是大根堆)
查看>>
python的memcache使用如果对key设置了一个int型
查看>>
Leetcode: Longest Substring with At Most Two Distinct Characters
查看>>
173. Binary Search Tree Iterator
查看>>
[python基础知识]python内置函数map/reduce/filter
查看>>
基因家族收缩和扩张分析 & Selective loss pathway & 泛基因组
查看>>
HDU2089 ------不要62(数位dp)
查看>>
hdu4756 Install Air Conditioning(MST + 树形DP)
查看>>
Android爬坑之旅之FileProvider(Failed to find configured root that contains)
查看>>
(四)Thread.join的作用和原理
查看>>
Watercolor Logos
查看>>
网络安全与机器学习(一):网络安全中的机器学习算法
查看>>
Egret场景切换管理类切换和单例使用方法
查看>>