List of usage examples for android.app AlarmManager set
public void set(@AlarmType int type, long triggerAtMillis, PendingIntent operation)
Schedule an alarm.
From source file:org.yuttadhammo.BodhiTimer.TimerReceiver.java
@Override public void onReceive(Context context, Intent pintent) { Log.v(TAG, "ALARM: received alarm"); NotificationManager mNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (player != null) { Log.v(TAG, "Releasing media player..."); try {// w w w. ja va2 s . co m player.release(); player = null; } catch (Exception e) { e.printStackTrace(); player = null; } finally { // do nothing } } // Cancel notification and return... if (CANCEL_NOTIFICATION.equals(pintent.getAction())) { Log.v(TAG, "Cancelling notification..."); mNM.cancelAll(); return; } // ...or display a new one Log.v(TAG, "Showing notification..."); player = new MediaPlayer(); int setTime = pintent.getIntExtra("SetTime", 0); String setTimeStr = TimerUtils.time2humanStr(context, setTime); Log.v(TAG, "Time: " + setTime); CharSequence text = context.getText(R.string.Notification); CharSequence textLatest = String.format(context.getString(R.string.timer_for_x), setTimeStr); // Load the settings SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean led = prefs.getBoolean("LED", true); boolean vibrate = prefs.getBoolean("Vibrate", true); String notificationUri = ""; boolean useAdvTime = prefs.getBoolean("useAdvTime", false); String advTimeString = prefs.getString("advTimeString", ""); String[] advTime = null; int advTimeIndex = 1; if (useAdvTime && advTimeString.length() > 0) { advTime = advTimeString.split("\\^"); advTimeIndex = prefs.getInt("advTimeIndex", 1); String[] thisAdvTime = advTime[advTimeIndex - 1].split("#"); // will be of format timeInMs#pathToSound if (thisAdvTime.length == 3) notificationUri = thisAdvTime[1]; if (notificationUri.equals("sys_def")) notificationUri = prefs.getString("NotificationUri", "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell); } else notificationUri = prefs.getString("NotificationUri", "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell); Log.v(TAG, "notification uri: " + notificationUri); if (notificationUri.equals("system")) notificationUri = prefs.getString("SystemUri", ""); else if (notificationUri.equals("file")) notificationUri = prefs.getString("FileUri", ""); else if (notificationUri.equals("tts")) { notificationUri = ""; final String ttsString = prefs.getString("tts_string", context.getString(R.string.timer_done)); Intent ttsIntent = new Intent(context, TTSService.class); ttsIntent.putExtra("spoken_text", ttsString); context.startService(ttsIntent); } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext()) .setSmallIcon(R.drawable.notification).setContentTitle(text).setContentText(textLatest); Uri uri = null; // Play a sound! if (!notificationUri.equals("")) uri = Uri.parse(notificationUri); // Vibrate if (vibrate && uri == null) { mBuilder.setDefaults(Notification.DEFAULT_VIBRATE); } // Have a light if (led) { mBuilder.setLights(0xff00ff00, 300, 1000); } mBuilder.setAutoCancel(true); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(context, TimerActivity.class); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(TimerActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); // Create intent for cancelling the notification Context appContext = context.getApplicationContext(); Intent intent = new Intent(appContext, TimerReceiver.class); intent.setAction(CANCEL_NOTIFICATION); // Cancel the pending cancellation and create a new one PendingIntent pendingCancelIntent = PendingIntent.getBroadcast(appContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); if (uri != null) { //remove notification sound mBuilder.setSound(null); try { if (player != null && player.isPlaying()) { player.release(); player = new MediaPlayer(); } int currVolume = prefs.getInt("tone_volume", 0); if (currVolume != 0) { float log1 = (float) (Math.log(100 - currVolume) / Math.log(100)); player.setVolume(1 - log1, 1 - log1); } player.setDataSource(context, uri); player.prepare(); player.setLooping(false); player.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); player.start(); if (vibrate) { Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(1000); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (prefs.getBoolean("AutoClear", false)) { // Determine duration of notification sound int duration = 5000; if (uri != null) { MediaPlayer cancelPlayer = new MediaPlayer(); try { cancelPlayer.setDataSource(context, uri); cancelPlayer.prepare(); duration = Math.max(duration, cancelPlayer.getDuration() + 2000); } catch (java.io.IOException ex) { Log.e(TAG, "Cannot get sound duration: " + ex); duration = 30000; // on error, default to 30 seconds } finally { cancelPlayer.release(); } cancelPlayer.release(); } Log.v(TAG, "Notification duration: " + duration + " ms"); // Schedule cancellation AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + duration, pendingCancelIntent); } if (useAdvTime && advTimeString.length() > 0) { Intent broadcast = new Intent(); SharedPreferences.Editor editor = prefs.edit(); if (advTimeIndex < advTime.length) { editor.putInt("advTimeIndex", advTimeIndex + 1); String[] thisAdvTime = advTime[advTimeIndex].split("#"); // will be of format timeInMs#pathToSound int time = Integer.parseInt(thisAdvTime[0]); broadcast.putExtra("time", time); // Save new time editor.putLong("TimeStamp", new Date().getTime() + time); editor.putInt("LastTime", time); // editor.putString("NotificationUri", thisAdvTime[1]); mNM.cancelAll(); Log.v(TAG, "Starting next iteration of the timer service ..."); Intent rintent = new Intent(context, TimerReceiver.class); rintent.putExtra("SetTime", time); PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent); } else { broadcast.putExtra("stop", true); editor.putInt("advTimeIndex", 1); } broadcast.setAction(BROADCAST_RESET); context.sendBroadcast(broadcast); editor.apply(); } else if (prefs.getBoolean("AutoRestart", false)) { int time = pintent.getIntExtra("SetTime", 0); if (time != 0) { mNM.cancel(0); Log.v(TAG, "Restarting the timer service ..."); Intent rintent = new Intent(context, TimerReceiver.class); rintent.putExtra("SetTime", time); PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent); // Save new time SharedPreferences.Editor editor = prefs.edit(); editor.putLong("TimeStamp", new Date().getTime() + time); editor.putInt("LastTime", time); editor.apply(); Intent broadcast = new Intent(); broadcast.putExtra("time", time); broadcast.setAction(BROADCAST_RESET); context.sendBroadcast(broadcast); } } mNotificationManager.notify(0, mBuilder.build()); Log.d(TAG, "ALARM: alarm finished"); }
From source file:com.swetha.easypark.GetIndividualParkingSpotDetails.java
private void scheduleNotification(Notification notification) { Intent notificationIntent = new Intent(this, NotificationPublisher.class); notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, Integer.parseInt(theParkingSpotId)); notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); long currentTimeInLong = DateTimeHelpers .convertToLongFromTime(DateTimeHelpers.dtf.format(new Date()).toString()); long delay = toTime - (currentTimeInLong + Constants.tenMinutesInMilliseconds); long futureInMills = SystemClock.elapsedRealtime() + delay; Log.i("GetIndividualParkingSpotDetails", " Spot has been blocked till long " + toTime); Log.i("GetIndividualParkingSpotDetails", " Spot has been blocked till DateTime" + DateTimeHelpers.convertToTimeFromLong(toTime)); Log.i("GetIndividualParkingSpotDetails", " CurrentTime in long " + currentTimeInLong); Log.i("GetIndividualParkingSpotDetails", " Spot has been blocked till DateTime" + DateTimeHelpers.convertToTimeFromLong(currentTimeInLong)); Log.i("GetIndividualParkingSpotDetails", "value of delay" + delay); Log.i("GetIndividualParkingSpotDetails", "value of mills in time" + DateTimeHelpers.convertToTimeFromLong(futureInMills)); Log.i("GetIndividualParkingSpotDetails", "Notification is kept at this mills" + futureInMills); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMills, pendingIntent); }
From source file:org.pixmob.freemobile.netstat.SyncService.java
public static void schedule(Context context, boolean enabled) { final Context appContext = context.getApplicationContext(); final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); final PendingIntent syncIntent = PendingIntent.getService(appContext, 0, new Intent(appContext, SyncService.class), PendingIntent.FLAG_CANCEL_CURRENT); am.cancel(syncIntent);//from w ww . j ava2 s . c o m if (enabled) { // Set the sync period. long period = AlarmManager.INTERVAL_HOUR; final int syncErrors = context.getSharedPreferences(INTERNAL_SP_NAME, MODE_PRIVATE) .getInt(INTERNAL_SP_KEY_SYNC_ERRORS, 0); if (syncErrors != 0) { // When there was a sync error, the sync period is longer. period = AlarmManager.INTERVAL_HOUR * Math.min(syncErrors, MAX_SYNC_ERRORS); } // Add a random time to prevent concurrent requests for the server. final long fuzz = RANDOM.nextInt(1000 * 60 * 30); period += fuzz; if (DEBUG) { Log.d(TAG, "Scheduling synchronization: next in " + (period / 1000 / 60) + " minutes"); } final long syncTime = System.currentTimeMillis() + period; am.set(AlarmManager.RTC_WAKEUP, syncTime, syncIntent); } else { if (DEBUG) { Log.d(TAG, "Synchronization schedule canceled"); } } }
From source file:com.android.settings.cyanogenmod.LtoService.java
private PendingIntent scheduleNextDownload(long lastDownload) { AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(this, LtoService.class); PendingIntent pi = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT); long nextLtoDownload = lastDownload + LongTermOrbits.getDownloadInterval(); am.set(AlarmManager.RTC, nextLtoDownload, pi); return pi;/*from w ww . j av a 2s . c om*/ }
From source file:cc.softwarefactory.lokki.android.androidServices.LocationService.java
private void setTemporalTimer() { AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE); Intent alarmIntent = new Intent(this, LocationService.class); alarmIntent.putExtra(ALARM_TIMER, 1); PendingIntent alarmCallback = PendingIntent.getService(this, 0, alarmIntent, 0); alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + INTERVAL_1_MIN, alarmCallback);//from w ww . j a v a 2s.com Log.d(TAG, "Time created."); }
From source file:com.tvs.signaltracker.MainScreen.java
@Override protected void onResume() { super.onResume(); CleanUp();//from ww w .j a v a2 s .c o m try { if (STService.Opened == false) { Intent myIntent = new Intent(MainScreen.this, STService.class); PendingIntent pendingIntent = PendingIntent.getService(MainScreen.this, 0, myIntent, 0); AlarmManager alarmManager = (AlarmManager) MainScreen.this.getSystemService(Context.ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 1); alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); } } catch (Exception e) { Log.e("SignalTracker::onResume(MainScreen)", "Erro ao iniciar servio: " + e.getMessage()); } if (!CommonHandler.ServiceRunning) CommonHandler.LoadLists(); setUpMap(); InitUp(); }
From source file:com.google.samples.apps.iosched.service.SessionAlarmService.java
public void scheduleFeedbackAlarm(final long sessionEnd, final long alarmOffset, final String sessionTitle) { // By default, feedback alarms fire 5 minutes before session end time. If alarm offset is // provided, alarm is set to go off that much time from now (useful for testing). long alarmTime; if (alarmOffset == UNDEFINED_ALARM_OFFSET) { alarmTime = sessionEnd - MILLI_FIVE_MINUTES; } else {//from ww w . j a v a 2s .c o m alarmTime = UIUtils.getCurrentTime(this) + alarmOffset; } LOGD(TAG, "Scheduling session feedback alarm for session '" + sessionTitle + "'"); LOGD(TAG, " -> end time: " + sessionEnd + " = " + (new Date(sessionEnd)).toString()); LOGD(TAG, " -> alarm time: " + alarmTime + " = " + (new Date(alarmTime)).toString()); final Intent feedbackIntent = new Intent(ACTION_NOTIFY_SESSION_FEEDBACK, null, this, SessionAlarmService.class); PendingIntent pi = PendingIntent.getService(this, 1, feedbackIntent, PendingIntent.FLAG_CANCEL_CURRENT); final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi); }
From source file:com.razza.apps.iosched.service.SessionAlarmService.java
public void scheduleFeedbackAlarm(final long sessionEnd, final long alarmOffset, final String sessionTitle) { // By default, feedback alarms fire 5 minutes before session end time. If alarm offset is // provided, alarm is set to go off that much time from now (useful for testing). long alarmTime; if (alarmOffset == UNDEFINED_ALARM_OFFSET) { alarmTime = sessionEnd - MILLI_FIVE_MINUTES; } else {//from ww w . j av a 2 s .co m alarmTime = UIUtils.getCurrentTime(this) + alarmOffset; } LogUtils.LOGD(TAG, "Scheduling session feedback alarm for session '" + sessionTitle + "'"); LogUtils.LOGD(TAG, " -> end time: " + sessionEnd + " = " + (new Date(sessionEnd)).toString()); LogUtils.LOGD(TAG, " -> alarm time: " + alarmTime + " = " + (new Date(alarmTime)).toString()); final Intent feedbackIntent = new Intent(ACTION_NOTIFY_SESSION_FEEDBACK, null, this, SessionAlarmService.class); PendingIntent pi = PendingIntent.getService(this, 1, feedbackIntent, PendingIntent.FLAG_CANCEL_CURRENT); final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi); }
From source file:com.nbplus.vbroadlistener.gcm.RegistrationIntentService.java
@Override protected void onHandleIntent(Intent intent) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); String action = intent.getAction(); String token = null;//from w w w .j a v a 2 s .c om if (Constants.REGISTER_GCM.equals(action) || Constants.UPDATE_GCM.equals(action)) { try { // In the (unlikely) event that multiple refresh operations occur simultaneously, // ensure that they are processed sequentially. synchronized (TAG) { // [START register_for_gcm] // Initially this call goes out to the network to retrieve the token, subsequent calls // are local. // [START get_token] LauncherSettings.getInstance(this).setGcmToken(""); LauncherSettings.getInstance(this).setGcmSentToServerStatus(false); LauncherSettings.getInstance(this).setGcmRegisteredStatus(false); InstanceID instanceID = InstanceID.getInstance(this); token = instanceID.getToken(Constants.GCM_SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); // [END get_token] Log.i(TAG, "GCM Registration Token: " + token); /** * 2015.07.17 * ?? ?? ? ... ? ? ? * ?? ? ?? ?? ? Native? . */ if (Constants.UPDATE_GCM.equals(action)) { boolean result = sendRegistrationToServer(token); LauncherSettings.getInstance(this).setGcmSentToServerStatus(result); if (!result) { Log.i(TAG, "setAlarm() = 5min"); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(this, RegistrationIntentService.class); i.setAction(Constants.UPDATE_GCM); PendingIntent pIntent = PendingIntent.getService(this, 0, i, 0); alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 60 * 5 * 1000, pIntent); startService(i); } } else { LauncherSettings.getInstance(this).setGcmSentToServerStatus(true); // Subscribe to topic channels subscribeTopics(token); } // You should store a boolean that indicates whether the generated token has been // sent to your server. If the boolean is false, send the token to your server, // otherwise your server should have already received the token. LauncherSettings.getInstance(this).setGcmRegisteredStatus(true); LauncherSettings.getInstance(this).setGcmToken(token); // [END register_for_gcm] } } catch (Exception e) { Log.d(TAG, "Failed to complete token refresh", e); // If an exception happens while fetching the new token or updating our registration data // on a third-party server, this ensures that we'll attempt the update at a later time. LauncherSettings.getInstance(this).setGcmSentToServerStatus(false); if (!StringUtils.isEmptyString(token)) { LauncherSettings.getInstance(this).setGcmToken(token); LauncherSettings.getInstance(this).setGcmRegisteredStatus(true); } } // Notify UI that registration has completed, so the progress indicator can be hidden. Intent registrationComplete = new Intent(Constants.REGISTRATION_COMPLETE); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); } else if (Constants.UNREGISTER_GCM.equals(action)) { try { // In the (unlikely) event that multiple refresh operations occur simultaneously, // ensure that they are processed sequentially. synchronized (TAG) { // [START register_for_gcm] // Initially this call goes out to the network to retrieve the token, subsequent calls // are local. // [START get_token] InstanceID instanceID = InstanceID.getInstance(this); token = instanceID.getToken(Constants.GCM_SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); // TODO: Implement this method to send any registration to your app's servers. sendUnRegistrationToServer(token); // Subscribe to topic channels unSubscribeTopics(token); instanceID.deleteToken(Constants.GCM_SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE); // [END get_token] Log.i(TAG, "GCM Registration Token: " + token); // You should store a boolean that indicates whether the generated token has been // sent to your server. If the boolean is false, send the token to your server, // otherwise your server should have already received the token. LauncherSettings.getInstance(this).setGcmSentToServerStatus(false); LauncherSettings.getInstance(this).setGcmRegisteredStatus(false); LauncherSettings.getInstance(this).setGcmToken(""); // [END register_for_gcm] } } catch (Exception e) { Log.d(TAG, "Failed to complete token refresh", e); // If an exception happens while fetching the new token or updating our registration data // on a third-party server, this ensures that we'll attempt the update at a later time. LauncherSettings.getInstance(this).setGcmSentToServerStatus(false); LauncherSettings.getInstance(this).setGcmRegisteredStatus(false); LauncherSettings.getInstance(this).setGcmToken(""); } // Notify UI that registration has completed, so the progress indicator can be hidden. Intent registrationComplete = new Intent(Constants.UNREGISTRATION_COMPLETE); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); } }
From source file:com.michael.feng.textlater.NewActivity.java
private void scheduleTask(Message message) { Calendar calendar = Calendar.getInstance(); if (null != whenMap && whenMap.containsKey("year")) { calendar.set(Calendar.YEAR, whenMap.get("year")); calendar.set(Calendar.MONTH, whenMap.get("month")); calendar.set(Calendar.DAY_OF_MONTH, whenMap.get("day")); calendar.set(Calendar.HOUR_OF_DAY, whenMap.get("hour")); calendar.set(Calendar.MINUTE, whenMap.get("min")); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); cleanWhenMap();/*from ww w. j a v a2s.c o m*/ } Intent intent = new Intent(this, AlarmReceiver.class); intent.putExtra("textContact", message.getTextContact().trim()); intent.putExtra("textNumber", message.getTextNumber().trim()); intent.putExtra("textWhen", message.getTextWhen()); intent.putExtra("textContent", message.getTextContent()); // Different requestCode can lead to different PendingIntent PendingIntent pendingIntent = PendingIntent.getBroadcast(this, (int) calendar.getTimeInMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); Log.d("requstcode in new-->", calendar.getTimeInMillis() + ""); // AlarmManager.RTC_WAKEUP can be executed when CPU sleep // AlarmManager.RTC can't be executed when CPU sleep am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); }