下面列出了android.app.AlarmManager#set ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void setRetryTimer() {
if (CollectionServiceStarter.isBteWixelorWifiandBtWixel(getApplicationContext())
|| CollectionServiceStarter.isDexbridgeWixelorWifiandDexbridgeWixel(getApplicationContext())) {
long retry_in;
if(CollectionServiceStarter.isDexbridgeWixelorWifiandDexbridgeWixel(getApplicationContext())) {
retry_in = (1000 * 25);
}else {
retry_in = (1000*65);
}
Log.d(TAG, "setRetryTimer: Restarting in: " + (retry_in / 1000) + " seconds");
Calendar calendar = Calendar.getInstance();
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
long wakeTime = calendar.getTimeInMillis() + retry_in;
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);
}
}
public static long wakeUpIntent(Context context, long delayMs, PendingIntent pendingIntent) {
final long wakeTime = JoH.tsl() + delayMs;
if (pendingIntent != null) {
Log.d(TAG, "Scheduling wakeup intent: " + dateTimeText(wakeTime));
final AlarmManager alarm = (AlarmManager) context.getSystemService(ALARM_SERVICE);
try {
alarm.cancel(pendingIntent);
} catch (Exception e) {
Log.e(TAG, "Exception cancelling alarm in wakeUpIntent: " + e);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (buggy_samsung) {
alarm.setAlarmClock(new AlarmManager.AlarmClockInfo(wakeTime, null), pendingIntent);
} else {
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);
} else {
Log.e(TAG, "wakeUpIntent - pending intent was null!");
}
return wakeTime;
}
/** Issues a registration retry with delay. */
static void issueDelayedRegistrationIntent(Context context, AndroidClock clock,
ByteString clientId, ObjectId objectId, boolean isRegister, int delayMs, int requestCode) {
RegistrationCommand command = isRegister ?
AndroidListenerProtos.newDelayedRegisterCommand(clientId, objectId) :
AndroidListenerProtos.newDelayedUnregisterCommand(clientId, objectId);
Intent intent = new Intent()
.putExtra(EXTRA_REGISTRATION, command.toByteArray())
.setClass(context, AlarmReceiver.class);
// Create a pending intent that will cause the AlarmManager to fire the above intent.
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent,
PendingIntent.FLAG_ONE_SHOT);
// Schedule the pending intent after the appropriate delay.
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
long executeMs = clock.nowMs() + delayMs;
alarmManager.set(AlarmManager.RTC, executeMs, pendingIntent);
}
public void setalarm(Context context, int time, int notiID) {
//---use the AlarmManager to trigger an alarm---
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//---get current date and time---
Calendar calendar = Calendar.getInstance();
//---sets the time for the alarm to trigger in 2 minutes from now---
calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + time);
calendar.set(Calendar.SECOND, 0);
//---PendingIntent to launch receiver when the alarm triggers-
//Intent notificationIntent = new Intent(getApplicationContext(), MyReceiver.class);
Intent notificationIntent = new Intent(MainActivity.ACTION);
notificationIntent.setPackage("edu.cs4730.broadcastboot"); //in API 26, it must be explicit now.
notificationIntent.putExtra("notiid", notiID);
PendingIntent contentIntent = PendingIntent.getBroadcast(context, notiID, notificationIntent, 0);
Log.i(TAG, "Set alarm, I hope");
//---sets the alarm to trigger---
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), contentIntent);
}
/**
* crash退出程序,0.5s后重启
* 如果在系统onCreate前写的代码产生crash,需要特殊处理
*/
@Override
public void uncaughtException(Thread t, Throwable e) {
PgyerCrashObservable.get().notifyObservers(t, e);
final Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
PendingIntent restartIntent = PendingIntent.getActivity(
context, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent);
}
App.getInstance().abortedApp();
}
@Override
public void onReceive(Context context, Intent mintent) {
//if (Intent.ACTION_BOOT_COMPLETED.equals(mintent.getAction())) {
// 启动完成
Log.i("BootReceiver", "onReceive");
Intent intent = new Intent(context, AlarmReceiver.class);
intent.setAction(AlarmReceiver.ACTION);
PendingIntent sender = PendingIntent.getBroadcast(context, 0,
intent, 0);
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
if(android.os.Build.VERSION.SDK_INT<android.os.Build.VERSION_CODES.KITKAT){
/** 开机激活闹钟 **/
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+60000, sender);
}
else{
am.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+60000, sender);
}
// }
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(PhonkServerService.this, "ooops!", Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
// handlerToast.post(runnable);
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mRestartPendingIntent);
mNotificationManager.cancelAll();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
throw new RuntimeException(ex);
}
/**
* Restart the current app. Supply the class to start on startup
*/
public void restartApp(Class classToStart) {
Intent inte = new Intent(_context, classToStart);
PendingIntent inteP = PendingIntent.getActivity(_context, 555, inte, 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, inteP);
} else {
inte.addFlags(FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(inte);
}
Runtime.getRuntime().exit(0);
}
public static void post(Context context) {
long delay = Integer.valueOf(PreferencesUtil.getCheckGlucoseInterval(context)) * 60000 + 120000;
Log.i(TAG, "set next check: " + delay + " (" + new SimpleDateFormat("HH:mm:ss")
.format(new Date(delay + System.currentTimeMillis())) + ") "
+ new Exception().getStackTrace()[1]);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
PendingIntent intent = getAlarmReceiverIntent(context);
alarmManager.cancel(intent);
if (android.os.Build.VERSION.SDK_INT <= 18) {
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + delay, intent);
} else {
alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + delay, intent);
}
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putLong("next_check", System.currentTimeMillis() + delay).apply();
}
/**
* Set alarm for 2 minutes to clear the clipboard
*/
protected void setClearClipboardAlarm() {
// create pending intent
AlarmManager alarmMgr = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getContext(), ClipboardAlarmReceiver.class);
intent.setAction("co.banano.natriumwallet.alarm");
PendingIntent alarmIntent = PendingIntent.getBroadcast(getContext(), 0, intent, 0);
// set a two minute alarm to start the pending intent
if (alarmMgr != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
alarmMgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 120 * 1000, alarmIntent);
} else {
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 120 * 1000, alarmIntent);
}
}
}
public static void setReminder(Reminder reminder) {
Calendar alarmCalendar = Calendar.getInstance();
Calendar reminderDate = Calendar.getInstance();
reminderDate.setTime(reminder.getDate());
if (reminder.getDay() <= alarmCalendar.get(Calendar.DAY_OF_MONTH) || !DateUtils.isToday(reminder.getCreatedAt())) {
alarmCalendar.setTime(DateUtils.getLastDateOfCurrentMonth());
}
alarmCalendar.set(Calendar.DATE, reminder.getDay());
alarmCalendar.set(Calendar.HOUR_OF_DAY, reminderDate.get(Calendar.HOUR_OF_DAY));
alarmCalendar.set(Calendar.MINUTE, reminderDate.get(Calendar.MINUTE));
AlarmManager alarmMgr = (AlarmManager) ExpenseTrackerApp.getContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(ExpenseTrackerApp.getContext(), AlarmReceiver.class);
intent.putExtra(NewReminderFragment.REMINDER_ID_KEY, reminder.getId());
PendingIntent alarmIntent = PendingIntent.getBroadcast(ExpenseTrackerApp.getContext(), (int) reminder.getCreatedAt().getTime(), intent, 0);
alarmMgr.set(AlarmManager.RTC_WAKEUP, alarmCalendar.getTimeInMillis(), alarmIntent);
}
private static void set(Context context, short timeIndex, Calendar actualTime) {
if (Calendar.getInstance().after(actualTime)) {
// Somehow current time is greater than the prayer time
return;
}
Intent intent = new Intent(context, StartNotificationReceiver.class);
intent.putExtra(CONSTANT.EXTRA_ACTUAL_TIME, actualTime.getTimeInMillis());
intent.putExtra(CONSTANT.EXTRA_TIME_INDEX, timeIndex);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
am.setExact(AlarmManager.RTC_WAKEUP, actualTime.getTimeInMillis(),
PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
} else {
am.set(AlarmManager.RTC_WAKEUP, actualTime.getTimeInMillis(),
PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
}
}
private static void createAlarm(Context context, IntervalTimer timer, PendingIntent pendingIntent) {
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (timer.getExecutionInterval() == -1) {
// one time alarm
alarmMgr.set(AlarmManager.RTC_WAKEUP, timer.getExecutionTime().getTimeInMillis(), pendingIntent);
} else {
// repeating alarm
Calendar currentTime = Calendar.getInstance();
Calendar exactExecutionTime = Calendar.getInstance();
exactExecutionTime.set(Calendar.HOUR_OF_DAY, timer.getExecutionTime().get(Calendar.HOUR_OF_DAY));
exactExecutionTime.set(Calendar.MINUTE, timer.getExecutionTime().get(Calendar.MINUTE));
exactExecutionTime.set(Calendar.SECOND, 0);
exactExecutionTime.set(Calendar.MILLISECOND, 0);
while (exactExecutionTime.before(currentTime)) {
exactExecutionTime.add(Calendar.MILLISECOND, (int) timer.getExecutionInterval());
}
if (Build.VERSION.SDK_INT >= 23) {
alarmMgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, exactExecutionTime.getTimeInMillis(), pendingIntent);
} else if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 23) {
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, exactExecutionTime.getTimeInMillis(), pendingIntent);
} else if (Build.VERSION.SDK_INT < 19) {
alarmMgr.set(AlarmManager.RTC_WAKEUP, exactExecutionTime.getTimeInMillis(), pendingIntent);
} else {
Log.e("AlarmHandler", "Unknown SDK Version!");
}
}
}
protected void startServiceWithCheck(Context context, Intent intent) {
try {
context.startService(intent);
} catch (IllegalStateException ise) {
intent.putExtra("isInteractive", false);
PendingIntent pendingIntent = PendingIntent.getService(context,
0,
intent,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 10,
pendingIntent);
}
}
/**
* Sets an alarm in the alarm manager.
*/
@VisibleForTesting
protected void setAlarm(AlarmManager am, long timestamp, PendingIntent retryPIntent) {
Log.d(TAG, "now(" + new Date(getCurrentTime()) + ") refiringAt("
+ new Date(timestamp) + ")");
try {
am.set(AlarmManager.RTC, timestamp, retryPIntent);
} catch (SecurityException e) {
Log.e(TAG, "Failed to set backoff alarm.");
}
}
@SuppressLint("NewApi")
@Override
public void onTaskRemoved(Intent rootIntent){
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
public void setAlarm(long alarmIn) {
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);
}
/**
* 装在定时任务
* @param Time
*/
private void configureAlarmManager(long Time) {
AlarmManager manager = (AlarmManager) mContext.getSystemService(ALARM_SERVICE);
PendingIntent pendIntent = getPendingIntent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, Time, pendIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
manager.setExact(AlarmManager.RTC_WAKEUP, Time, pendIntent);
} else {
manager.set(AlarmManager.RTC_WAKEUP, Time, pendIntent);
}
}
/**
* Restart the application.
*/
public void restartApplication() {
Intent mStartActivity = new Intent(this, MainActivity.class);
PendingIntent intent = PendingIntent.getActivity(this.getBaseContext(),
0, mStartActivity, getIntent().getFlags());
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 300, intent);
//System.exit(2);
android.os.Process.killProcess(android.os.Process.myPid());
}
private void setCleanupWakeAlarm(long interval) {
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval,
PendingIntent.getBroadcast(this, 0, new Intent(ACTION_CLEANUP), 0));
}