我试图在处理程序中每 2 秒循环一次,以使用 sharedpreference 标志 isHomeActive 模拟主页按钮按下。它将尝试每 2 秒检查一次服务内的标志是否处于活动状态。如果值为 no,它将尝试重新启动应用程序,但如果值为 yes,则不会重新启动应用程序。到目前为止,我无法让循环正常工作
主要活动的 onResume 和 onPause:
@Override
public void onPause()
{
super.onPause();
SharedPreferences home = PreferenceManager.getDefaultSharedPreferences(PhysicalTheftDialog.this);
Editor edit=home.edit();
edit.putString("isHomeActive", "no");
edit.commit();
}
@Override
public void onResume()
{
super.onResume();
SharedPreferences home = PreferenceManager.getDefaultSharedPreferences(PhysicalTheftDialog.this);
Editor edit=home.edit();
edit.putString("isHomeActive", "yes");
edit.commit();
}
服务类内部的循环:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(PhysicalTheftService.this);
final String isHomeActive = sp.getString("isHomeActive", "");
Runnable myRunnable = new Runnable() {
public void run() {
while (isHomeActive.equals("no")) {
try {
Intent physicaldialog = new Intent(PhysicalTheftService.this, PhysicalTheftDialog.class);
physicaldialog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PhysicalTheftService.this.startActivity(physicaldialog);
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};