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.lambdasoup.quickfit.alarm.AlarmService.java

@WorkerThread
private void refreshNotificationDisplay() {
    try (Cursor toNotify = getContentResolver().query(QuickFitContentProvider.getUriWorkoutsList(),
            new String[] { WorkoutEntry.SCHEDULE_ID, WorkoutEntry.WORKOUT_ID, WorkoutEntry.ACTIVITY_TYPE,
                    WorkoutEntry.LABEL, WorkoutEntry.DURATION_MINUTES },
            ScheduleEntry.TABLE_NAME + "." + ScheduleEntry.COL_SHOW_NOTIFICATION + "=?",
            new String[] { Integer.toString(ScheduleEntry.SHOW_NOTIFICATION_YES) }, null)) {
        int count = toNotify == null ? 0 : toNotify.getCount();
        if (count == 0) {
            Timber.d("refreshNotificationDisplay: no events");
            NotificationManager notificationManager = (NotificationManager) getSystemService(
                    NOTIFICATION_SERVICE);
            notificationManager.cancel(Constants.NOTIFICATION_ALARM);
            return;
        }/*from www.j  ava  2s.com*/

        long[] scheduleIds = new long[count];
        int i = 0;
        toNotify.moveToPosition(-1);
        while (toNotify.moveToNext()) {
            scheduleIds[i] = toNotify.getLong(toNotify.getColumnIndex(WorkoutEntry.SCHEDULE_ID));
            i++;
        }

        PendingIntent cancelIntent = PendingIntent.getService(getApplicationContext(), 0,
                getIntentOnNotificationsCanceled(this, scheduleIds), PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder notification;
        if (count == 1) {
            Timber.d("refreshNotificationDisplay: single event");
            toNotify.moveToFirst();
            notification = notifySingleEvent(toNotify, cancelIntent);
        } else {
            Timber.d("refreshNotificationDisplay: multiple events");
            toNotify.moveToPosition(-1);
            notification = notifyMultipleEvents(toNotify, cancelIntent);
        }

        notification.setDeleteIntent(cancelIntent);
        notification.setAutoCancel(true);
        notification.setPriority(Notification.PRIORITY_HIGH);
        notification.setSmallIcon(R.drawable.ic_stat_quickfit_icon);
        notification.setColor(ContextCompat.getColor(this, R.color.colorPrimary));

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String ringtoneUriStr = preferences.getString(getString(R.string.pref_key_notification_ringtone), null);
        if (ringtoneUriStr == null) {
            notification.setSound(
                    RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION));
        } else if (!ringtoneUriStr.isEmpty()) {
            notification.setSound(Uri.parse(ringtoneUriStr));
        }
        boolean ledOn = preferences.getBoolean(getString(R.string.pref_key_notification_led), true);
        boolean vibrationOn = preferences.getBoolean(getString(R.string.pref_key_notification_vibrate), true);
        notification.setDefaults(
                (ledOn ? Notification.DEFAULT_LIGHTS : 0) | (vibrationOn ? Notification.DEFAULT_VIBRATE : 0));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            notification.setCategory(Notification.CATEGORY_ALARM);
        }

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(Constants.NOTIFICATION_ALARM, notification.build());
    }
}

From source file:com.google.samples.apps.iosched.service.SessionAlarmService.java

/**
 *  A starred session is about to end. Notify the user to provide session feedback.
 *  Constructs and triggers a system notification. Does nothing if the session has already
 *  concluded./*from w ww  .j  ava2 s.co  m*/
 */
private void notifySessionFeedback(boolean debug) {
    LOGD(TAG, "Considering firing notification for session feedback.");

    if (debug) {
        LOGW(TAG, "Note: this is a debug notification.");
    }

    // Don't fire notification if this feature is disabled in settings
    if (!SettingsUtils.shouldShowSessionFeedbackReminders(this)) {
        LOGD(TAG, "Skipping session feedback notification. Disabled in settings.");
        return;
    }

    Cursor c = null;
    try {
        c = getContentResolver().query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI,
                SessionsNeedingFeedbackQuery.PROJECTION, SessionsNeedingFeedbackQuery.WHERE_CLAUSE, null, null);
        if (c == null) {
            return;
        }

        FeedbackHelper feedbackHelper = new FeedbackHelper(this);

        List<String> needFeedbackIds = new ArrayList<String>();
        List<String> needFeedbackTitles = new ArrayList<String>();
        while (c.moveToNext()) {
            String sessionId = c.getString(SessionsNeedingFeedbackQuery.SESSION_ID);
            String sessionTitle = c.getString(SessionsNeedingFeedbackQuery.SESSION_TITLE);

            // Avoid repeated notifications.
            if (feedbackHelper.isFeedbackNotificationFiredForSession(sessionId)) {
                LOGD(TAG, "Skipping repeated session feedback notification for session '" + sessionTitle + "'");
                continue;
            }

            needFeedbackIds.add(sessionId);
            needFeedbackTitles.add(sessionTitle);
        }

        if (needFeedbackIds.size() == 0) {
            // the user has already been notified of all sessions needing feedback
            return;
        }

        LOGD(TAG, "Going forward with session feedback notification for " + needFeedbackIds.size()
                + " session(s).");

        final Resources res = getResources();

        // this is used to synchronize deletion of notifications on phone and wear
        Intent dismissalIntent = new Intent(ACTION_NOTIFICATION_DISMISSAL);
        // TODO: fix Wear dismiss integration
        //dismissalIntent.putExtra(KEY_SESSION_ID, sessionId);
        PendingIntent dismissalPendingIntent = PendingIntent.getService(this, (int) new Date().getTime(),
                dismissalIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        String provideFeedbackTicker = res.getString(R.string.session_feedback_notification_ticker);
        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
                .setColor(getResources().getColor(R.color.theme_primary)).setContentText(provideFeedbackTicker)
                .setTicker(provideFeedbackTicker)
                .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR,
                        SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS)
                .setSmallIcon(R.drawable.ic_stat_notification).setPriority(Notification.PRIORITY_LOW)
                .setLocalOnly(true) // make it local to the phone
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                .setDeleteIntent(dismissalPendingIntent).setAutoCancel(true);

        if (needFeedbackIds.size() == 1) {
            // Only 1 session needs feedback
            Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(needFeedbackIds.get(0));
            PendingIntent pi = TaskStackBuilder.create(this)
                    .addNextIntent(new Intent(this, MyScheduleActivity.class))
                    .addNextIntent(
                            new Intent(Intent.ACTION_VIEW, sessionUri, this, SessionFeedbackActivity.class))
                    .getPendingIntent(1, PendingIntent.FLAG_CANCEL_CURRENT);

            notifBuilder.setContentTitle(needFeedbackTitles.get(0)).setContentIntent(pi);
        } else {
            // Show information about several sessions that need feedback
            PendingIntent pi = TaskStackBuilder.create(this)
                    .addNextIntent(new Intent(this, MyScheduleActivity.class))
                    .getPendingIntent(1, PendingIntent.FLAG_CANCEL_CURRENT);

            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            inboxStyle.setBigContentTitle(provideFeedbackTicker);
            for (String title : needFeedbackTitles) {
                inboxStyle.addLine(title);
            }

            notifBuilder
                    .setContentTitle(getResources().getQuantityString(R.plurals.session_plurals,
                            needFeedbackIds.size(), needFeedbackIds.size()))
                    .setStyle(inboxStyle).setContentIntent(pi);
        }

        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        LOGD(TAG, "Now showing session feedback notification!");
        nm.notify(FEEDBACK_NOTIFICATION_ID, notifBuilder.build());

        for (int i = 0; i < needFeedbackIds.size(); i++) {
            setupNotificationOnWear(needFeedbackIds.get(i), null, needFeedbackTitles.get(i), null);
            feedbackHelper.setFeedbackNotificationAsFiredForSession(needFeedbackIds.get(i));
        }
    } finally {
        if (c != null) {
            try {
                c.close();
            } catch (Exception ignored) {
            }
        }
    }
}

From source file:com.razza.apps.iosched.service.SessionAlarmService.java

/**
 *  A starred session is about to end. Notify the user to provide session feedback.
 *  Constructs and triggers a system notification. Does nothing if the session has already
 *  concluded./*from w  w  w.  ja  v  a2 s  .c om*/
 */
private void notifySessionFeedback(boolean debug) {
    LogUtils.LOGD(TAG, "Considering firing notification for session feedback.");

    if (debug) {
        LogUtils.LOGW(TAG, "Note: this is a debug notification.");
    }

    // Don't fire notification if this feature is disabled in settings
    if (!SettingsUtils.shouldShowSessionFeedbackReminders(this)) {
        LogUtils.LOGD(TAG, "Skipping session feedback notification. Disabled in settings.");
        return;
    }

    Cursor c = null;
    try {
        c = getContentResolver().query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI,
                SessionsNeedingFeedbackQuery.PROJECTION, SessionsNeedingFeedbackQuery.WHERE_CLAUSE, null, null);
        if (c == null) {
            return;
        }

        FeedbackHelper feedbackHelper = new FeedbackHelper(this);

        List<String> needFeedbackIds = new ArrayList<String>();
        List<String> needFeedbackTitles = new ArrayList<String>();
        while (c.moveToNext()) {
            String sessionId = c.getString(SessionsNeedingFeedbackQuery.SESSION_ID);
            String sessionTitle = c.getString(SessionsNeedingFeedbackQuery.SESSION_TITLE);

            // Avoid repeated notifications.
            if (feedbackHelper.isFeedbackNotificationFiredForSession(sessionId)) {
                LogUtils.LOGD(TAG,
                        "Skipping repeated session feedback notification for session '" + sessionTitle + "'");
                continue;
            }

            needFeedbackIds.add(sessionId);
            needFeedbackTitles.add(sessionTitle);
        }

        if (needFeedbackIds.size() == 0) {
            // the user has already been notified of all sessions needing feedback
            return;
        }

        LogUtils.LOGD(TAG, "Going forward with session feedback notification for " + needFeedbackIds.size()
                + " session(s).");

        final Resources res = getResources();

        // this is used to synchronize deletion of notifications on phone and wear
        Intent dismissalIntent = new Intent(ACTION_NOTIFICATION_DISMISSAL);
        // TODO: fix Wear dismiss integration
        //dismissalIntent.putExtra(KEY_SESSION_ID, sessionId);
        PendingIntent dismissalPendingIntent = PendingIntent.getService(this, (int) new Date().getTime(),
                dismissalIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        String provideFeedbackTicker = res.getString(R.string.session_feedback_notification_ticker);
        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
                .setColor(getResources().getColor(R.color.theme_primary)).setContentText(provideFeedbackTicker)
                .setTicker(provideFeedbackTicker)
                .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR,
                        SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS)
                .setSmallIcon(R.drawable.ic_stat_notification).setPriority(Notification.PRIORITY_LOW)
                .setLocalOnly(true) // make it local to the phone
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                .setDeleteIntent(dismissalPendingIntent).setAutoCancel(true);

        if (needFeedbackIds.size() == 1) {
            // Only 1 session needs feedback
            Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(needFeedbackIds.get(0));
            PendingIntent pi = TaskStackBuilder.create(this)
                    .addNextIntent(new Intent(this, MyScheduleActivity.class))
                    .addNextIntent(
                            new Intent(Intent.ACTION_VIEW, sessionUri, this, SessionFeedbackActivity.class))
                    .getPendingIntent(1, PendingIntent.FLAG_CANCEL_CURRENT);

            notifBuilder.setContentTitle(needFeedbackTitles.get(0)).setContentIntent(pi);
        } else {
            // Show information about several sessions that need feedback
            PendingIntent pi = TaskStackBuilder.create(this)
                    .addNextIntent(new Intent(this, MyScheduleActivity.class))
                    .getPendingIntent(1, PendingIntent.FLAG_CANCEL_CURRENT);

            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            inboxStyle.setBigContentTitle(provideFeedbackTicker);
            for (String title : needFeedbackTitles) {
                inboxStyle.addLine(title);
            }

            notifBuilder
                    .setContentTitle(getResources().getQuantityString(R.plurals.session_plurals,
                            needFeedbackIds.size(), needFeedbackIds.size()))
                    .setStyle(inboxStyle).setContentIntent(pi);
        }

        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        LogUtils.LOGD(TAG, "Now showing session feedback notification!");
        nm.notify(FEEDBACK_NOTIFICATION_ID, notifBuilder.build());

        for (int i = 0; i < needFeedbackIds.size(); i++) {
            setupNotificationOnWear(needFeedbackIds.get(i), null, needFeedbackTitles.get(i), null);
            feedbackHelper.setFeedbackNotificationAsFiredForSession(needFeedbackIds.get(i));
        }
    } finally {
        if (c != null) {
            try {
                c.close();
            } catch (Exception ignored) {
            }
        }
    }
}

From source file:com.somexapps.wyre.services.MediaService.java

private android.support.v4.app.NotificationCompat.Action generateAction(int icon, String title,
        String intentAction) {// w  ww  . j  a  v  a2  s.com
    Intent intent = new Intent(getApplicationContext(), MediaService.class);
    intent.setAction(intentAction);
    PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(),
            MEDIA_NOTIFICATION_REQUEST_CODE, intent, 0);

    return new android.support.v4.app.NotificationCompat.Action.Builder(icon, title, pendingIntent).build();
}

From source file:de.domjos.schooltools.activities.MainActivity.java

private void initServices() {
    try {/* w  ww  .j a v  a 2 s . c  o  m*/
        if (MainActivity.globals.getUserSettings().isNotificationsShown()) {
            // init Memory Service
            Intent intent = new Intent(this.getApplicationContext(), MemoryService.class);
            PendingIntent pendingIntent1 = PendingIntent.getService(this.getApplicationContext(), 0, intent, 0);

            // init frequently
            AlarmManager alarmManager1 = (AlarmManager) this.getApplicationContext()
                    .getSystemService(Context.ALARM_SERVICE);
            long frequency = 8 * 60 * 60 * 1000;
            assert alarmManager1 != null;
            alarmManager1.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(),
                    frequency, pendingIntent1);
        }
    } catch (Exception ex) {
        Helper.printException(this.getApplicationContext(), ex);
    }
}

From source file:com.naman14.timber.musicplayer.MusicService.java

@Override
public void onCreate() {
    if (D)/*ww  w  .  jav a  2  s.co m*/
        Log.d(TAG, "Creating service");
    super.onCreate();

    mNotificationManager = NotificationManagerCompat.from(this);

    // gets a pointer to the playback state store
    mPlaybackStateStore = MusicPlaybackState.getInstance(this);
    mSongPlayCount = SongPlayCount.getInstance(this);
    mRecentStore = RecentStore.getInstance(this);

    mHandlerThread = new HandlerThread("MusicPlayerHandler", android.os.Process.THREAD_PRIORITY_BACKGROUND);
    mHandlerThread.start();

    mPlayerHandler = new MusicPlayerHandler(this, mHandlerThread.getLooper());

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        setUpMediaSession();
    }

    mPreferences = getSharedPreferences("Service", 0);
    //        mCardId = getCardId();

    //        registerExternalStorageListener();

    mPlayer = new MultiPlayer2(this);
    mPlayer.setHandler(mPlayerHandler);

    // Initialize the intent filter and each action
    final IntentFilter filter = new IntentFilter();
    filter.addAction(SERVICECMD);
    filter.addAction(TOGGLEPAUSE_ACTION);
    filter.addAction(PAUSE_ACTION);
    filter.addAction(STOP_ACTION);
    filter.addAction(NEXT_ACTION);
    filter.addAction(PREVIOUS_ACTION);
    filter.addAction(PREVIOUS_FORCE_ACTION);
    filter.addAction(REPEAT_ACTION);
    filter.addAction(SHUFFLE_ACTION);

    // Attach the broadcast listener
    registerReceiver(mIntentReceiver, filter);

    //        mMediaStoreObserver = new MediaStoreObserver(mPlayerHandler);
    //        getContentResolver().registerContentObserver(
    //                MediaStore.Audio.Media.INTERNAL_CONTENT_URI, true, mMediaStoreObserver);
    //        getContentResolver().registerContentObserver(
    //                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true, mMediaStoreObserver);

    // Initialize the wake lock
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    mWakeLock.setReferenceCounted(false);

    final Intent shutdownIntent = new Intent(this, MusicService.class);
    shutdownIntent.setAction(SHUTDOWN);

    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0);

    scheduleDelayedShutdown();

    //        reloadQueueAfterPermissionCheck();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);
}

From source file:at.vcity.androidimsocket.services.IMService.java

public void authenticationResult(Object... args) {
    this.authenticatedUser = true;
    try {//from w w w  . j  av  a2 s .  c o m
        JSONObject param = new JSONObject(args[0].toString());
        String result = param.getString("result");
        if (result.equals(NetworkCommand.SUCCESSFUL)) {
            //currentUserId=param.getString("userId");
            FriendInfo f = new FriendInfo();
            f.userName = username;
            f.userId = param.getString("userId");
            Chatting.setCurrentUser(f);

            // getFriendList();

            AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(this, IMService.class);
            intent.putExtra("myToken", socketOperator.getToken());
            intent.putExtra("username", username);
            intent.putExtra("password", password);
            PendingIntent pintent = PendingIntent.getService(this, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                    SystemClock.elapsedRealtime() + WAKE_TIME_PERIOD, WAKE_TIME_PERIOD, pintent);

            Intent loginintent = new Intent(TRY_LOGIN);
            loginintent.putExtra("AUTHENTICATION_RESULT", NetworkCommand.SUCCESSFUL);
            sendBroadcast(loginintent);

            // Start heartbeat
            heartIsBeating = true;
            startHeartbeat();
        } else {
            Toast.makeText(this, "Wrong user name", Toast.LENGTH_SHORT).show();
        }
    } catch (JSONException e) {
    }
    ;
}

From source file:com.finchuk.clock2.chronometer.ChronometerNotificationService.java

/**
 * Adds the specified action to the notification's Builder.
 * @param id The id of the notification that the action should be added to.
 *           Will be used as an integer request code to create the PendingIntent that
 *           is fired when this action is clicked.
 *//*ww w .j  a  v  a 2 s . c om*/
protected final void addAction(String action, @DrawableRes int icon, String actionTitle, long id) {
    Intent intent = new Intent(this, getClass()).setAction(action).putExtra(EXTRA_ACTION_ID, id);
    PendingIntent pi = PendingIntent.getService(this, (int) id, intent, 0/*no flags*/);
    mNoteBuilders.get(id).addAction(icon, actionTitle, pi);
}

From source file:com.mylovemhz.simplay.MusicService.java

private NotificationCompat.Action generateAction(int icon, String title, String intentAction) {
    Intent intent = new Intent(getApplicationContext(), MusicService.class);
    intent.setAction(intentAction);/* ww w . j  av  a2s  .  c o  m*/
    PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
    return new NotificationCompat.Action.Builder(icon, title, pendingIntent).build();
}

From source file:com.tvs.signaltracker.MainScreen.java

@Override
protected void onResume() {
    super.onResume();
    CleanUp();//from   w  w  w .ja  v  a  2s  .  co  m
    try {
        if (STService.Opened == false) {
            Intent myIntent = new Intent(MainScreen.this, STService.class);
            PendingIntent pendingIntent = PendingIntent.getService(MainScreen.this, 0, myIntent, 0);
            AlarmManager alarmManager = (AlarmManager) MainScreen.this.getSystemService(Context.ALARM_SERVICE);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND, 1);
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        }
    } catch (Exception e) {
        Log.e("SignalTracker::onResume(MainScreen)", "Erro ao iniciar servio: " + e.getMessage());
    }
    if (!CommonHandler.ServiceRunning)
        CommonHandler.LoadLists();
    setUpMap();
    InitUp();
}