android程式控制系統關機,在這裡給一種實作方法,相信會幫到大家。
首先,控制系統關機需要擷取android系統權限,要系統簽名,不然程式無法控制:
1,清單檔案AndroidManifest.xml中
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.zksj.robot"
android:versionCode="1"
android:sharedUserId="android.uid.system"
android:versionName="1.0.0" >
要加上紅色的這個系統簽名,
2,在根目錄下建立android.mk檔案,檔案中需要加一句話
LOCAL_CERTIFICATE := platform
3,代碼
package com.rebootdevice;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.lang.reflect.Method;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// PowerManager powerManager =(PowerManager) MainActivity.this.getSystemService(Context.POWER_SERVICE);
// powerManager.reboot("adb reboot");
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());
}
}
});
}
}
資源下載下傳路徑:http://download.csdn.net/detail/qq_29586601/9801516