Android在代码中实现重启(reboot)


Android在代码中实现重启(reboot) ,直接上代码:

    public void rebootAction(){
        new AlertDialog.Builder(this)
            .setTitle("Warning")
            .setMessage("Sure to reboot?")
            .setNegativeButton("Cancel", null)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String cmd = "su -c reboot";
                    try {
                        Runtime.getRuntime().exec(cmd);
                    } catch (Exception e){
                        Toast.makeText(getApplicationContext(), "Error! Fail to reboot.", Toast.LENGTH_SHORT).show();
                    }
                }
            })
            .show();
    }

还有一种方法,但是需要系统级程序才可以使用,否则会提示权限不够。

          try {
                Intent intent = new Intent(Intent.ACTION_REBOOT);
                intent.putExtra("nowait", 1);
                intent.putExtra("interval", 1);
                intent.putExtra("window", 0);
                this.sendBroadcast(intent);
            } catch (Exception e){
                new AlertDialog.Builder(this).setTitle("Error").setMessage(e.getMessage()).setPositiveButton("OK", null).show();
            }

在普通app中调用会报错:

java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.REBOOT from pid=11892, uid=10146

相关内容

    暂无相关文章