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:com.windroilla.invoker.gcm.MyGcmListenerService.java
/** * Called when message is received.//from ww w . ja va 2 s. com * * @param from SenderID of the sender. * @param data Data bundle containing message data as key/value pairs. * For Set of keys use data.keySet(). */ // [START receive_message] @Override public void onMessageReceived(String from, Bundle data) { String message = data.getString("message"); Log.d(TAG, "From: " + from); Log.d(TAG, "Message: " + message); if (from.startsWith("/topics/")) { // message received from some topic. } else { Log.i("Device ID ", deviceID); // normal downstream message. apiService.getBlockTimes(new RequestBlockTimes(deviceID)).subscribeOn(Schedulers.newThread()) .observeOn(Schedulers.newThread()).subscribe(new Action1<BlockTimeList>() { @Override public void call(BlockTimeList blockTimeList) { Log.d(TAG, blockTimeList.access_time); Vector<ContentValues> cVVector = new Vector<ContentValues>( blockTimeList.getBlockTimes().size()); AlarmManager mgrAlarm = (AlarmManager) getApplicationContext() .getSystemService(ALARM_SERVICE); ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); formatter.setLenient(false); for (int i = 0; i < blockTimeList.getBlockTimes().size(); i++) { BlockTime blockTime = blockTimeList.getBlockTimes().get(i); Log.d(TAG, blockTime.getCourse_id() + " " + blockTime.getId() + " " + blockTime.getStarttime() + " " + blockTime.getEndtime() + " " + blockTime.getCreated_time()); ContentValues blockTimeValues = new ContentValues(); blockTimeValues.put(BlocktimeContract.BlocktimeEntry.COLUMN_START_TIME, blockTime.getStarttime()); blockTimeValues.put(BlocktimeContract.BlocktimeEntry.COLUMN_END_TIME, blockTime.getEndtime()); blockTimeValues.put(BlocktimeContract.BlocktimeEntry.COLUMN_CREATED_TIME, blockTime.getCreated_time()); Intent startIntent = new Intent(getBaseContext(), AlarmReceiver.class); startIntent.setAction("com.windroilla.invoker.blockservice.start"); Intent endIntent = new Intent(getBaseContext(), AlarmReceiver.class); endIntent.setAction("com.windroilla.invoker.blockservice.stop"); PendingIntent pendingStartIntent = PendingIntent.getBroadcast( getApplicationContext(), blockTime.getId(), startIntent, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent pendingEndIntent = PendingIntent.getBroadcast(getApplicationContext(), -blockTime.getId(), endIntent, PendingIntent.FLAG_UPDATE_CURRENT); try { mgrAlarm.set(AlarmManager.RTC_WAKEUP, formatter.parse(blockTime.getStarttime()).getTime(), pendingStartIntent); Log.d(TAG, formatter.parse(blockTime.getStarttime()).getTime() + " " + System.currentTimeMillis() + " " + (formatter.parse(blockTime.getStarttime()).getTime() - System.currentTimeMillis())); Log.d(TAG, formatter.parse(blockTime.getEndtime()).getTime() + " " + System.currentTimeMillis() + " " + (formatter.parse(blockTime.getEndtime()).getTime() - System.currentTimeMillis())); mgrAlarm.set(AlarmManager.RTC_WAKEUP, formatter.parse(blockTime.getEndtime()).getTime(), pendingEndIntent); } catch (ParseException e) { Log.e(TAG, e.toString()); } intentArray.add(pendingStartIntent); intentArray.add(pendingEndIntent); cVVector.add(blockTimeValues); } Log.d(TAG, intentArray.size() + " PendingIntents have been progressed"); int inserted = 0; // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); getBaseContext().getContentResolver() .bulkInsert(BlocktimeContract.BlocktimeEntry.CONTENT_URI, cvArray); } } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { Log.e(TAG, "BlockTimes Sync failed! " + throwable); } }); } // [START_EXCLUDE] /** * Production applications would usually process the message here. * Eg: - Syncing with server. * - Store message in local database. * - Update UI. */ /** * In some cases it may be useful to show a notification indicating to the user * that a message was received. */ sendNotification(message); // [END_EXCLUDE] }
From source file:org.kontalk.service.msgcenter.MessageCenterService.java
void setWakeupAlarm() { long delay = Preferences.getWakeupTimeMillis(this, MIN_WAKEUP_TIME); // start message center pending intent PendingIntent pi = PendingIntent.getService(getApplicationContext(), 0, getStartIntent(this), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT); // we don't use the shared alarm manager instance here // since this can happen after the service has begun to stop AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delay, pi); }
From source file:com.av.remusic.service.MediaService.java
public void timing(int time) { PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(PAUSE_ACTION), PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); am.set(AlarmManager.RTC, System.currentTimeMillis() + time, pendingIntent); }
From source file:com.guardtrax.ui.screens.HomeScreen.java
private void showAlert(final String title, final String message, boolean OKOnly) { AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this); dialog.setCancelable(false);//from www. j a va2s . com dialog.setTitle(title); dialog.setMessage(message); dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int place) { //if device not registered go straight to scan screen if (!Utility.deviceRegistered()) scan_click(false); //if OK entered from updateSync then reboot if (restartsyncTimer) { Intent restartIntent = getPackageManager().getLaunchIntentForPackage(getPackageName()); PendingIntent intent = PendingIntent.getActivity(HomeScreen.this, 0, restartIntent, Intent.FLAG_ACTIVITY_CLEAR_TOP); AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); manager.set(AlarmManager.RTC, System.currentTimeMillis() + 500, intent); System.exit(2); } if (taa == 5) { taa = 3; //when returning to onResume from signature screen this will execute specific code inside onResume signaturefileName = Utility.createSignatureFileName(); Intent intent = new Intent(); intent.setClass(HomeScreen.this, SignatureScreen.class); intent.putExtra("file_name", Utility.getsharedPreference(HomeScreen.this, "signaturefileName")); startActivity(intent); } } }); if (!OKOnly) { dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int place) { if (taa == 5) { taa = 3; //tells onResume to execute end shift code onResume(); } } }); } dialog.show(); }
From source file:com.guardtrax.ui.screens.HomeScreen.java
@Override public void onResume() { //if exiting from the scan screen with an unregistered app if (GTConstants.exitingScanScreen && !Utility.deviceRegistered()) onBackPressed();/*w ww .ja v a 2 s. c o m*/ //if this is a newly registered app then reboot if (newRegistration && Utility.deviceRegistered()) { try { Intent restartIntent = getPackageManager().getLaunchIntentForPackage(getPackageName()); PendingIntent intent = PendingIntent.getActivity(HomeScreen.this, 0, restartIntent, Intent.FLAG_ACTIVITY_CLEAR_TOP); AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); manager.set(AlarmManager.RTC, System.currentTimeMillis() + 500, intent); System.exit(2); } catch (Exception e) { Toast.makeText(getApplicationContext(), "ON RESUME ERROR: " + e, Toast.LENGTH_LONG).show(); } } else { if (!ScreenReceiver.wasScreenOn) { //Toast.makeText(getApplicationContext(), "ON RESUME", Toast.LENGTH_LONG).show(); //if(ftpDownload.getStatus() != AsyncTask.Status.RUNNING)syncFTP(); //syncFTP(); } syncFTP(); setuserBanner(); //if returning from tag scan for time and attendance after an end shift then taa was set to 1 //set taa to 2 and then launch dialog to display the time and attendance record and then signature page if (taa == 1) { taa = 0; } if (taa == 2) { //write to tar, transfer file to send directory Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.tarfileName, "End shift;" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", true); //write additional info to tar file Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.tarfileName, "Total Time;" + Utility.gettimeDiff(Utility.getsessionStart(), Utility.getLocalDateTime()) + "\r\n" + "Time on Lunch;" + lunchTime + "\r\n" + "Time on Break;" + breakTime + "\r\n", true); //give time for file write Utility.initializeGeneralTimer(2000); do { Utility.Sleep(100); } while (!Utility.fileAccessComplete() && !Utility.getgeneraltimerFlag()); lunchTime = "00:00:00:00"; breakTime = "00:00:00:00"; taa = 5; show_taaSignature_dialog(); //returning from end shift location scan } if (taa == 3) { //write the event 25 information to the file String GM = ""; if (GTConstants.isSignature) { GM = Utility.getHeaderMessage("$GM") + ",25," + getCellID() + CRLF + "***SIGNATURE***" + CRLF + Utility.getsharedPreference(HomeScreen.this, "signaturefileName"); GTConstants.isSignature = false; signaturefileName = ""; } else GM = Utility.getHeaderMessage("$GM") + ",25," + getCellID(); Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.tarfileName, GM + "\r\n", true); //give time for file write Utility.initializeGeneralTimer(2000); do { Utility.Sleep(100); } while (!Utility.fileAccessComplete() && !Utility.getgeneraltimerFlag()); //move the tar file to the send file folder File from = new File(GTConstants.dardestinationFolder, GTConstants.tarfileName); //change the file name to match the $GM time and date String[] parse = GM.split(","); String newFile = GTConstants.LICENSE_ID.substring(7) + "_" + parse[10] + "_" + parse[2] + "_tar.tar"; File to = new File(GTConstants.sendfileFolder, newFile); from.renameTo(to); endshiftCode(); taa = 0; } //check if the tag is in a tour if (GTConstants.exitingScanScreen) { if (GTConstants.isTour) { if (GTConstants.tourName.length() == 1) { if (getlasttagScanned().length() == 16) show_tours_dialog(true); } else { updateTour(getlasttagScanned()); } } //check if this is an account setup tag, designated by an "@&" as the first two characters if (getlasttagScanned().length() == 16) { String temp = Utility.get_from_GTParamsDataBase(HomeScreen.this, getlasttagScanned()); if (temp.contains("@&")) { temp = temp.substring(2); setupAccounts("0", temp); //Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_LONG).show(); } } GTConstants.exitingScanScreen = false; } } super.onResume(); }
From source file:de.anderdonau.spacetrader.Main.java
public void btnChangeTheme(View view) { SharedPreferences sp = getSharedPreferences("spacetrader", MODE_PRIVATE); SharedPreferences.Editor ed = sp.edit(); String theme = sp.getString("Theme", "Light"); if (view.getId() == R.id.btnDarkTheme) { if ("Dark".equals(theme)) { Toast.makeText(this, "This theme is already selected.", Toast.LENGTH_SHORT).show(); return; }//from www . j a v a 2 s. co m ed.putString("Theme", "Dark"); } else { if ("Light".equals(theme)) { Toast.makeText(this, "This theme is already selected.", Toast.LENGTH_SHORT).show(); return; } ed.putString("Theme", "Light"); } ed.commit(); Popup popup = new Popup(this, "Change Theme", "Space Trader must be restarted to change the theme. Do you want to do that now?", "", "Restart now", "Restart later", new Popup.buttonCallback() { @Override public void execute(Popup popup, View view) { saveGame(); Intent mStartActivity = new Intent(getApplicationContext(), Main.class); int mPendingIntentId = Math.abs(gameState.rand.nextInt()); //noinspection ConstantConditions PendingIntent mPendingIntent = PendingIntent.getActivity(getApplicationContext(), mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager mgr = (AlarmManager) getApplicationContext() .getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent); System.exit(0); } }, cbShowNextPopup); addPopup(popup); showNextPopup(); }
From source file:com.battlelancer.seriesguide.service.NotificationService.java
@SuppressLint("CommitPrefEdits") @TargetApi(android.os.Build.VERSION_CODES.KITKAT) @Override/*ww w . j a va2s . c o m*/ protected void onHandleIntent(Intent intent) { Timber.d("Waking up..."); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); /* * Handle a possible delete intent. */ if (handleDeleteIntent(this, intent)) { return; } /* * Unschedule notification service wake-ups for disabled notifications * and non-supporters. */ if (!NotificationSettings.isNotificationsEnabled(this) || !Utils.hasAccessToX(this)) { Timber.d("Notification service disabled, removing wakup-up alarm"); // cancel any pending alarm AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(this, OnAlarmReceiver.class); PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0); am.cancel(pi); resetLastEpisodeAirtime(prefs); return; } long wakeUpTime = 0; /* * Get pool of episodes which air from 12 hours ago until eternity which * match the users settings. */ StringBuilder selection = new StringBuilder(SELECTION); boolean isFavsOnly = NotificationSettings.isNotifyAboutFavoritesOnly(this); Timber.d("Do notify about " + (isFavsOnly ? "favorites ONLY" : "ALL")); if (isFavsOnly) { selection.append(" AND ").append(Shows.SELECTION_FAVORITES); } boolean isNoSpecials = DisplaySettings.isHidingSpecials(this); Timber.d("Do " + (isNoSpecials ? "NOT " : "") + "notify about specials"); if (isNoSpecials) { selection.append(" AND ").append(Episodes.SELECTION_NO_SPECIALS); } // always exclude hidden shows selection.append(" AND ").append(Shows.SELECTION_NO_HIDDEN); final long customCurrentTime = TimeTools.getCurrentTime(this); final Cursor upcomingEpisodes = getContentResolver().query(Episodes.CONTENT_URI_WITHSHOW, PROJECTION, selection.toString(), new String[] { String.valueOf(customCurrentTime - 12 * DateUtils.HOUR_IN_MILLIS) }, SORTING); if (upcomingEpisodes != null) { int notificationThreshold = NotificationSettings.getLatestToIncludeTreshold(this); if (DEBUG) { Timber.d("DEBUG MODE: notification threshold is 1 week"); // a week, for debugging (use only one show to get single // episode notifications) notificationThreshold = 10080; // notify again for same episodes resetLastEpisodeAirtime(prefs); } final long nextEpisodeReleaseTime = NotificationSettings.getNextToNotifyAbout(this); // wake user-defined amount of time earlier than next episode release time final long plannedWakeUpTime = TimeTools.getEpisodeReleaseTime(this, nextEpisodeReleaseTime).getTime() - DateUtils.MINUTE_IN_MILLIS * notificationThreshold; /* * Set to -1 as on first run nextTimePlanned will be 0. This assures * we still see notifications of upcoming episodes then. */ int newEpisodesAvailable = -1; // Check if we did wake up earlier than planned if (System.currentTimeMillis() < plannedWakeUpTime) { Timber.d("Woke up earlier than planned, checking for new episodes"); newEpisodesAvailable = 0; long latestTimeNotified = NotificationSettings.getLastNotified(this); // Check if there are any earlier episodes to notify about while (upcomingEpisodes.moveToNext()) { final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS); if (releaseTime < nextEpisodeReleaseTime) { if (releaseTime > latestTimeNotified) { /** * This will not get new episodes which would have * aired the same time as the last one we notified * about. Sad, but the best we can do right now. */ newEpisodesAvailable = 1; break; } } else { break; } } } if (newEpisodesAvailable == 0) { // Go to sleep, wake up as planned Timber.d("No new episodes, going to sleep."); wakeUpTime = plannedWakeUpTime; } else { // Get episodes which are within the notification threshold // (user set) and not yet cleared final List<Integer> notifyPositions = new ArrayList<>(); final long latestTimeCleared = NotificationSettings.getLastCleared(this); final long latestTimeToInclude = customCurrentTime + DateUtils.MINUTE_IN_MILLIS * notificationThreshold; int position = -1; upcomingEpisodes.moveToPosition(position); while (upcomingEpisodes.moveToNext()) { position++; final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS); if (releaseTime <= latestTimeToInclude) { /* * Only add those after the last one the user cleared. * At most those of the last 24 hours (see query above). */ if (releaseTime > latestTimeCleared) { notifyPositions.add(position); } } else { // Too far into the future, stop! break; } } // Notify if we found any episodes if (notifyPositions.size() > 0) { // store latest air time of all episodes we notified about upcomingEpisodes.moveToPosition(notifyPositions.get(notifyPositions.size() - 1)); long latestAirtime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS); if (!AndroidUtils.isHoneycombOrHigher()) { /* * Everything below HC does not have delete intents, so * we just never notify about the same episode twice. */ Timber.d("Delete intent NOT supported, setting last cleared to: " + latestAirtime); prefs.edit().putLong(NotificationSettings.KEY_LAST_CLEARED, latestAirtime).commit(); } Timber.d("Found " + notifyPositions.size() + " new episodes, setting last notified to: " + latestAirtime); prefs.edit().putLong(NotificationSettings.KEY_LAST_NOTIFIED, latestAirtime).commit(); onNotify(upcomingEpisodes, notifyPositions, latestAirtime); } /* * Plan next episode to notify about, calc wake-up alarm as * early as user wants. */ upcomingEpisodes.moveToPosition(-1); while (upcomingEpisodes.moveToNext()) { final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS); if (releaseTime > latestTimeToInclude) { // store next episode we plan to notify about Timber.d("Storing next episode time to notify about: " + releaseTime); prefs.edit().putLong(NotificationSettings.KEY_NEXT_TO_NOTIFY, releaseTime).commit(); // calc actual wake up time wakeUpTime = TimeTools.getEpisodeReleaseTime(this, releaseTime).getTime() - DateUtils.MINUTE_IN_MILLIS * notificationThreshold; break; } } } upcomingEpisodes.close(); } // Set a default wake-up time if there are no future episodes for now if (wakeUpTime <= 0) { wakeUpTime = System.currentTimeMillis() + 6 * DateUtils.HOUR_IN_MILLIS; Timber.d("No future episodes found, wake up in 6 hours"); } AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(this, NotificationService.class); PendingIntent pi = PendingIntent.getService(this, 0, i, 0); Timber.d("Going to sleep, setting wake-up alarm to: " + wakeUpTime); if (AndroidUtils.isKitKatOrHigher()) { am.setExact(AlarmManager.RTC_WAKEUP, wakeUpTime, pi); } else { am.set(AlarmManager.RTC_WAKEUP, wakeUpTime, pi); } }
From source file:com.codename1.impl.android.AndroidImplementation.java
public void scheduleLocalNotification(LocalNotification notif, long firstTime, int repeat) { final Intent notificationIntent = new Intent(getContext(), LocalNotificationPublisher.class); notificationIntent.setAction(getContext().getApplicationInfo().packageName + "." + notif.getId()); notificationIntent.putExtra(LocalNotificationPublisher.NOTIFICATION, createBundleFromNotification(notif)); Intent contentIntent = new Intent(); if (getActivity() != null) { contentIntent.setComponent(getActivity().getComponentName()); }/*from w ww . java 2 s.com*/ contentIntent.putExtra("LocalNotificationID", notif.getId()); if (BACKGROUND_FETCH_NOTIFICATION_ID.equals(notif.getId()) && getBackgroundFetchListener() != null) { Context context = AndroidNativeUtil.getContext(); Intent intent = new Intent(context, BackgroundFetchHandler.class); //there is an bug that causes this to not to workhttps://code.google.com/p/android/issues/detail?id=81812 //intent.putExtra("backgroundClass", getBackgroundLocationListener().getName()); //an ugly workaround to the putExtra bug intent.setData( Uri.parse("http://codenameone.com/a?" + getBackgroundFetchListener().getClass().getName())); PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); notificationIntent.putExtra(LocalNotificationPublisher.BACKGROUND_FETCH_INTENT, pendingIntent); } else { contentIntent.setData( Uri.parse("http://codenameone.com/a?LocalNotificationID=" + Uri.encode(notif.getId()))); } PendingIntent pendingContentIntent = PendingIntent.getActivity(getContext(), 0, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT); notificationIntent.putExtra(LocalNotificationPublisher.NOTIFICATION_INTENT, pendingContentIntent); PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE); if (BACKGROUND_FETCH_NOTIFICATION_ID.equals(notif.getId())) { alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, getPreferredBackgroundFetchInterval() * 1000, pendingIntent); } else { if (repeat == LocalNotification.REPEAT_NONE) { alarmManager.set(AlarmManager.RTC_WAKEUP, firstTime, pendingIntent); } else if (repeat == LocalNotification.REPEAT_MINUTE) { alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, 60 * 1000, pendingIntent); } else if (repeat == LocalNotification.REPEAT_HOUR) { alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstTime, AlarmManager.INTERVAL_HALF_HOUR, pendingIntent); } else if (repeat == LocalNotification.REPEAT_DAY) { alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstTime, AlarmManager.INTERVAL_DAY, pendingIntent); } else if (repeat == LocalNotification.REPEAT_WEEK) { alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, AlarmManager.INTERVAL_DAY * 7, pendingIntent); } } }