下面列出了android.app.AlarmManager#cancel ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void setFailoverTimer() { //Sometimes it gets stuck in limbo on 4.4, this should make it try again
if (CollectionServiceStarter.isBTShare(getApplicationContext())) {
long retry_in = (1000 * 60 * 5);
Log.d(TAG, "Fallover 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);
} else {
stopSelf();
}
}
@Override
public void onDestroy() {
super.onDestroy();
close();
if (shouldServiceRun(getApplicationContext())) {//Android killed service
setRetryTimer();
}
else {//onDestroy triggered by CollectionServiceStart.stopBtService
if (pendingIntent != null) {
Log.d(TAG, "onDestroy stop Alarm serviceIntent");
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
alarm.cancel(pendingIntent);
}
}
//KS foregroundServiceStarter.stop();
unregisterReceiver(mPairReceiver);
//KS BgToSpeech.tearDownTTS();
Log.i(TAG, "SERVICE STOPPED");
}
public void setNextAlarm(Context context) {
AlarmManager aManager = (AlarmManager) context
.getSystemService(Service.ALARM_SERVICE);
Calendar tcalendar = Calendar.getInstance();
tcalendar.setTimeInMillis(System.currentTimeMillis());
tcalendar.add(Calendar.DAY_OF_YEAR, +1);
tcalendar.set(Calendar.HOUR_OF_DAY, 0);
tcalendar.set(Calendar.MINUTE, 19);
tcalendar.set(Calendar.SECOND, 19);
Intent intent = new Intent(context, LessonsWidgetProvider_4_1.class);
intent.setAction("zq.whu.zhangshangwuda.ui.lessons.widget_4_1.today");
PendingIntent work = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
aManager.cancel(work);
aManager.set(AlarmManager.RTC, tcalendar.getTimeInMillis(), work);
Log.v("zq.whu.zhangshangwuda.ui.lessons.widget_4_1", "设置定时更新成功");
}
@Override
public void onDestroy() {
super.onDestroy();
close();
if (shouldServiceRun(getApplicationContext())) {//Android killed service
setRetryTimer();
}
else {//onDestroy triggered by CollectionServiceStart.stopBtService
if (pendingIntent != null) {
Log.d(TAG, "onDestroy stop Alarm serviceIntent");
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
alarm.cancel(pendingIntent);
}
}
foregroundServiceStarter.stop();
unregisterReceiver(mPairReceiver);
//BgToSpeech.tearDownTTS();
Log.i(TAG, "SERVICE STOPPED");
}
@Override
public void stop() {
Log.d(TAG, "Unregister alarmreceiver to MqttService"+comms.getClient().getClientId());
if(hasStarted){
if(pendingIntent != null){
// Cancel Alarm.
AlarmManager alarmManager = (AlarmManager) service.getSystemService(Service.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
hasStarted = false;
try{
service.unregisterReceiver(alarmReceiver);
}catch(IllegalArgumentException e){
//Ignore unregister errors.
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand(): intent = [" + intent.toUri(0) + "], flags = [" + flags + "], startId = [" + startId + "]");
try {
// 定时检查 WorkService 是否在运行,如果不在运行就把它拉起来
// Android 5.0+ 使用 JobScheduler,效果比 AlarmManager 好
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.i(TAG, "开启 JobService 定时");
JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.cancelAll();
JobInfo.Builder builder = new JobInfo.Builder(1024, new ComponentName(getPackageName(), ScheduleService.class.getName()));
builder.setPeriodic(WAKE_INTERVAL);
builder.setPersisted(true);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
int schedule = jobScheduler.schedule(builder.build());
if (schedule <= 0) {
Log.w(TAG, "schedule error!");
}
} else {
// Android 4.4- 使用 AlarmManager
Log.i(TAG, "开启 AlarmManager 定时");
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(getApplication(), DaemonService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1024, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pendingIntent);
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + WAKE_INTERVAL, WAKE_INTERVAL, pendingIntent);
}
} catch (Exception e) {
Log.e(TAG, "e:", e);
}
// 简单守护开机广播
getPackageManager().setComponentEnabledSetting(
new ComponentName(getPackageName(), DaemonService.class.getName()),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
return super.onStartCommand(intent, flags, startId);
}
public static void updateNotificationSystem(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intentForService = new Intent(context, UpdateService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intentForService, 0);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
boolean notifications = sharedPref.getBoolean(ENABLE_NOTIFICATION_SYNCHRO, true);
Log.i("fbn", "Notifications enabled? " + notifications);
if (notifications) {
int updateInterval = Integer.parseInt(sharedPref.getString(UPDATE_INTERVAL, "15"));
alarmManager.setInexactRepeating(MainActivity.AlarmType, SystemClock.elapsedRealtime() + 5000, updateInterval * 1000 * 60, pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
}
}
public static void setSleep(Calendar time) {
AlarmManager alarmMgr = (AlarmManager) VLCApplication.getAppContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(VLCApplication.SLEEP_INTENT);
PendingIntent sleepPendingIntent = PendingIntent.getBroadcast(VLCApplication.getAppContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (time != null) {
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), sleepPendingIntent);
}
else {
alarmMgr.cancel(sleepPendingIntent);
}
VLCApplication.sPlayerSleepTime = time;
}
public void CancelAlarm(Context context) {
Logd(TAG, "Unsetting location alarm.");
Intent i = new Intent(alarmContext, LocationAlarm.class);
PendingIntent pi = PendingIntent.getBroadcast(alarmContext, 99, i, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) alarmContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pi);
}
public static void setBusAlarm(Context context, String endStation, String time, int id) {
if (!time.contains(" ") || !time.contains("-") || !time.contains(":")) {
return;
}
Intent intent = new Intent(context, BusAlarmService.class);
Bundle bundle = new Bundle();
bundle.putString("endStation", endStation);
bundle.putString("Time", time);
intent.putExtras(bundle);
Calendar calendar = Calendar.getInstance();
String _date = time.split(" ")[0];
String _time = time.split(" ")[1];
calendar.set(Integer.parseInt(_date.split("-")[0]),
Integer.parseInt(_date.split("-")[1]) - 1, Integer.parseInt(_date.split("-")[2]),
Integer.parseInt(_time.split(":")[0]), Integer.parseInt(_time.split(":")[1]));
calendar.add(Calendar.MINUTE, -30);
PendingIntent pendingIntent =
PendingIntent.getService(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) context.getSystemService(Service.ALARM_SERVICE);
alarm.cancel(pendingIntent);
Date now = new Date(System.currentTimeMillis());
if (calendar.getTime().after(now)) {
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
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 static void cancelAlarm(Context context, String action, int id) {
Intent intent = new Intent(action);
PendingIntent pi = PendingIntent.getBroadcast(context, id, intent, PendingIntent
.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(pi);
}
static void teardownNightMode(Context context, AlarmManager am) {
try {
// cancel nightmode
Intent intentNMOn = new Intent(Intent.ACTION_EDIT, Uri.parse("nightmode://on"), context, DataToggler.class);
Intent intentNMOff = new Intent(Intent.ACTION_EDIT, Uri.parse("nightmode://off"), context, DataToggler.class);
PendingIntent senderNMOn = PendingIntent.getBroadcast(context, 0, intentNMOn, 0);
PendingIntent senderNMOff = PendingIntent.getBroadcast(context, 0, intentNMOff, 0);
am.cancel(senderNMOn);
am.cancel(senderNMOff);
} catch (Exception e) {
Log.e("BatteryFu", "Error cancelling nightmode", e);
}
}
void cancelAlarm(AlarmModel alarm) {
alarm.setActive(0);
getAlarmDB().update(alarm);
AlarmManager alarmManager = this.getAlarmManager();
int alarmId = alarm.getAlarmId();
Intent intent = new Intent(mContext, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(mContext, alarmId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(alarmIntent);
this.setBootReceiver();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand(): intent = [" + intent.toUri(0) + "], flags = [" + flags + "], startId = [" + startId + "]");
try {
// 定时检查 WorkService 是否在运行,如果不在运行就把它拉起来
// Android 5.0+ 使用 JobScheduler,效果比 AlarmManager 好
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.i(TAG, "开启 JobService 定时");
JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.cancelAll();
JobInfo.Builder builder = new JobInfo.Builder(1024, new ComponentName(getPackageName(), ScheduleService.class.getName()));
builder.setPeriodic(WAKE_INTERVAL);
builder.setPersisted(true);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
int schedule = jobScheduler.schedule(builder.build());
if (schedule <= 0) {
Log.w(TAG, "schedule error!");
}
} else {
// Android 4.4- 使用 AlarmManager
Log.i(TAG, "开启 AlarmManager 定时");
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(getApplication(), DaemonService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1024, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pendingIntent);
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + WAKE_INTERVAL, WAKE_INTERVAL, pendingIntent);
}
} catch (Exception e) {
Log.e(TAG, "e:", e);
}
// 简单守护开机广播
getPackageManager().setComponentEnabledSetting(
new ComponentName(getPackageName(), DaemonService.class.getName()),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
return super.onStartCommand(intent, flags, startId);
}
/**
* Cancel the scheduled persistence service
* @param forceSave if true the persistence service will be execute now and canceled after
* @param context The application context
*/
public static void cancelPersistenceService(boolean forceSave, Context context){
// force save
if(forceSave) {
startPersistenceService(context);
}
Intent stepCountPersistenceServiceIntent = new Intent(context, StepCountPersistenceReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 2, stepCountPersistenceServiceIntent, 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(sender);
}
/**
* Cancels the motivation alert
* @param context The application context
*/
public static void cancelMotivationAlert(Context context){
Log.i(LOG_CLASS, "Canceling motivation alert alarm");
Intent motivationAlertIntent = new Intent(context, MotivationAlertReceiver.class);
PendingIntent motivationAlertPendingIntent = PendingIntent.getBroadcast(context, 1, motivationAlertIntent, 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(motivationAlertPendingIntent);
}
/**
* Saves and applies the configuration changes.
* If there aren't configured hosts, it disables the {@link ConnectivityReceiver} and cancels
* scheduled period checks. If there is at least one configured host, it enables the
* {@link ConnectivityReceiver} and re-schedules periodic checks with new settings. If periodic
* check interval is set to zero, host reachability checks will be triggered only when the
* connectivity status of the device changes.
*/
public void save() {
Logger.debug(getClass().getSimpleName(), "saving configuration");
SharedPreferences.Editor prefs = getPrefs().edit();
if (mHostsMap != null && !mHostsMap.isEmpty()) {
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
prefs.putString(KEY_HOSTS, gson.toJson(mHostsMap));
}
if (mBroadcastAction != null && !mBroadcastAction.isEmpty()) {
prefs.putString(KEY_BROADCAST_ACTION, mBroadcastAction);
}
if (mSocketTimeout > 0) {
prefs.putInt(KEY_SOCKET_TIMEOUT, mSocketTimeout);
}
if (mCheckInterval >= 0) {
prefs.putInt(KEY_CHECK_INTERVAL, mCheckInterval);
}
if (mMaxAttempts > 0) {
prefs.putInt(KEY_MAX_ATTEMPTS, mMaxAttempts);
}
prefs.apply();
boolean thereIsAtLeastOneHost = !getHostsMap().isEmpty();
Util.setBroadcastReceiverEnabled(mContext, ConnectivityReceiver.class, thereIsAtLeastOneHost);
AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
PendingIntent intent = getPeriodicCheckIntent(mContext);
Logger.debug(HostMonitor.class.getSimpleName(), "cancelling scheduled checks");
alarmManager.cancel(intent);
if (thereIsAtLeastOneHost) {
if (getCheckInterval() > 0) {
Logger.debug(getClass().getSimpleName(), "scheduling periodic checks every " +
(getCheckInterval() / 1000) + " seconds");
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + getCheckInterval(),
getCheckInterval(), intent);
}
Logger.debug(getClass().getSimpleName(), "triggering reachability check");
HostMonitor.start(mContext);
}
}
public void stopCron() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(cronPI);
}
public static void clearReminder(Context context) {
Intent alarmIntent = new Intent(ReminderReceiver.REMINDER_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}