1、在manifest.xml 中添加权限
<uses-permission android:name="android.permission.ACCESS_SUPERUSER" />
2、新建DeviceAutoRebootService文件,并在manifest.xml 添加service
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class DeviceAutoRebootService extends Service {
private ScheduledExecutorService threadPool = null;
private int betweenTime = 59;//间隔59秒执行一次
private int delayTime = 2;//线程池开启5秒后执行
private String time = "03:30";//重启时间一
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.CHINA);
String[] rebootArray = {"su", "-c", "reboot"};//执行重启的命令
String dateStr = "";//获取的时间
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
threadPool = Executors.newScheduledThreadPool(3);
executeShutDown();
}
public void executeShutDown() {
threadPool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
dateStr = sdf.format(new Date());
Log.d("重启", dateStr.equals(time) + "=" + dateStr);
// root机子
if (dateStr.equals(time)) {
try {
Runtime.getRuntime().exec(rebootArray);
exec("reboot");
} catch (IOException io) {
io.printStackTrace();
}
}
}
}, delayTime, betweenTime, TimeUnit.SECONDS);
}
private String exec(String command) {
Process process = null;
BufferedReader reader = null;
InputStreamReader is = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec("su");
is = new InputStreamReader(process.getInputStream());
reader = new BufferedReader(is);
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command + "\n");
os.writeBytes("exit\n");
os.flush();
int read;
char[] buffer = new char[4096];
StringBuilder output = new StringBuilder();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
process.waitFor();
return output.toString();
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
} finally {
try {
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
if (reader != null) {
reader.close();
}
if (process != null) {
process.destroy();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onDestroy() {
threadPool.shutdown();
threadPool = null;
dateStr = null;
super.onDestroy();
}
}
3、MainActivity onCreate方法中开启service
startService(new Intent(MainActivity.this, DeviceAutoRebootService.class));