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:nz.co.wholemeal.christchurchmetro.PlatformActivity.java
/** * Fires a notification when the arrival is the given number of minutes * away from arriving at this stop.//www . ja v a2s .com * * @param arrival The arrival that this alarm is set for * @param minutes The number of minutes before arrival the alert should be raised */ protected void createNotificationForArrival(Arrival arrival, int minutes) { Intent intent = new Intent(this, ArrivalNotificationReceiver.class); intent.putExtra("routeNumber", arrival.routeNumber); intent.putExtra("destination", arrival.destination); intent.putExtra("tripNumber", arrival.tripNumber); intent.putExtra("platformTag", current_stop.platformTag); intent.putExtra("minutes", minutes); PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); /** * Calculate the time delay for this alarm. We add 2 minutes to the * requested time in case the bus makes up time on it's journey from * when the user set the alarm. In that case, the * ArrivalNotificationReceiver will take care of resetting itself if the * bus ETA is still greater than the requested number of minutes. */ int delay = arrival.eta - (minutes + 2); Calendar calendar = Calendar.getInstance(); /** * Set the time for comparison from the time the arrival was fetched, * not the current time. The user may have had the screen loaded * for some time without refresh, so the arrival eta may no longer be * accurate. */ long timestamp = current_stop.lastArrivalFetch; // Safety net if (timestamp == 0) { timestamp = System.currentTimeMillis(); } calendar.setTimeInMillis(timestamp); calendar.add(Calendar.MINUTE, delay); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender); String alarmTime = DateFormat.getTimeInstance().format(calendar.getTime()); Toast.makeText(this, String.format(getResources().getString(R.string.set_alarm_for_eta), minutes), Toast.LENGTH_LONG).show(); Log.d(TAG, "Set alarm for " + minutes + " minutes - " + alarmTime); }
From source file:net.texh.cordovapluginstepcounter.StepCounterService.java
@Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG, "onStartCommand"); SharedPreferences sharedPref = getSharedPreferences(CordovaStepCounter.USER_DATA_PREF, Context.MODE_PRIVATE); Boolean pActive = CordovaStepCounter.getPedometerIsActive(sharedPref); //Service should not be activated (pedometer stopped by user) if (!pActive) { Log.i(TAG,/*from www. j av a 2 s.c o m*/ "/!\\ onStartCommand Ask to stopSelf, should not be launched ! Should not even be here (maybe 4.4.2 specific bug causes a restart here)"); stopSelf(); return START_NOT_STICKY; } Log.i(TAG, "- Relaunch service in 1 hour (4.4.2 start_sticky bug ) : "); Intent newServiceIntent = new Intent(this, StepCounterService.class); AlarmManager aManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); PendingIntent stepIntent = PendingIntent.getService(getApplicationContext(), 10, newServiceIntent, PendingIntent.FLAG_UPDATE_CURRENT); //PendingIntent.GetService (ApplicationContext, 10, intent2, PendingIntentFlags.UpdateCurrent); aManager.set(AlarmManager.RTC, java.lang.System.currentTimeMillis() + 1000 * 60 * 60, stepIntent); if (isRunning /* || has no step sensors */) { Log.i(TAG, "Not initialising sensors"); return Service.START_STICKY; } Log.i(TAG, "Initialising sensors"); doInit(); isRunning = true; return Service.START_STICKY; }
From source file:com.meiste.greg.ptw.WidgetProvider.java
@SuppressLint("NewApi") private void setAlarm(final Context context) { /* No point setting alarm if no widgets */ if (getInstalledWidgets(context).length == 0) return;/* ww w .j a v a 2 s . c o m*/ final long now = System.currentTimeMillis(); long next = UPDATE_INTERVAL - (now % UPDATE_INTERVAL) - UPDATE_FUDGE; if (next <= 0) { next += UPDATE_INTERVAL; } final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { am.setExact(AlarmManager.RTC, now + next, getAlarmIntent(context)); } else { am.set(AlarmManager.RTC, now + next, getAlarmIntent(context)); } }
From source file:com.nextgis.mobile.TrackerService.java
protected void ScheduleNextUpdate(Context context, String action, long nMinTimeBetweenSend, boolean bEnergyEconomy, boolean bStart) { if (context == null) return;/*from ww w .j a v a 2 s. com*/ Log.d(MainActivity.TAG, "Schedule Next Update for tracker " + bStart); if (bStart == false) return; Intent intent = new Intent(action); PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // The update frequency should often be user configurable. This is not. long currentTimeMillis = System.currentTimeMillis(); long nextUpdateTimeMillis = currentTimeMillis + nMinTimeBetweenSend; Time nextUpdateTime = new Time(); nextUpdateTime.set(nextUpdateTimeMillis); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); if (bEnergyEconomy) alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent); else alarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdateTimeMillis, pendingIntent); }
From source file:com.adithya321.sharesanalysis.activities.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sharedPreferences = getSharedPreferences("prefs", 0); if (sharedPreferences.getBoolean("first", true)) { startActivity(new Intent(this, IntroActivity.class)); return;/*from w w w .j ava 2s. c om*/ } setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); AccountHeader accountHeader = new AccountHeaderBuilder().withHeaderBackground(R.drawable.header) .withCompactStyle(true).withActivity(this) .addProfiles(new ProfileDrawerItem().withName(sharedPreferences.getString("name", "Name")) .withEmail("Target : " + sharedPreferences.getFloat("target", 20) + "%") .withIcon(getResources().getDrawable(R.mipmap.ic_launcher))) .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { @Override public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) { return false; } }).build(); final DatabaseHandler databaseHandler = new DatabaseHandler(getApplicationContext()); drawer = new DrawerBuilder().withActivity(this).withToolbar(toolbar).withAccountHeader(accountHeader) .withActionBarDrawerToggleAnimated(true) .addDrawerItems( new PrimaryDrawerItem().withIdentifier(0).withName("Dashboard") .withIcon(R.drawable.ic_timeline_gray), new PrimaryDrawerItem().withIdentifier(1).withName("Fund Flow") .withIcon(R.drawable.ic_compare_arrows_gray), new DividerDrawerItem(), new PrimaryDrawerItem().withIdentifier(2).withName("Share Purchase") .withIcon(R.drawable.ic_add_red) .withTextColor(getResources().getColor(R.color.red_500)), new PrimaryDrawerItem().withIdentifier(3).withName("Share Sales") .withIcon(R.drawable.ic_remove_green) .withTextColor(getResources().getColor(R.color.colorPrimary)), new PrimaryDrawerItem().withIdentifier(4).withName("Share Holdings") .withIcon(R.drawable.ic_account_balance_blue) .withTextColor(getResources().getColor(R.color.colorAccent)), new DividerDrawerItem(), new PrimaryDrawerItem().withIdentifier(5).withName("Charts") .withIcon(R.drawable.ic_insert_chart_gray), new PrimaryDrawerItem() .withIdentifier(6).withName("Summary").withIcon(R.drawable.ic_description_gray), new DividerDrawerItem(), new PrimaryDrawerItem().withIdentifier(7).withName("Feedback") .withIcon(R.drawable.ic_feedback_gray), new PrimaryDrawerItem() .withIdentifier(8).withName("Help").withIcon(R.drawable.ic_help_gray), new DividerDrawerItem(), new PrimaryDrawerItem().withIdentifier(10).withName("Backup") .withIcon(R.drawable.ic_backup_gray), new PrimaryDrawerItem() .withIdentifier(11).withName("Restore").withIcon(R.drawable.ic_restore_gray), new DividerDrawerItem(), new PrimaryDrawerItem().withIdentifier(21).withName("Settings") .withIcon(R.drawable.ic_settings_gray), new PrimaryDrawerItem().withIdentifier(22).withName("About") .withIcon(R.drawable.ic_info_gray)) .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { @Override public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { boolean flag; List<Share> shareList = databaseHandler.getShares(); if (drawerItem != null) { flag = true; switch ((int) drawerItem.getIdentifier()) { case 0: if (shareList.size() < 1) drawer.setSelection(2, true); else switchFragment("Dashboard", "Dashboard"); break; case 1: switchFragment("Fund Flow", "FundFlow"); break; case 2: switchFragment("Share Purchase", "SharePurchaseMain"); break; case 3: if (shareList.size() < 1) drawer.setSelection(2, true); else switchFragment("Share Sales", "SharePurchaseMain"); break; case 4: if (shareList.size() < 1) drawer.setSelection(2, true); else switchFragment("Share Holdings", "ShareHoldings"); break; case 5: if (shareList.size() < 1) drawer.setSelection(2, true); else switchFragment("Charts", "Charts"); break; case 6: if (shareList.size() < 1) drawer.setSelection(2, true); else switchFragment("Summary", "Summary"); break; case 7: ConversationActivity.show(MainActivity.this); break; case 8: startActivity(new Intent(MainActivity.this, IntroActivity.class)); break; case 10: RealmBackupRestore backup = new RealmBackupRestore(MainActivity.this); backup.backup(); break; case 11: RealmBackupRestore restore = new RealmBackupRestore(MainActivity.this); restore.restore(); Intent mStartActivity = new Intent(MainActivity.this, MainActivity.class); int mPendingIntentId = 123456; PendingIntent mPendingIntent = PendingIntent.getActivity(MainActivity.this, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager mgr = (AlarmManager) MainActivity.this .getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent); System.exit(0); break; case 21: startActivity(new Intent(MainActivity.this, ProfileActivity.class)); break; case 22: new LibsBuilder().withActivityStyle(Libs.ActivityStyle.LIGHT_DARK_TOOLBAR) .withActivityTitle(getString(R.string.app_name)).withAboutIconShown(true) .withAboutVersionShown(true).withVersionShown(true).withLicenseShown(true) .withLicenseDialog(true).withListener(libsListener) .start(MainActivity.this); break; default: switchFragment("Dashboard", "Dashboard"); break; } } else { flag = false; } return flag; } }).build(); if (savedInstanceState == null) drawer.setSelection(0, true); else drawer.setSelection(savedInstanceState.getLong("drawerSelection"), true); CustomActivityOnCrash.install(this); }
From source file:com.nextgis.mobile.services.TrackerService.java
protected void ScheduleNextUpdate(Context context, String action, long nMinTimeBetweenSend, boolean bEnergyEconomy, boolean bStart) { if (context == null) return;/*from w w w. ja v a 2s. c o m*/ Log.d(TAG, "Schedule Next Update for tracker " + bStart); if (bStart == false) return; Intent intent = new Intent(action); PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // The update frequency should often be user configurable. This is not. long currentTimeMillis = System.currentTimeMillis(); long nextUpdateTimeMillis = currentTimeMillis + nMinTimeBetweenSend; Time nextUpdateTime = new Time(); nextUpdateTime.set(nextUpdateTimeMillis); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); if (bEnergyEconomy) alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent); else alarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdateTimeMillis, pendingIntent); }
From source file:damo.three.ie.prepay.UpdateService.java
@Override protected void onHandleIntent(Intent intent) { Context context = getApplicationContext(); try {//from ww w.j a va 2 s. c om Log.d(Constants.TAG, "Fetching usages from service."); UsageFetcher usageFetcher = new UsageFetcher(context, true); JSONArray usages = usageFetcher.getUsages(); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences sharedUsagePref = context.getSharedPreferences("damo.three.ie.previous_usage", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedUsagePref.edit(); editor.putLong("last_refreshed_milliseconds", new DateTime().getMillis()); editor.putString("usage_info", usages.toString()); editor.commit(); // Register alarms for newly refreshed usages in background boolean notificationsEnabled = sharedPref.getBoolean("notification", true); List<UsageItem> usageItems = JSONUtils.jsonToUsageItems(usages); List<BasicUsageItem> basicUsageItems = UsageUtils.getAllBasicItems(usageItems); UsageUtils.registerInternetExpireAlarm(context, basicUsageItems, notificationsEnabled, true); } catch (Exception e) { // Try again at 7pm, unless its past 7pm. Then forget and let tomorrow's alarm do the updating. // Still trying to decide if I need a more robust retry mechanism. Log.d(Constants.TAG, "Caught exception: " + e.getLocalizedMessage()); Calendar calendar = Calendar.getInstance(); if (calendar.get(Calendar.HOUR_OF_DAY) < Constants.HOUR_TO_RETRY) { Log.d(Constants.TAG, "Scheduling a re-try for 7pm"); calendar.set(Calendar.HOUR_OF_DAY, Constants.HOUR_TO_RETRY); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); Intent receiver = new Intent(context, UpdateReceiver.class); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Using different request code to 0 so it won't conflict with other alarm below. PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 3, receiver, PendingIntent.FLAG_UPDATE_CURRENT); // Keeping efficiency in mind: // http://developer.android.com/reference/android/app/AlarmManager.html#ELAPSED_REALTIME am.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent); } } finally { Log.d(Constants.TAG, "Finish UpdateService"); UpdateReceiver.completeWakefulIntent(intent); } }
From source file:com.sean.takeastand.alarmprocess.UnscheduledRepeatingAlarm.java
@Override public void pause() { //Cancel previous PendingIntent pendingIntent = createPendingIntent(mContext); AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); am.cancel(pendingIntent);//from w ww .j a v a 2 s . com endAlarmService(); int totalPauseTime = Utils.getDefaultPauseAmount(mContext); long delayTimeInMillis = totalPauseTime * Constants.secondsInMinute * Constants.millisecondsInSecond; long triggerTime = SystemClock.elapsedRealtime() + delayTimeInMillis; PendingIntent pausePendingIntent = createPausePendingIntent(mContext); am.set(AlarmManager.ELAPSED_REALTIME, triggerTime, pausePendingIntent); Calendar pausedUntilTime = Calendar.getInstance(); pausedUntilTime.add(Calendar.MINUTE, Utils.getDefaultPauseAmount(mContext)); Utils.setPausedTime(pausedUntilTime, mContext); Utils.setImageStatus(mContext, Constants.NON_SCHEDULE_PAUSED); }
From source file:com.smarthome.deskclock.Alarms.java
/** * Sets alert in AlarmManger and StatusBar. This is what will * actually launch the alert when the alarm triggers. * * @param alarm Alarm./* w w w. j a v a 2 s . co m*/ * @param atTimeInMillis milliseconds since epoch */ private static void enableAlert(Context context, final Alarm alarm, final long atTimeInMillis) { AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); if (Log.LOGV) { Log.v("** setAlert id " + alarm.id + " atTime " + atTimeInMillis); } Intent intent = new Intent(ALARM_ALERT_ACTION); // XXX: This is a slight hack to avoid an exception in the remote // AlarmManagerService process. The AlarmManager adds extra data to // this Intent which causes it to inflate. Since the remote process // does not know about the Alarm class, it throws a // ClassNotFoundException. // // To avoid this, we marshall the data ourselves and then parcel a plain // byte[] array. The AlarmReceiver class knows to build the Alarm // object from the byte[] array. Parcel out = Parcel.obtain(); alarm.writeToParcel(out, 0); out.setDataPosition(0); intent.putExtra(ALARM_RAW_DATA, out.marshall()); PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); am.set(AlarmManager.RTC_WAKEUP, atTimeInMillis, sender); setStatusBarIcon(context, true); Calendar c = Calendar.getInstance(); c.setTimeInMillis(atTimeInMillis); String timeString = formatDayAndTime(context, c); saveNextAlarm(context, timeString); }
From source file:com.watabou.noosa.Game.java
public void doRestart() { Intent i = instance().getBaseContext().getPackageManager() .getLaunchIntentForPackage(getBaseContext().getPackageName()); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); int piId = 123456; PendingIntent pi = PendingIntent.getActivity(getBaseContext(), piId, i, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager mgr = (AlarmManager) getBaseContext().getSystemService(ContextWrapper.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pi); shutdown();/*from w w w . j av a 2s. c om*/ }