Android定时关机

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_38752761/article/details/78233396

第一个小项目练练手吧,,大多数内容都是参考别人的。

1.设置关机时间。设置时间用的是TimePicker ,

      tp_time1 = (TimePicker) findViewById(R.id.tp_time1);
      tp_time1.setIs24HourView(true);

      Button btn_settime1=(Button) findViewById(R.id.btn_settime1);

      btn_settime1.setOnClickListener(new OnClickListener() {

    @Override
public void onClick(View v) {
// TODO Auto-generated method stub
Integer hour1 = tp_time1.getCurrentHour();
Integer minute1 = tp_time1.getCurrentMinute();

String hourOff = hour1.toString();
String minuteOff = minute1.toString();

Intent intent = new Intent();
intent.putExtra("hourOff", hourOff);
intent.putExtra("minuteOff", minuteOff);

setResult(1, intent);

}

2.启动一个服务来获取当前手机系统的世界,并将设置的时间参数传给服务,来判断当前时间是否与设置的时间相同

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 1) {
hourOff1 = data.getStringExtra("hourOff");
minuteOff1 = data.getStringExtra("minuteOff");
hourOn1 = data.getStringExtra("hourOn");
minuteOn1 = data.getStringExtra("minuteOn");
if (hourOff1 != null && minuteOff1 != null) {
tv_time1.setText(hourOff1 + ":" + minuteOff1 + "-" + hourOn1
+ ":" + minuteOn1);
}
}

}

if (hourOff1 != null && minuteOff1 != null) {
int hour1 = Integer.valueOf(hourOff1);
int minute1 = Integer.valueOf(minuteOff1);
long setTimeMillis1 = timeToMillis(hour1, minute1);
serviceIntent1.putExtra("settime1", setTimeMillis1);
if (sw_start1.isChecked()) {
startService(serviceIntent1);
}else{
stopService(serviceIntent1);
}
}else{
serviceIntent1.putExtra("settime1", 0);
if(sw_start1.isChecked())

startService(serviceIntent1);
}
}

其中,sw_start1是开关控件,timeToMillis()方法是将获取到的时间转换成毫秒

 

3.在服务中来判断当前时间是否为关机时间

public void onStart(Intent intent, int startId) {
getLastTimeSet();
setTimeMillis1 = intent.getLongExtra("settime1", getLastTimeSet1());
new Thread() {
public void run() {
//while (true) {
long currentTimeMillis = getCurrentTimeMillis();
if (currentTimeMillis == setTimeMillis1) {
powerOff();
}
//}
};
}.start();
super.onStart(intent, startId);
}

获取当前时间的方法:

public long getCurrentTimeMillis() {
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return timeToMillis(hour, minute);
}

     关机的方法

public void powerOff() {
try {
// /需要root权限后才能用这个方法
System.out.println("执行关机 ");
Process pro = Runtime.getRuntime().exec(
new String[] { "su", "-c", "reboot -p" });
pro.waitFor();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("执行关机失败");
e.printStackTrace();
}
}

代码量交少,主要的关机功能是参考的网上的,但是需要手机root后才能用。。。一直想找不用root的关机方法,但是没找到,不知道有没有。不足之处还请指教

展开阅读全文

没有更多推荐了,返回首页