最近要复现一个BUG,需要无限重启进行测试,就花费点时间写个简单的应用来实现手机重启、关机功能。
注:因为需要很高的权限才可以正常使用,所以必须具有手机平台编译系统,手机开发者使用,本人亲测成功。
首先在app开发工具中新建项目AppReboot;在xml中定义重启、关机按钮;下面就是唯一Activity代码:
public class RebootActivity extends Activity implements OnClickListener{
private Button rebootclick,shutdownclick;
// 是否显示关机确认的对话框
// false 不显示确认关机的对话框,直接关机
// true 显示确认关机的对话框,让用户选择是否确认关机
public static final boolean showShutdownDialog = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rebootclick=(Button) findViewById(R.id.reboot_click);
shutdownclick=(Button) findViewById(R.id.shutdown_click);
rebootclick.setOnClickListener(this);
shutdownclick.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.reboot_click:
onReboot(rebootclick);
break;
case R.id.shutdown_click:
onShutdown(shutdownclick);
break;
default:
break;
}
}
/**
* 发送广播.
* @param view
*/
public void onReboot(View view) {
Intent reboot = new Intent(Intent.ACTION_REBOOT);
reboot.putExtra("nowait", 1);
reboot.putExtra("interval", 1);
reboot.putExtra("window", 0);
sendBroadcast(reboot);
}
/**
* 启动 Activity.
* @param view
*/
public void onShutdown(View view) {
Intent shutdown = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
shutdown.putExtra(Intent.EXTRA_KEY_CONFIRM, showShutdownDialog);
shutdown.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(shutdown);
}
}
AndroidManifest.xml中要增加 android:sharedUserId="android.uid.system"属性
然后是Android.mk文件如下:
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := optional
LOCAL_CERTIFICATE := platform
LOCAL_SRC_FILES := $(call all-java-files-under, src)
LOCAL_PACKAGE_NAME := reboot
#LOCAL_PROGUARD_FLAG_FILES := proguard.flags
include $(BUILD_PACKAGE)
##################################################
include $(CLEAR_VARS)
# Use the folloing include to make our test apk.
include $(call all-makefiles-under,$(LOCAL_PATH))
最后建议style.xml删除,在AndroidManifest不使用主题,这样编译就不会因为主题风格而报错了。