您的位置:首页 > 移动开发 > Android开发

Android关机和重启功能的实现

2016-10-12 17:25 501 查看
 最近使用手机时候发现,手机的电源按键不灵敏了。因为主要作为测试机使用所以经常会为了,省电经常会用到关机或者重启。想着就自己写了一个简单的小程序。本以为很简单,结果发现网上的很多看不懂,要么就是给了几行代码,测试了根本不成功。于是乎一气之下就自己弄一个,一来为了自己查阅方便,二来可以给有同样需求的朋友一个参考。
          声明:由于关机重启属于敏感操作,所以前提手机必须root。至于如何root不是本文的重点,root的渠道有很多,可以自己去尝试。看代码:

package com.shutdown;

import java.io.IOException;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/**
* android 关机和重启服务
* 需要获取root权限
* @author NanFeiLong
* @date 2016年10月11日
*/

public class MainActivity extends Activity {
private Button mShutDownBt;
private Button mRestartBt;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mShutDownBt = (Button) findViewById(R.id.btn_shutdown);//关机
mShutDownBt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String[] arrayShutDown = {"su","-c","reboot -p"};
closePhone(MainActivity.this,arrayShutDown);
}
});

mRestartBt = (Button) findViewById(R.id.btn_restart);//重启
mRestartBt.setOnClickListener(new OnClickListener() {
String[] arrayRestart = {"su","-c","reboot"};
@Override
public void onClick(View v) {
closePhone(MainActivity.this, arrayRestart);
}
});

}

@SuppressWarnings("unused")
private void closePhone(Context context,String[] shutdown){
try {
Process	 process = Runtime.getRuntime().exec(shutdown);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<Button
android:id="@+id/btn_shutdown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginTop="22dp"
android:text="点击关机" />

<Button
android:id="@+id/btn_restart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/btn_shutdown"
android:layout_marginTop="14dp"
android:text="点击重启" />

</RelativeLayout>


至此一个关机和重启的小功能就完成了。是不是很简单。想要源码的可以去这里下载
源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息