下面列出了怎么用android.app.AlarmManager的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 开启一个闹钟
*/
private void setAlarmReceiver(String year,String month,String day,String hour,String minute ){
Intent receiverIntent = new Intent(getApplicationContext(), NoteAlarmReceiver.class);
long dbId = note.getId();
LogUtils.e(TAG,"dbId ==> "+dbId);
receiverIntent.putExtra(BaseNote.KEY_DB_ID,dbId );
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), note.getAlarmReqCode(), receiverIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Integer.parseInt(year), Integer.parseInt(month)-1, Integer.parseInt(day), Integer.parseInt(hour), Integer.parseInt(minute));
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
LogUtils.e("YEAR MONTH DAY "+calendar.get(Calendar.YEAR)+"-"+calendar.get(Calendar.MONTH)+"-"+calendar.get(Calendar.DAY_OF_MONTH));
LogUtils.e("HOUR MINUTE "+calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE));
long time = calendar.getTimeInMillis();
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
}
public void setRetryTimer() {
if (CollectionServiceStarter.isBTShare(getApplicationContext())) {
BgReading bgReading = BgReading.last();
long retry_in;
if (bgReading != null) {
retry_in = Math.min(Math.max((1000 * 30), (1000 * 60 * 5) - (new Date().getTime() - bgReading.timestamp) + (1000 * 5)), (1000 * 60 * 5));
} else {
retry_in = (1000 * 20);
}
Log.d(TAG, "Restarting in: " + (retry_in / (60 * 1000)) + " minutes");
Calendar calendar = Calendar.getInstance();
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
if (pendingIntent != null)
alarm.cancel(pendingIntent);
long wakeTime = calendar.getTimeInMillis() + retry_in;
pendingIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
} else
alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
}
}
/**
* Restart the current app. Supply the class to start on startup
*/
public void restartApp(Class classToStart) {
Intent intent = new Intent(_context, classToStart);
PendingIntent pendi = PendingIntent.getActivity(_context, 555, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE);
if (_context instanceof Activity) {
((Activity) _context).finish();
}
if (mgr != null) {
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendi);
} else {
intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(intent);
}
Runtime.getRuntime().exit(0);
}
/**
* Stops the {@link com.orangegangsters.github.lib.SensorStepService}
*/
public void stopAutoUpdateService(Context context) {
Log.d(TAG, "Stopping StepSensorService after broadcast");
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
activateStepCounter(false);
if (mService == null) {
Intent retrieverIntent = new Intent(context, getReceiverClass());
mService = PendingIntent.getBroadcast(context, SERVICE_ID, retrieverIntent, PendingIntent.FLAG_NO_CREATE);
}
if (mService != null) {
alarm.cancel(mService);
if (SensorStepService.getInstance() != null) {
SensorStepService.getInstance().unregisterSensorStep();
}
}
mService = null;
}
public static void startDaily(Context context) {
Intent alarmIntent = new Intent(context, BackgroundService.class);
alarmIntent.setAction(BackgroundService.ACTION_DAILY);
PendingIntent pi = PendingIntent.getService(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long trigger = calendar.getTimeInMillis() + 24 * 3600 * 1000;
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, trigger, pi);
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
alarmManager.setExact(AlarmManager.RTC_WAKEUP, trigger, pi);
else
alarmManager.set(AlarmManager.RTC_WAKEUP, trigger, pi);
Log.i(TAG, "Start daily job next=" + SimpleDateFormat.getDateTimeInstance().format(trigger));
}
@Override
public void onBackPressed() {
if (UserState.getInstances(this).isLogin()) {
if (lastUrlState != UrlConfigManager.getCurrentState()) {
UserState.getInstances(this).logout(this);
setResult(RESULT_OK);
Intent mStartActivity = new Intent(this, SplashActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(this, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 200, mPendingIntent);
MobclickAgent.onKillProcess(this);
android.os.Process.killProcess(android.os.Process.myPid());
return;
}
}
ActivityUtils.animFinish(this, R.anim.slide_in_from_left, R.anim.slide_out_to_right);
}
/** Stop replications currently in progress and cancel future scheduled replications. */
public synchronized void stopPeriodicReplication() {
if (isPeriodicReplicationEnabled()) {
setPeriodicReplicationEnabled(false);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, clazz);
alarmIntent.setAction(PeriodicReplicationReceiver.ALARM_ACTION);
PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
alarmManager.cancel(pendingAlarmIntent);
stopReplications();
} else {
Log.i(TAG, "Attempted to stop an already stopped alarm manager");
}
}
private void removeAlarm(/*boolean startEvent, */Context context)
{
try {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
//Intent intent = new Intent(context, EventCalendarBroadcastReceiver.class);
Intent intent = new Intent();
intent.setAction(PhoneProfilesService.ACTION_EVENT_CALENDAR_BROADCAST_RECEIVER);
//intent.setClass(context, EventCalendarBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) _event._id, intent, PendingIntent.FLAG_NO_CREATE);
if (pendingIntent != null) {
//PPApplication.logE("EventPreferencesCalendar.removeAlarm", "alarm found");
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
}
}
} catch (Exception e) {
PPApplication.recordException(e);
}
PhoneProfilesService.cancelWork(ElapsedAlarmsWorker.ELAPSED_ALARMS_CALENDAR_SENSOR_TAG_WORK+"_" + (int) _event._id);
}
@Test
public void checksAlarmRegistered() throws Exception {
Context mockedContext = mock(Context.class);
AlarmManager mockedAlarmManager = mock(AlarmManager.class);
AlarmReceiver mockedAlarmReceiver = mock(AlarmReceiver.class);
AlarmSchedulerFlusher theAlarmSchedulerFlusher = new AlarmSchedulerFlusher(mockedContext, mockedAlarmManager,
mockedAlarmReceiver);
theAlarmSchedulerFlusher.register();
IntentFilter expectedFilter = new IntentFilter("com.mapbox.scheduler_flusher");
verify(mockedContext, times(1)).registerReceiver(
eq(mockedAlarmReceiver),
refEq(expectedFilter)
);
}
/**
* Schedule next update.
*
* @param context {@link Context}
* @param delay delay in milliseconds
* @param action {@link Intent}'s action
*/
public static void schedNext(final Context context, final long delay, final String action) {
Log.d(TAG, "schedNext(ctx, ", delay, ",", action, ")");
final Intent i = new Intent(context, LogRunnerReceiver.class);
if (action != null) {
i.setAction(action);
}
try {
final PendingIntent pi = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
final long t = SystemClock.elapsedRealtime() + delay;
final AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.ELAPSED_REALTIME, t, pi);
} catch (ArrayIndexOutOfBoundsException e) {
Log.e(TAG, "schedule next check failed", e);
}
}
private void handleScheduleStrongAuthTimeout(int userId) {
final DevicePolicyManager dpm =
(DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
long when = SystemClock.elapsedRealtime() + dpm.getRequiredStrongAuthTimeout(null, userId);
// cancel current alarm listener for the user (if there was one)
StrongAuthTimeoutAlarmListener alarm = mStrongAuthTimeoutAlarmListenerForUser.get(userId);
if (alarm != null) {
mAlarmManager.cancel(alarm);
} else {
alarm = new StrongAuthTimeoutAlarmListener(userId);
mStrongAuthTimeoutAlarmListenerForUser.put(userId, alarm);
}
// schedule a new alarm listener for the user
mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, when, STRONG_AUTH_TIMEOUT_ALARM_TAG,
alarm, mHandler);
}
private void initializeService() {
if(D) Log.d(TAG, "initializeService");
Beacons.initialize(this);
mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
IntentFilter localIntentFilter = new IntentFilter(ACTION_ITEM_STATE);
LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, localIntentFilter);
// Bluetooth events are not received when using LocalBroadcastManager
IntentFilter systemIntentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver, systemIntentFilter);
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
if (null != bluetoothManager) {
mAdvertisersManager = new AdvertisersManager(bluetoothManager, this);
restoreSavedState();
}
}
public static void startUpdate(int type, Context context, long when) {
AlarmManager alarmMan = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (type == MOVIES) {
// We don't want multiple instances of the movie library service to run at the same time
if (MizLib.isMovieLibraryBeingUpdated(context))
return;
} else {
// We don't want multiple instances of the TV show library service to run at the same time
if (MizLib.isTvShowLibraryBeingUpdated(context))
return;
}
Intent defineIntent = new Intent(context, (type == MOVIES) ? MovieLibraryUpdate.class : TvShowsLibraryUpdate.class);
defineIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent piWakeUp = PendingIntent.getService(context,0, defineIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (when > -1) {
alarmMan.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + when, piWakeUp);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = settings.edit();
editor.putLong((type == MOVIES) ? NEXT_SCHEDULED_MOVIE_UPDATE : NEXT_SCHEDULED_TVSHOWS_UPDATE, System.currentTimeMillis() + when);
editor.apply();
}
}
private void bindSystemServices(Application application) {
bindSystemService(application, LocationManager.class, LOCATION_SERVICE);
bindSystemService(application, WindowManager.class, WINDOW_SERVICE);
bindSystemService(application, ActivityManager.class, ACTIVITY_SERVICE);
bindSystemService(application, PowerManager.class, POWER_SERVICE);
bindSystemService(application, AlarmManager.class, ALARM_SERVICE);
bindSystemService(application, NotificationManager.class, NOTIFICATION_SERVICE);
bindSystemService(application, KeyguardManager.class, KEYGUARD_SERVICE);
bindSystemService(application, Vibrator.class, VIBRATOR_SERVICE);
bindSystemService(application, ConnectivityManager.class, CONNECTIVITY_SERVICE);
bindSystemService(application, WifiManager.class, WIFI_SERVICE);
bindSystemService(application, InputMethodManager.class, INPUT_METHOD_SERVICE);
bindSystemService(application, SearchManager.class, SEARCH_SERVICE);
bindSystemService(application, SensorManager.class, SENSOR_SERVICE);
bindSystemService(application, TelephonyManager.class, TELEPHONY_SERVICE);
bindSystemService(application, AudioManager.class, AUDIO_SERVICE);
bindSystemService(application, DownloadManager.class, DOWNLOAD_SERVICE);
bindSystemService(application, ClipboardManager.class, CLIPBOARD_SERVICE);
}
public void setAlarm(long alarmIn, boolean force) {
if(!force && (alarmIn < 5 * 60 * 1000)) {
// No need to check more than once every 5 minutes
alarmIn = 5 * 60 * 1000;
}
Log.d(TAG, "Setting timer to " + alarmIn / 60000 + " minutes from now" );
Calendar calendar = Calendar.getInstance();
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
long wakeTime = calendar.getTimeInMillis() + alarmIn;
PendingIntent serviceIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, wakeTime, serviceIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, serviceIntent);
} else
alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, serviceIntent);
}
/**
* Function to set alarm notification every day
*
* @param context Application context
* @param hour Hour of alarm
* @param min Min of alarm
* @param id ID of alarm
*/
public static void setAlarmForAzkar(Context context, int hour, int min, int id , String type) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, min);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Bundle details = new Bundle();
details.putString("Azkar", type);
Intent alarmReceiver = new Intent(context, AzkarAlarm.class);
alarmReceiver.putExtras(details);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, id, alarmReceiver, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// kitkat...
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
} else {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1000 * 60 * 60 * 24, pendingIntent);
}
}
/**
* @param calendar {@link Calendar}
* @return 今天, 昨天, 前天, n天前
*/
public static String formatSomeDay(Calendar calendar) {
if (calendar == null) return "?天前";
Calendar mCurrentDate = Calendar.getInstance();
long crim = mCurrentDate.getTimeInMillis(); // current
long trim = calendar.getTimeInMillis(); // target
long diff = crim - trim;
int year = mCurrentDate.get(Calendar.YEAR);
int month = mCurrentDate.get(Calendar.MONTH);
int day = mCurrentDate.get(Calendar.DATE);
mCurrentDate.set(year, month, day, 0, 0, 0);
if (trim >= mCurrentDate.getTimeInMillis()) {
return "今天";
}
mCurrentDate.set(year, month, day - 1, 0, 0, 0);
if (trim >= mCurrentDate.getTimeInMillis()) {
return "昨天";
}
mCurrentDate.set(year, month, day - 2, 0, 0, 0);
if (trim >= mCurrentDate.getTimeInMillis()) {
return "前天";
}
return String.format("%s天前", diff / AlarmManager.INTERVAL_DAY);
}
@SuppressLint("UseSparseArrays")
@Override
public void onCreate() {
super.onCreate();
Languager.setLanguage(this);
// Register BroadcastReceiver to track connection changes.
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkReceiver, filter);
updateConnectedFlags();
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
allowMobileData = sharedPrefs.getBoolean(SettingsFragment.PREF_KEY_MOBILE_DATA, true);
alarmsMap = new HashMap<Integer, Alarm>();
exchangesMap = new HashMap<String, Exchange>();
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
try {
db = new DBManager(this);
nextAlarmID = db.getMaxID() + 1;
alarmsMap = db.getAlarms();
if(alarmsMap.isEmpty()) {
// new PopupalteDBTask().execute();
} else {
// Set Exchange and start alarm
for (Alarm alarm : alarmsMap.values()) {
alarm.setExchange(getExchange(alarm.getExchangeCode()));
if(alarm.isOn()) {
addToAlarmManager(alarm, 0);
}
}
}
} catch (Exception e) {
Log.e("Caught exception while recovering alarms from DB.", e);
}
}
public void setExact(int type, long time, PendingIntent service) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP && Preferences.USE_ALARM.get()) {
AlarmManager.AlarmClockInfo info = new AlarmManager.AlarmClockInfo(time,
PendingIntent.getActivity(context, 0, Module.TIMES.buildIntent(context), PendingIntent.FLAG_UPDATE_CURRENT));
alarmManager.setAlarmClock(info, service);
} else if (type == AlarmManager.RTC_WAKEUP && Build.VERSION.SDK_INT >= 23) {
alarmManager.setExactAndAllowWhileIdle(type, time, service);
} else {
alarmManager.setExact(type, time, service);
}
}
public static void removeAlarm(Context context, int id){
Intent intent = new Intent(AntiHijackingActicon);
intent.setFlags(FLAG_INCLUDE_STOPPED_PACKAGES);
PendingIntent pi = PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
alarmManager.cancel(pi);
}
public void startAlarm(AlarmManager mAlamManager, PendingIntent pi){
Log.d("alarm","启动闹钟");
Calendar c=Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY,alarmInfo.getHour());
c.set(Calendar.MINUTE,alarmInfo.getMinute());
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND, 0);
// Log.d("alarm", "当前系统版本" + Build.VERSION.SDK_INT);
if(c.getTimeInMillis()<System.currentTimeMillis()){
if(Build.VERSION.SDK_INT>=19)
{
mAlamManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis() + 24 * 60 * 60 * 1000, pi);
}else{
mAlamManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis() + 24 * 60 * 60 * 1000, pi);
}
}else{
if(Build.VERSION.SDK_INT>=19)
{
Log.d("alarm","执行定时任务");
Date date=c.getTime();
Log.d("alarm","定时的时间是"+date.toString());
mAlamManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
}else{
mAlamManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
}
}
}
private static void enableBackup() {
Intent intent = new Intent("NARRATE_BACKUP");
intent.setClass(GlobalApplication.getAppContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(GlobalApplication.getAppContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) GlobalApplication.getAppContext().getSystemService(GlobalApplication.getAppContext().ALARM_SERVICE);
int interval = Settings.getLocalBackupFrequency();
if ( interval > -1 ) {
long millis = 0;
switch (interval) {
case 0:
millis = DateUtil.DAY_IN_MILLISECONDS;
break;
case 1:
millis = DateUtil.WEEK_IN_MILLISECONDS;
break;
case 2:
millis = DateUtil.WEEK_IN_MILLISECONDS * 4;
break;
}
// delay things by a second
am.setRepeating(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis() + (30 * DateUtil.SECOND_IN_MILLISECONDS), millis, pendingIntent);
}
}
public void retry(Context context, long sec) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
pref.edit().putBoolean("isRetry", true).apply();
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + sec * 1000L, pi);
}
public static void startPollingService(Context context, int minute) {
if (context != null) {
PendingIntent pending = PendingIntent.getService(context, 1521045111, new Intent(context, RedPacketPollingService.class), 268435456);
AlarmManager alarm = (AlarmManager) context.getSystemService(NotificationCompat.CATEGORY_ALARM);
alarm.cancel(pending);
alarm.set(2, SystemClock.elapsedRealtime() + ((long) ((minute * 60) * 1000)), pending);
}
}
private void trackStop() {
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, LocAlarmService.class);
i.setAction(Util.INTENT_ACTION_TRACK_INI);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
am.cancel(pi);
Util.TracksNumber = 0;
Util.TrackOn = false;
}
private void scheduleRecommendationUpdate(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent recommendationIntent = new Intent(context, RecommendationsService.class);
PendingIntent alarmIntent = PendingIntent.getService(context, 0, recommendationIntent, 0);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
INITIAL_DELAY,
AlarmManager.INTERVAL_HALF_HOUR,
alarmIntent);
}
/**
* Schedule or cancel this service to update the app index, according to the
* current preferences. Should be called a) at boot, b) if the preference
* is changed, or c) on startup, in case we get upgraded.
*/
public static void schedule(Context context) {
long keepTime = Preferences.get().getKeepCacheTime();
long interval = TimeUnit.DAYS.toMillis(1);
if (keepTime < interval) {
interval = keepTime;
}
if (Build.VERSION.SDK_INT < 21) {
Intent intent = new Intent(context, CleanCacheService.class);
PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 5000, interval, pending);
} else {
Utils.debugLog(TAG, "Using android-21 JobScheduler for updates");
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
ComponentName componentName = new ComponentName(context, CleanCacheJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, componentName)
.setRequiresDeviceIdle(true)
.setRequiresCharging(true)
.setPeriodic(interval);
if (Build.VERSION.SDK_INT >= 26) {
builder.setRequiresBatteryNotLow(true);
}
jobScheduler.schedule(builder.build());
}
}
private void d()
{
AlarmManager alarmmanager = (AlarmManager)getSystemService("alarm");
Intent intent = new Intent();
intent.setAction("com.xiaomi.hm.health.set_max_latency");
alarmmanager.cancel(PendingIntent.getBroadcast(this, 0, intent, 0));
}
public boolean cancelReminder(Date date, Bundle extra) {
Intent myIntent = new Intent(mContext, ReminderReceiver.class);
myIntent.putExtras(extra);
int row_id = extra.getInt(OColumn.ROW_ID);
AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, row_id, myIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.cancel(pendingIntent);
return true;
}
private void setAlarm(long alarmTime, String alarmPackageName, AlarmManager alarmManager, Context context) {
removeAlarm(alarmManager, context);
//PhoneProfilesService instance = PhoneProfilesService.getInstance();
//if (instance == null)
// return;
// !!! Keep disabled "if", next alarm my be received before registering
// AlarmClockBroadcastReceiver for example from Editor
//if (instance.alarmClockBroadcastReceiver != null) {
//long alarmTime = time;// - Event.EVENT_ALARM_TIME_SOFT_OFFSET;
/*if (PPApplication.logEnabled()) {
@SuppressLint("SimpleDateFormat")
SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
String result = sdf.format(alarmTime);
PPApplication.logE("NextAlarmClockBroadcastReceiver.setAlarm", "alarmTime=" + result);
}*/
//Intent intent = new Intent(context, AlarmClockBroadcastReceiver.class);
Intent intent = new Intent();
intent.setAction(PhoneProfilesService.ACTION_ALARM_CLOCK_BROADCAST_RECEIVER);
//intent.setClass(context, AlarmClockBroadcastReceiver.class);
intent.putExtra(AlarmClockBroadcastReceiver.EXTRA_ALARM_PACKAGE_NAME, alarmPackageName);
// set alarm
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 9998, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//if (android.os.Build.VERSION.SDK_INT >= 23)
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
//else //if (android.os.Build.VERSION.SDK_INT >= 19)
// alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
//else
// alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
//}
}