在Activity中设置AlarmManager:
//获取定时时间(例如每天早上8点)
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
//创建Intent
Intent intent = new Intent(this, UnlockActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//设置AlarmManager
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
在BroadcastReceiver中打开Activity:
public class UnlockReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent unlockIntent = new Intent(context, UnlockActivity.class);
unlockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(unlockIntent);
}
}
在AndroidManifest.xml中注册BroadcastReceiver和Activity:
代码示例如下:
在Activity中设置JobScheduler:
//获取JobScheduler
JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
//设置JobInfo
ComponentName componentName = new ComponentName(this, UnlockJobService.class);
JobInfo jobInfo = new JobInfo.Builder(1, componentName)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setMinimumLatency(0)
.setOverrideDeadline(1000)
.setPersisted(true)
.build();
//执行JobScheduler
jobScheduler.schedule(jobInfo);
在JobService中打开Activity:
public class UnlockJobService extends JobService {
@Override
public boolean onStartJob(JobParameters params) {
Intent unlockIntent = new Intent(this, UnlockActivity.class);
unlockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(unlockIntent