Example usage for android.app PendingIntent getService

List of usage examples for android.app PendingIntent getService

Introduction

In this page you can find the example usage for android.app PendingIntent getService.

Prototype

public static PendingIntent getService(Context context, int requestCode, @NonNull Intent intent,
        @Flags int flags) 

Source Link

Document

Retrieve a PendingIntent that will start a service, like calling Context#startService Context.startService() .

Usage

From source file:com.hplasplas.reminders.services.NotificationService.java

private PendingIntent createPendingIntent(int id) {

    Intent intent = new Intent(this.getApplicationContext(), NotificationService.class);
    intent.putExtra(CURRENT_NOTIFICATION_READ, true);
    if (id == ACTIVITY_PENDING_INTENT_ID) {
        intent.putExtra(NEED_ACTIVITY_START, true);
    }//from w w w  .  j a  v a2  s  .co  m
    return PendingIntent.getService(this.getApplicationContext(), id, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
}

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

@SuppressLint("CommitPrefEdits")
@TargetApi(android.os.Build.VERSION_CODES.KITKAT)
@Override//from   ww w  .  j a v a  2s  .  co  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.smedic.tubtub.BackgroundAudioService.java

/**
 * Generates specific action with parameters below
 *
 * @param icon/*from ww  w . j  a  v a  2s .  c o m*/
 * @param title
 * @param intentAction
 * @return
 */
private NotificationCompat.Action generateAction(int icon, String title, String intentAction) {
    Intent intent = new Intent(getApplicationContext(), BackgroundAudioService.class);
    intent.setAction(intentAction);
    PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
    return new NotificationCompat.Action.Builder(icon, title, pendingIntent).build();
}

From source file:com.metinkale.prayerapp.vakit.WidgetService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    WidgetProvider.updateWidgets(this);
    updateOngoing();/*from   w ww  .  ja v a  2s .co m*/

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    PendingIntent service = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    App.setExact(am, AlarmManager.RTC,
            DateTime.now().withMillisOfSecond(0).withSecondOfMinute(0).plusMinutes(1).getMillis(), service);

    stopSelf();
    return super.onStartCommand(intent, flags, startId);
}

From source file:no.firestorm.weathernotificatonservice.WeatherNotificationService.java

private void removeAlarm() {
    final PendingIntent pendingIntent = PendingIntent.getService(this, 0,
            new Intent(this, WeatherNotificationService.class), PendingIntent.FLAG_UPDATE_CURRENT);
    final AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarm.cancel(pendingIntent);//from www . j  a v  a2  s .  c  o m
}

From source file:com.unlp.tesis.steer.LocationService.java

/**
 * Gets a PendingIntent to send with the request to add or remove Geofences. Location Services
 * issues the Intent inside this PendingIntent whenever a geofence transition occurs for the
 * current list of geofences./*from   ww w. j av  a 2  s  .c o m*/
 *
 * @return A PendingIntent for the IntentService that handles geofence transitions.
 */
private PendingIntent getGeofencePendingIntent() {
    // Reuse the PendingIntent if we already have it.
    if (mGeofencePendingIntent != null) {
        return mGeofencePendingIntent;
    }
    Intent intent = new Intent(getApplicationContext(), GeofenceTransitionsIntentService.class);
    // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
    // addGeofences() and removeGeofences().
    return PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

From source file:com.granita.tasks.notification.NotificationActionUtils.java

/**
 * Creates a {@link PendingIntent} to be used for creating and canceling the undo timeout alarm.
 *//* ww  w.j  a v a 2  s  .  c o m*/
private static PendingIntent createUndoTimeoutPendingIntent(final Context context,
        final NotificationAction notificationAction) {
    final Intent intent = new Intent(ACTION_UNDO_TIMEOUT);
    intent.setPackage(context.getPackageName());
    putNotificationActionExtra(intent, notificationAction);
    final int requestCode = notificationAction.mNotificationId;
    final PendingIntent pendingIntent = PendingIntent.getService(context, requestCode, intent, 0);
    return pendingIntent;
}

From source file:com.darshancomputing.alockblock.ALockBlockService.java

private void minimize() {
    mNotificationManager.cancelAll();// w  w  w  . j av a 2 s .co m
    stopForeground(true);

    if (!settings.getBoolean(SettingsActivity.KEY_ALWAYS_SHOW_NOTIFICATION, false))
        return;

    Intent mainWindowIntent = new Intent(context, ALockBlockActivity.class);
    mainWindowPendingIntent = PendingIntent.getActivity(context, 0, mainWindowIntent, 0);

    ComponentName comp = new ComponentName(getPackageName(), ALockBlockService.class.getName());
    Intent disableIntent = new Intent().setComponent(comp).putExtra(EXTRA_ACTION, ACTION_DISABLE);
    PendingIntent disablePendingIntent = PendingIntent.getService(this, 0, disableIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder kgunb = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.kg_unlocked)
            .setLargeIcon(largeIconL).setContentTitle("Lock Screen Enabled").setContentText("A Lock Block")
            .setContentIntent(mainWindowPendingIntent).setShowWhen(false).setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_MIN);

    if (settings.getBoolean(SettingsActivity.KEY_REENABLE_FROM_NOTIFICATION, false))
        kgunb.addAction(R.drawable.ic_menu_login, "Disable", disablePendingIntent);

    mNotificationManager.notify(NOTIFICATION_KG_UNLOCKED, kgunb.build());
}

From source file:no.firestorm.weathernotificatonservice.WeatherNotificationService.java

/**
 * Set alarm//www  . j a v  a 2 s  .  c om
 * 
 * @param updateRate
 *            in minutes
 */
private void setAlarm(long updateRate) {
    // Set alarm
    final PendingIntent pendingIntent = PendingIntent.getService(this, 0,
            new Intent(this, WeatherNotificationService.class), PendingIntent.FLAG_UPDATE_CURRENT);
    final AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    // Set time to next hour plus 5 minutes:
    final long now = System.currentTimeMillis();
    long triggerAtTime = now;
    // set back to last hour plus 2 minutes:
    triggerAtTime -= triggerAtTime % 3600000 - 12000;
    // Add selected update rate
    triggerAtTime += updateRate * 60000;

    // Check that trigger time is not passed.
    if (triggerAtTime < now)
        triggerAtTime = now + updateRate * 60000;

    alarm.set(AlarmManager.RTC, triggerAtTime, pendingIntent);
}

From source file:com.androidinspain.deskclock.alarms.AlarmNotifications.java

static synchronized void showSnoozeNotification(Context context, AlarmInstance instance) {
    LogUtils.v("Displaying snoozed notification for alarm instance: " + instance.mId);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setShowWhen(false)
            .setContentTitle(instance.getLabelOrDefault(context))
            .setContentText(context.getString(com.androidinspain.deskclock.R.string.alarm_alert_snooze_until,
                    AlarmUtils.getFormattedTime(context, instance.getAlarmTime())))
            .setColor(ContextCompat.getColor(context, com.androidinspain.deskclock.R.color.default_background))
            .setSmallIcon(com.androidinspain.deskclock.R.drawable.stat_notify_alarm).setAutoCancel(false)
            .setSortKey(createSortKey(instance)).setPriority(NotificationCompat.PRIORITY_MAX)
            .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setLocalOnly(true);/*from   www  . j a  v a 2 s  . co  m*/

    if (Utils.isNOrLater()) {
        builder.setGroup(UPCOMING_GROUP_KEY);
    }

    // Setup up dismiss action
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(context,
            AlarmStateManager.ALARM_DISMISS_TAG, instance, AlarmInstance.DISMISSED_STATE);
    final int id = instance.hashCode();
    builder.addAction(com.androidinspain.deskclock.R.drawable.ic_alarm_off_24dp,
            context.getString(com.androidinspain.deskclock.R.string.alarm_alert_dismiss_text),
            PendingIntent.getService(context, id, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup content action if instance is owned by alarm
    Intent viewAlarmIntent = createViewAlarmIntent(context, instance);
    builder.setContentIntent(
            PendingIntent.getActivity(context, id, viewAlarmIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    final Notification notification = builder.build();
    nm.notify(id, notification);
    updateUpcomingAlarmGroupNotification(context, -1, notification);
}