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:com.jerrellmardis.amphitheatre.util.Utils.java

public static void scheduleRecommendations(Context context) {
    Log.d("amp:Utils",
            "Checking if alarm is already set: " + isAlarmAlreadySet(context, RecommendationsService.class));
    //And now//from  w ww. j  av  a 2  s .  c  o m
    Log.d("amp:Utils", "Start rechecking the recommendations");
    Intent intent = new Intent(context, RecommendationsService.class);
    intent.putExtra("ALARM", true);
    /*context.startService(intent);*/
    if (isAlarmAlreadySet(context, RecommendationsService.class))
        return;

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    //Intent intent = ...
    PendingIntent alarmIntent = PendingIntent.getService(context, LIBRARY_UPDATE_REQUEST_CODE, intent, 0);

    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 5000,
            AlarmManager.INTERVAL_HALF_HOUR, //Every half hour seems sufficient
            alarmIntent);

}

From source file:com.battlelancer.seriesguide.service.NotificationService.java

@SuppressLint("CommitPrefEdits")
@TargetApi(android.os.Build.VERSION_CODES.KITKAT)
@Override/* w  w w .j a  va 2 s . 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:alaindc.crowdroid.SensorsIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        final String action = intent.getAction();
        if (action.equals(Constants.INTENT_START_SENSORS)) {

            // Init throughput taken
            SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(Constants.PREF_FILE,
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putBoolean(Constants.THROUGHPUT_TAKEN, false);
            editor.commit();/*from ww  w. ja  v a  2  s.c  o m*/

            // Configure sensors and eventlistener
            mSensorManager = (SensorManager) getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
            List<Sensor> sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
            for (Sensor sensor : sensorList) {
                if (Constants.isInMonitoredSensors(sensor.getType()))
                    mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
            }

            // TODO STUB: Comment this in release
            for (int type : Constants.STUBBED_MONITORED_SENSORS) {
                stub_onSensorChanged(type);
            }

        }

        if (action.equals(Constants.INTENT_START_AUDIOAMPLITUDE_SENSE)) {
            // Configure amplitude and start TEST
            amplitudeTask = new GetAmplitudeTask(this);
            amplitudeTask.getData();
        }

        if (action.equals(Constants.INTENT_STUB_SENSOR_CHANGED + Sensor.TYPE_AMBIENT_TEMPERATURE)) {
            stub_onSensorChanged(intent.getIntExtra(Constants.INTENT_STUB_SENSOR_CHANGED_TYPE, -1));
        }

        if (action.equals(Constants.INTENT_STUB_SENSOR_CHANGED + Sensor.TYPE_PRESSURE)) {
            stub_onSensorChanged(intent.getIntExtra(Constants.INTENT_STUB_SENSOR_CHANGED_TYPE, -1));
        }

        if (action.equals(Constants.INTENT_STUB_SENSOR_CHANGED + Sensor.TYPE_RELATIVE_HUMIDITY)) {
            stub_onSensorChanged(intent.getIntExtra(Constants.INTENT_STUB_SENSOR_CHANGED_TYPE, -1));
        }

        if (action.equals(Constants.INTENT_RECEIVED_AMPLITUDE)) {
            double amplitude = intent.getDoubleExtra(Constants.EXTRA_AMPLITUDE, -1);

            if (amplitude > 0) {
                SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(Constants.PREF_FILE,
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString(Constants.PREF_SENSOR_ + Constants.TYPE_AMPLITUDE, Double.toString(amplitude));
                editor.commit();

                // Update view
                Intent senseintent = new Intent(Constants.INTENT_UPDATE_SENSORS);
                senseintent.putExtra(Constants.INTENT_RECEIVED_DATA_EXTRA_DATA,
                        "Sensor " + Constants.getNameOfSensor(Constants.TYPE_AMPLITUDE) + " value: "
                                + Double.toString(amplitude));
                LocalBroadcastManager.getInstance(this).sendBroadcast(senseintent);
            }

            int index = Constants.getIndexAlarmForSensor(Constants.TYPE_AMPLITUDE);

            // Set the alarms for next sensing of amplitude
            alarmMgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
            Intent intentAlarm = new Intent(getApplicationContext(), SensorsIntentService.class);
            intentAlarm.setAction(Constants.INTENT_START_AUDIOAMPLITUDE_SENSE);
            alarmIntent = PendingIntent.getService(getApplicationContext(), 0, intentAlarm, 0);

            // TIMEOUT for another monitoring of audio
            int seconds = 30; // TODO: De-hardcode this
            alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + seconds * 1000,
                    alarmIntent);

        }
    }
}

From source file:com.sean.takeastand.alarmprocess.UnscheduledRepeatingAlarm.java

@Override
public void unpause() {
    PendingIntent pendingIntent = createPausePendingIntent(mContext);
    AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    am.cancel(pendingIntent);//from ww w. j a  v a  2 s.  c  o  m
    setRepeatingAlarm();
    Utils.setImageStatus(mContext, Constants.NON_SCHEDULE_ALARM_RUNNING);
}

From source file:com.jmstudios.redmoon.receiver.AutomaticFilterChangeReceiver.java

public static void scheduleNextAlarm(Context context, String time, Intent operation) {
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time.split(":")[0]));
    calendar.set(Calendar.MINUTE, Integer.parseInt(time.split(":")[1]));

    GregorianCalendar now = new GregorianCalendar();
    now.add(Calendar.SECOND, 1);//from   ww  w . jav  a  2s. c  om
    if (calendar.before(now)) {
        calendar.add(Calendar.DATE, 1);
    }

    if (DEBUG)
        Log.i(TAG, "Scheduling alarm for " + calendar.toString());

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

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, operation, 0);

    if (android.os.Build.VERSION.SDK_INT >= 19) {
        alarmManager.setExact(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
    } else {
        alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
    }
}

From source file:com.sean.takeastand.alarmprocess.ScheduledRepeatingAlarm.java

@Override
public void cancelAlarm() {
    PendingIntent pendingIntent = createPendingIntent(mContext, mCurrentAlarmSchedule);
    AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    am.cancel(pendingIntent);/*w  w w .j  a va 2  s  .  c o m*/
    endAlarmService();
    Utils.setImageStatus(mContext, Constants.NO_ALARM_RUNNING);
    Utils.setRunningScheduledAlarm(mContext, -1);
}

From source file:com.tortel.deploytrack.service.NotificationService.java

@SuppressLint("NewApi")
private void showNotification() {
    // If there isnt an ID saved, shut down the service
    if (deploymentId == -1) {
        stopSelf();//from  w ww . j  a  v a  2 s .  c o m
        return;
    }
    if (DEBUG) {
        Toast.makeText(this, "NotificationService loading notification", Toast.LENGTH_SHORT).show();
    }

    // Load the Deployment object
    Deployment deployment = DatabaseManager.getInstance(this).getDeployment(deploymentId);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    RemoteViews view = new RemoteViews(getPackageName(), R.layout.notification);
    view.setImageViewBitmap(R.id.notification_pie, WidgetProvider.getChartBitmap(deployment, SIZE));
    view.setTextViewText(R.id.notification_title, deployment.getName());

    view.setTextViewText(R.id.notification_main, getResources().getString(R.string.small_notification,
            deployment.getPercentage(), deployment.getCompleted(), deployment.getLength()));

    if (prefs.getBoolean(Prefs.KEY_HIDE_DATE, false)) {
        view.setViewVisibility(R.id.notification_daterange, View.GONE);
    } else {
        view.setTextViewText(R.id.notification_daterange, getResources().getString(R.string.date_range,
                deployment.getFormattedStart(), deployment.getFormattedEnd()));
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle(deployment.getName());
    builder.setContentText(getResources().getString(R.string.small_notification, deployment.getPercentage(),
            deployment.getCompleted(), deployment.getLength()));
    builder.setOngoing(true);

    // Hide the time, its persistent
    builder.setWhen(0);

    builder.setSmallIcon(R.drawable.ic_notification);
    builder.setPriority(Integer.MAX_VALUE);

    Notification notification = builder.build();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        notification.bigContentView = view;
    }

    notificationManager.notify(NOTIFICATION_ID, notification);

    //Schedule an update at midnight
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    DateTime now = new DateTime();
    DateTime tomorrow = new DateTime(now.plusDays(1)).withTimeAtStartOfDay();

    PendingIntent pending = PendingIntent.getBroadcast(getBaseContext(), 0, new Intent(UPDATE_INTENT),
            PendingIntent.FLAG_UPDATE_CURRENT);

    //Adding 100msec to make sure its triggered after midnight
    Log.d("Scheduling notification update for " + tomorrow.getMillis() + 100);

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
        alarmManager.setExact(AlarmManager.RTC, tomorrow.getMillis() + 100, pending);
    } else {
        alarmManager.set(AlarmManager.RTC, tomorrow.getMillis() + 100, pending);
    }
}

From source file:com.appsaur.tarucassist.AutomuteAlarmReceiver.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, AutomuteAlarmReceiver.class),
            0);/*  w  w  w . java  2s  .  c om*/
    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);
}

From source file:gpsalarm.app.service.PostMonitor.java

@Override
public void onCreate() {
    super.onCreate();
    sdb = new TimelineHelper(this);
    rdb = new ReminderHelper(this);

    //get user account from preference.
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    team = prefs.getString("team", "").toUpperCase();
    myAccount = new Account(prefs.getString("user", null), prefs.getString("password", ""), null);

    registerReceiver(onBatteryChanged, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(this, OnAlarmReceiver.class);
    pi = PendingIntent.getBroadcast(this, 0, i, 0);
    setAlarm(INITIAL_POLL_PERIOD);/*from   ww  w .j av a  2  s.c o  m*/
}

From source file:com.snda.mymarket.providers.downloads.DownloadService.java

/**
 * Initializes the service when it is first created
 *//*from w ww.  j  ava 2s. c o m*/
public void onCreate() {
    super.onCreate();
    if (Constants.LOGVV) {
        Log.v(Constants.TAG, "Service onCreate");
    }

    if (mSystemFacade == null) {
        mSystemFacade = new RealSystemFacade(this);
    }

    mObserver = new DownloadManagerContentObserver();
    getContentResolver().registerContentObserver(Downloads.ALL_DOWNLOADS_CONTENT_URI, true, mObserver);

    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    mNotifier = new DownloadNotifier(this);
    mNotifier.cancelAll();

    mScanner = new DownloadScanner(this);

    mUpdateThread = new HandlerThread(Constants.TAG + "-UpdateThread");
    mUpdateThread.start();
    mUpdateHandler = new Handler(mUpdateThread.getLooper(), mUpdateCallback);

    updateFromProvider();
}