android apk应用关机功能的开发

来源:互联网 发布:淘宝网秧歌服山东菏泽 编辑:程序博客网 时间:2024/06/05 23:58
1.Intent newIntent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN); 
        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);

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


原创粉丝点击