以前做过一个MCU升级的小项目,其中有一个在升级完后需要对话框提示是否重启,
找了一些资料后终于实验成功,废话少说,直接上代码:
protected void showResetDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.dialog_system_message);
builder.setNegativeButton(R.string.dialog_negtive,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "ok!", Toast.LENGTH_SHORT);
dialog.dismiss();
}
});
builder.setPositiveButton(R.string.dialog_postive,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent reboot = new Intent(Intent.ACTION_REBOOT);
reboot.setAction(Intent.ACTION_REBOOT);
reboot.putExtra("nowait", 1);
reboot.putExtra("interval", 1);
reboot.putExtra("window", 0);
sendBroadcast(reboot);
dialog.dismiss();
}
});
builder.create().show();
}
这其中关键的重启代码就是如下的这个广播:
Intent reboot = new Intent(Intent.ACTION_REBOOT);
reboot.setAction(Intent.ACTION_REBOOT);
reboot.putExtra("nowait", 1);
reboot.putExtra("interval", 1);
reboot.putExtra("window", 0);
sendBroadcast(reboot);
最后,也是最重要 的一条,就是要在manifest.xml文件中添加权限:
<uses-permission android:name="android.permission.REBOOT"/>