启动此线程时,我的Android应用程序崩溃。
此线程应重新启动手机。当我启动它时,不要重新启动手机,并且在LOG中有以下文本:
这是我的主题。
class Reboot implements Runnable {
private volatile boolean cancelled;
Boolean checkRebootHeb;
Boolean checkRebootQuo;
int jourDemandeeInt;
String jourDemandeeString;
String weekDay;
int dayOfWeek;
SimpleDateFormat df;
String heure;
String dayOfWeekString;
String heureDemandee;
Calendar c;
public Reboot(Boolean VARcheckReboot, Boolean VARcheckRebootQuo, int VARjour, String VARtextReboot) {
checkRebootHeb = VARcheckReboot;
checkRebootQuo = VARcheckRebootQuo;
jourDemandeeInt = VARjour;
heureDemandee = VARtextReboot;
}
@Override
public void run() {
while (!cancelled) {
if (jourDemandeeInt == 0){
jourDemandeeString = "Lundi";
}
if (jourDemandeeInt == 1){
jourDemandeeString = "Mardi";
}
if (jourDemandeeInt == 2){
jourDemandeeString = "Mercredi";
}
if (jourDemandeeInt == 3){
jourDemandeeString = "Jeudi";
}
if (jourDemandeeInt == 4){
jourDemandeeString = "Vendredi";
}
if (jourDemandeeInt == 5){
jourDemandeeString = "Samedi";
}
if (jourDemandeeInt == 6){
jourDemandeeString = "Dimanche";
}
c = Calendar.getInstance();
dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
df = new SimpleDateFormat("HH:mm");
heure = df.format(c.getTime());
if (Calendar.MONDAY == dayOfWeek) weekDay = "Lundi";
else if (Calendar.TUESDAY == dayOfWeek) weekDay = "Mardi";
else if (Calendar.WEDNESDAY == dayOfWeek) weekDay = "Mercredi";
else if (Calendar.THURSDAY == dayOfWeek) weekDay = "Jeudi";
else if (Calendar.FRIDAY == dayOfWeek) weekDay = "Vendredi";
else if (Calendar.SATURDAY == dayOfWeek) weekDay = "Samedi";
else if (Calendar.SUNDAY == dayOfWeek) weekDay = "Dimanche";
dayOfWeekString = String.valueOf(dayOfWeek);
if (checkRebootQuo == true) {
if (heure.equals(heureDemandee)) {
try {
Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot"});
proc.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
if (checkRebootHeb == true) {
if (dayOfWeekString.equals(jourDemandeeString)) {
if (heure.equals(heureDemandee)) {
try {
Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot"});
proc.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
}
public void cancel() {
cancelled = true;
}
}
最佳答案
该代码有很多错误。
您的主要问题-您的线程正在执行“主动”等待。这意味着:每次循环时,它只是循环并创建一个新的Calendar对象。然后,您立即丢弃该对象,并创建一个新对象。
您会对垃圾回收器在您的代码上遇到麻烦感到惊讶吗?并且只是为了确保我的讽刺不会阻止人们理解这个问题:世界上没有垃圾收集器被设计为允许仅创建垃圾对象的“热”循环;尤其是在“移动”世界中。
因此,显而易见的答案是:在循环体中添加一些Thread.sleep()语句;喜欢:
您的代码可以:
-检查是否需要重启的时间
-如果是,请重新启动
- 重复
然后,对您的(抱歉)糟糕的代码提供一些一般性反馈: