android 實現代碼關機


開始從網上搜索,通過發action的方式實現,不過一直沒有成功。
Intent intent = new Intent();  
intent.setAction(Intent.ACTION_SHUTDOWN);
sendBroadcast(intent);
加權限
<uses-permission  android:name="android.permission.SHUTDOWN" tools:ignore="ProtectedPermissions" />

若有成功的同學,希望留言相告,謝謝。

這里介紹我自己的方法。

1. power服務實現了關機功能
framework/base/services/java/com/android/server/power/PowerManagerService.java
   
    /**
     * Shuts down the device.
     *
     * @param confirm If true, shows a shutdown confirmation dialog.
     * @param wait If true, this call waits for the shutdown to complete and does not return.
     */
    @Override // Binder call
    public void shutdown(boolean confirm, boolean wait) {
        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);

        final long ident = Binder.clearCallingIdentity();
        try {
            shutdownOrRebootInternal(true, confirm, null, wait);
        } finally {
            Binder.restoreCallingIdentity(ident);
        }
    }


2. PowerManager提供了reboot等接口,沒有提供shutdown接口。
若是重啟,實現就很簡單:
   PowerManager pm = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
   pm.reboot();
但是shutdown沒有實現,PowerManager的實現通過IPowerManager來調用Power服務的接口。
IPowerManager是AIDL文件自動生成的類,便於遠程通信。IPowerManage.aidl文件目錄framework/base/core/java/android/os/IPowerManage.aidl

3. IPowerManager實現了shutdown接口,這里只要獲得Power服務的IBinder,通過反射調用shutdown方法就能實現關機功能。
ServiceManager管理着系統的服務程序,它保存着所有服務的IBinder,通過服務名就能獲取到這個服務的IBinder。
而ServiceManager這個類也是HIDE的,也需要反射進行調用。


代碼實現:

       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(TAG, e.toString(), e);        
       }




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM