android关机、重启等电源键功能实现

2019-07-14 02:02发布

背景:小黑,玩机刷机日常关机重启少不了使用长按电源键,一个按一个心疼,这强迫症可能很多人有,担心按坏了。手机自带又没有这般快捷键,所以就想下载个关机重启的软件来释放电源键,无奈网上好用的软件广告太多或经常更新,烦人,所以就想自己写个纯洁的程序来自己用
程序截图 第一张:程序主界面
第二张:确认对话框


源代码: package com.xiaohei9.boot; import java.io.IOException; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; /** * 实现手机电源键功能 * @author 小黑 * */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 创建Layout并设置内容垂直排布 LinearLayout layout = new LinearLayout(this); layout.setOrientation(1); this.addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); // 向Layout增加内容 layout.addView(makeButton("快速关机", new String[]{"su","-c","reboot -p"})); layout.addView(makeButton("快速重启", new String[]{"su","-c","reboot"})); layout.addView(makeButton("恢复模式", new String[]{"su","-c","reboot recovery"})); layout.addView(makeButton("引导模式", new String[]{"su","-c","reboot bootloader"})); layout.addView(makeText("注意:本程序仅供学习与参考,需root")); layout.addView(makeText("作者:小黑 ch_yongming@qq.com")); } /** * 创建一个命令按钮 * @param text 按钮显示的文字 * @param cmd 按钮执行的命令 * @return 返回创建的按钮 */ private Button makeButton(final String text, final String[] cmd) { final Context context = this; Button btn = new Button(context); btn.setText(text); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("小黑提示"); builder.setMessage("确认继续【" + text + "】"); builder.setNegativeButton("取消", null); builder.setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int idx) { // 执行命令 execCmd(cmd); } }); builder.show(); } }); return btn; } /** * 创建一个文本 * @param text 文本所显示内容 * @return 返回创建的文件 */ private TextView makeText(String text) { TextView tv = new TextView(this); tv.setText(text); return tv; } /** * 执行命令 * @param cmd 命令 */ private void execCmd(String[] cmd) { try { Process proc = Runtime.getRuntime().exec(cmd); proc.waitFor(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
本程序下载地址(小黑电源键.apk) http://apk.xiaohei9.cn/