歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android在代碼中實現重啟(reboot)

Android在代碼中實現重啟(reboot)

日期:2017/3/1 9:48:05   编辑:Linux編程

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

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved