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