Example usage for android.content Context ALARM_SERVICE

List of usage examples for android.content Context ALARM_SERVICE

Introduction

In this page you can find the example usage for android.content Context ALARM_SERVICE.

Prototype

String ALARM_SERVICE

To view the source code for android.content Context ALARM_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.app.AlarmManager for receiving intents at a time of your choosing.

Usage

From source file:info.papdt.blacklight.support.Utility.java

public static void startServiceAlarm(Context context, Class<?> service, long interval) {
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, service);
    PendingIntent p = PendingIntent.getService(context, REQUEST_CODE, i, PendingIntent.FLAG_CANCEL_CURRENT);
    am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 0, interval, p);
}

From source file:app.jorge.mobile.com.transportalert.ScrollingActivity.java

public void scheduleAlarm() {
    // Construct an intent that will execute the AlarmReceiver
    Intent intent = new Intent(getApplicationContext(), MyAlarmReceiver.class);
    // Create a PendingIntent to be triggered when the alarm goes off
    final PendingIntent pIntent = PendingIntent.getBroadcast(this, MyAlarmReceiver.REQUEST_CODE, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    // Setup periodic alarm every 5 seconds
    long firstMillis = System.currentTimeMillis(); // alarm is set right away
    AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
    // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY

    //alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
    //      AlarmManager.INTERVAL_HALF_HOUR, pIntent);

    alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, AlarmManager.INTERVAL_HALF_HOUR, pIntent);
}

From source file:org.jamienicol.episodes.AutoRefreshHelper.java

public void rescheduleAlarm() {
    NetworkStateReceiver.disable(context);

    final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    final Intent intent = new Intent(context, AutoRefreshHelper.Service.class);
    final PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

    if (getAutoRefreshEnabled() && getAutoRefreshPeriod() != 0) {
        final long alarmTime = getPrevAutoRefreshTime() + getAutoRefreshPeriod();

        Log.i(TAG, String.format("Scheduling auto refresh alarm for %d.", alarmTime));

        alarmManager.set(AlarmManager.RTC, alarmTime, pendingIntent);
    } else {//from   w w w.j  ava 2  s .  c om
        Log.i(TAG, "Cancelling auto refresh alarm.");

        alarmManager.cancel(pendingIntent);
    }
}

From source file:com.appsaur.tarucassist.AlarmReceiver.java

public void setRepeatAlarm(Context context, Calendar calendar, int ID, long RepeatTime) {
    mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    // Put Reminder ID in Intent Extra
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(BaseActivity.EXTRA_REMINDER_ID, Integer.toString(ID));
    mPendingIntent = PendingIntent.getBroadcast(context, ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    // Calculate notification timein
    Calendar c = Calendar.getInstance();
    long currentTime = c.getTimeInMillis();
    long diffTime = calendar.getTimeInMillis() - currentTime;

    // Start alarm using initial notification time and repeat interval time
    mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + diffTime,
            RepeatTime, mPendingIntent);

    // Restart alarm if device is rebooted
    ComponentName receiver = new ComponentName(context, BootReceiver.class);
    PackageManager pm = context.getPackageManager();
    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
}

From source file:org.traccar.client.MainFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (BuildConfig.HIDDEN_APP) {
        removeLauncherIcon();/*from   w  ww .  j  a v a 2 s  . c om*/
    }

    setHasOptionsMenu(true);

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    addPreferencesFromResource(R.xml.preferences);
    initPreferences();

    findPreference(KEY_DEVICE).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            return newValue != null && !newValue.equals("");
        }
    });
    findPreference(KEY_URL).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            return (newValue != null) && validateServerURL(newValue.toString());
        }
    });

    findPreference(KEY_INTERVAL).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (newValue != null) {
                try {
                    int value = Integer.parseInt((String) newValue);
                    return value > 0;
                } catch (NumberFormatException e) {
                    Log.w(TAG, e);
                }
            }
            return false;
        }
    });

    Preference.OnPreferenceChangeListener numberValidationListener = new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (newValue != null) {
                try {
                    int value = Integer.parseInt((String) newValue);
                    return value >= 0;
                } catch (NumberFormatException e) {
                    Log.w(TAG, e);
                }
            }
            return false;
        }
    };
    findPreference(KEY_DISTANCE).setOnPreferenceChangeListener(numberValidationListener);
    findPreference(KEY_ANGLE).setOnPreferenceChangeListener(numberValidationListener);

    alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
    alarmIntent = PendingIntent.getBroadcast(getActivity(), 0,
            new Intent(getActivity(), AutostartReceiver.class), 0);

    if (sharedPreferences.getBoolean(KEY_STATUS, false)) {
        startTrackingService(true, false);
    }
}

From source file:com.ayuget.redface.job.PrivateMessagesService.java

@TargetApi(android.os.Build.VERSION_CODES.KITKAT)
@Override/*  w  w w .  j  a v a2  s .  c  o  m*/
protected void onHandleIntent(Intent intent) {
    Log.d(LOG_TAG, "Handling intent");

    if (!settings.arePrivateMessagesNoticationsEnabled()) {
        return;
    }

    final NotificationManagerCompat notificationManager = NotificationManagerCompat
            .from(getApplicationContext());

    for (User redfaceUser : userManager.getRealUsers()) {
        subscriptions.add(mdService.getNewPrivateMessages(redfaceUser)
                .subscribe(new EndlessObserver<List<PrivateMessage>>() {
                    @Override
                    public void onNext(List<PrivateMessage> privateMessages) {
                        for (PrivateMessage privateMessage : privateMessages) {
                            // Prepare intent to deal with clicks
                            Intent resultIntent = new Intent(PrivateMessagesService.this,
                                    PrivateMessagesActivity.class);
                            resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            resultIntent.putExtra(UIConstants.ARG_SELECTED_PM, privateMessage);
                            PendingIntent resultPendingIntent = PendingIntent.getActivity(
                                    getApplicationContext(), 0, resultIntent,
                                    PendingIntent.FLAG_UPDATE_CURRENT);

                            NotificationCompat.Builder builder = new NotificationCompat.Builder(
                                    getApplicationContext()).setSmallIcon(R.drawable.ic_action_emo_wonder)
                                            .setColor(getResources().getColor(R.color.theme_primary))
                                            .setContentTitle(privateMessage.getRecipient())
                                            .setContentText(privateMessage.getSubject())
                                            .setContentIntent(resultPendingIntent).setAutoCancel(true);

                            builder.setVibrate(VIBRATION_PATTERN);

                            notificationManager.notify((int) privateMessage.getId(), builder.build());
                        }
                    }
                }));
    }

    // Setup next alarm
    long wakeUpTime = System.currentTimeMillis()
            + settings.getPrivateMessagesPollingFrequency() * DateUtils.MINUTE_IN_MILLIS;
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(this, PrivateMessagesService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    Log.d(LOG_TAG, "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:org.kaoriha.phonegap.plugins.releasenotification.Notifier.java

public void stop() {
    AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(ctx, Receiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    am.cancel(pi);//  www.j  ava2s.  c om
}

From source file:com.google.android.apps.muzei.sync.TaskQueueService.java

private void scheduleRetryArtworkDownload() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(new JobInfo.Builder(LOAD_ARTWORK_JOB_ID,
                new ComponentName(this, DownloadArtworkJobService.class))
                        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).build());
    } else {//  w  w  w . ja v  a  2  s.  c  o  m
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        int reloadAttempt = sp.getInt(PREF_ARTWORK_DOWNLOAD_ATTEMPT, 0);
        sp.edit().putInt(PREF_ARTWORK_DOWNLOAD_ATTEMPT, reloadAttempt + 1).commit();
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        long retryTimeMillis = SystemClock.elapsedRealtime() + (1 << reloadAttempt) * 2000;
        am.set(AlarmManager.ELAPSED_REALTIME, retryTimeMillis,
                TaskQueueService.getArtworkDownloadRetryPendingIntent(this));
    }
}

From source file:com.lloydtorres.stately.push.TrixHelper.java

/**
 * Sets an alarm for Alphys to query NS for new notices. The alarm time is on whatever the user
 * selected in settings, starting from the time the function was called. A "jitter" of up to
 * 5 minutes is added on top to prevent overwhelming the NS servers.
 * @param c App context/*w  w  w .  j  av a2 s  .  c  o  m*/
 */
public static void setAlarmForAlphys(Context c) {
    // First check if alarms should be set to begin with.
    if (!SettingsActivity.getNotificationSetting(c)) {
        return;
    }

    Intent alphysIntent = new Intent(c, AlphysReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(c, 0, alphysIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    long timeToNextAlarm = System.currentTimeMillis()
            + SettingsActivity.getNotificationIntervalSetting(c) * 1000L;
    // add "jitter" from 0 min to 5 min to next alarm to prevent overwhelming NS servers
    Random r = new Random();
    timeToNextAlarm += (long) (r.nextDouble() * FIVE_MIN_IN_MS);

    // Source:
    // https://www.reddit.com/r/Android/comments/44opi3/reddit_sync_temporarily_blocked_for_bad_api_usage/czs3ne4
    AlarmManager am = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeToNextAlarm, pendingIntent);
    } else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        am.setExact(AlarmManager.RTC_WAKEUP, timeToNextAlarm, pendingIntent);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, timeToNextAlarm, pendingIntent);
    }
}

From source file:cn.studyjams.s2.sj0119.NForget.AlarmReceiver.java

public void cancelAlarm(Context context, int ID) {
    mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    // Cancel Alarm using Reminder ID
    mPendingIntent = PendingIntent.getBroadcast(context, ID, new Intent(context, AlarmReceiver.class), 0);
    mAlarmManager.cancel(mPendingIntent);

    // Disable alarm
    ComponentName receiver = new ComponentName(context, BootReceiver.class);
    PackageManager pm = context.getPackageManager();
    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);
}