alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent3 = new Intent(WebActivity.this, CommunicateService.class);
//intent
intent3.putExtra(SWITCH, SWITCH);
intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//实例化PendingIntent
PendingIntent pi3 = PendingIntent.getService(this, 3, intent3,PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30 * 1000, pi3);
service中
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP , SERVICE_NAME);
Bundle extras = intent.getExtras();
if (extras != null) {
if (CONFIG.equals(extras.getString(CONFIG))) {
new ConfigThread().start();
}
if (USAGEINFO.equals(extras.getString(USAGEINFO))) {
new UsageInfoThread().start();
}
if (SWITCH.equals(extras.getString(SWITCH))) {
new SwitchThread().start();
}
}
class SwitchThread extends Thread {
@Override
public void run() {
Log.i("关闭屏幕计时器", "正常");
if (todayConfigs.isEmpty())
return;
// Config currConfig = todayConfigs.get(0);
long onTime = 0, offTime = 0;
long now = System.currentTimeMillis();
for (int i = 0; i < todayConfigs.size(); i++) {
Config config = todayConfigs.get(i);
offTime = config.getOffTime().getTime();
if (now > offTime) {
onTime = now;
} else {
onTime = config.getOnTime().getTime();
// 如果既小于开机时间,又小于关机时间,说明处于前一个时间段与后一个时间段之间
if (now < onTime && i > 0) {
// 返回前一个关机时间
Config currConfig = todayConfigs.get(i - 1);
offTime = currConfig.getOffTime().getTime();
}
break;
}
}
try {
if (now >= onTime && now < offTime) {
Log.i("屏幕计时器", "进入开启范围");
Log.i("屏幕计时器", "NOW:" + sdf.format(new java.util.Date(now))
+ " ON:" + sdf.format(new java.util.Date(onTime))
+ " OFF:" + sdf.format(new java.util.Date(offTime)));
// turn on
if (!powerManager.isScreenOn()) {
wakeLock.acquire(24 * 60 * 60 * 1000);
}
} else if (now >= offTime) {
Log.i("屏幕计时器", "进入关闭范围");
Log.i("屏幕计时器", "NOW:" + sdf.format(new java.util.Date(now))
+ " ON:" + sdf.format(new java.util.Date(onTime))
+ " OFF:" + sdf.format(new java.util.Date(offTime)));
// turn off
if (powerManager.isScreenOn()) {
powerManager.goToSleep(SystemClock.uptimeMillis());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}