public class PowerUtil { private static final SimpleDateFormat FORMAT = new SimpleDateFormat("HHmm"); //调用执行方法 public static void setShutDownAt(String timeValue, Context context) { Calendar settingCalendar = Calendar.getInstance(); try { settingCalendar.setTime(FORMAT.parse(timeValue)); } catch (ParseException e) { Log.e("setShutDownAt", e.getLocalizedMessage()); e.printStackTrace(); return; } Calendar currentCalendar = Calendar.getInstance(); settingCalendar.set(Calendar.YEAR, currentCalendar.get(Calendar.YEAR)); settingCalendar.set(Calendar.MONTH, currentCalendar.get(Calendar.MONTH)); settingCalendar.set(Calendar.DAY_OF_MONTH, currentCalendar.get(Calendar.DAY_OF_MONTH)); if (settingCalendar.before(currentCalendar)) { settingCalendar.add(Calendar.DAY_OF_MONTH, 1); } // int year = settingCalendar.get(Calendar.YEAR); // int month = settingCalendar.get(Calendar.MONTH); // int day = settingCalendar.get(Calendar.DAY_OF_MONTH); // int hour = settingCalendar.get(Calendar.HOUR_OF_DAY); // int minute = settingCalendar.get(Calendar.MINUTE); // int seconds = settingCalendar.get(Calendar.SECOND); Log.i("定时关机时间", "最终设置关机时间=" + settingCalendar.getTime()); Intent intent = new Intent(context, ActionBroadCast.class); PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0); AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, settingCalendar.getTimeInMillis(), pi); } }
//广播类
public class ActionBroadCast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // String action = "com.android.internal.intent.action.REQUEST_SHUTDOWN"; // if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) { // action = "android.intent.action.ACTION_REQUEST_SHUTDOWN"; // } // Intent intent1 = new Intent(action); // intent1.putExtra("android.intent.extra.KEY_CONFIRM", false); // intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // context.startActivity(intent1); FileLogUtil.fileLog("ActionBroadCast","-------定时关机启动-----"); shutDown(); } private void shutDown() { try { //Process proc =Runtime.getRuntime().exec(new String[]{"su","-c","shutdown"}); //关机 // Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot -p"}); //关机 Process proc = Runtime.getRuntime().exec(new String[]{"reboot" ,"-p"}); //关机 proc.waitFor(); } catch (Exception e) { e.printStackTrace(); } } }
//AndroidManifest 注册静态广播
<receiver android:name=".receiver.ActionBroadCast">//ActionBroadCast路径 <intent-filter> <action android:name="android.intent.action.ALARM_CLOCK" /> </intent-filter> </receiver>