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.stasbar.knowyourself.alarms.AlarmNotifications.java

public static void showAlarmNotification(Service service, AlarmInstance instance) {
    LogUtils.v("Displaying alarm notification for alarm instance: " + instance.mId);

    Resources resources = service.getResources();
    NotificationCompat.Builder notification = new NotificationCompat.Builder(service)
            .setContentTitle(instance.getLabelOrDefault(service))
            .setContentText(AlarmUtils.getFormattedTime(service, instance.getAlarmTime()))
            .setColor(ContextCompat.getColor(service, R.color.default_background))
            .setSmallIcon(R.drawable.stat_notify_alarm).setOngoing(true).setAutoCancel(false)
            .setDefaults(NotificationCompat.DEFAULT_LIGHTS).setWhen(0)
            .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setLocalOnly(true);/* w  ww .  j  a  v  a  2s .  com*/

    // Setup Snooze Action
    Intent snoozeIntent = AlarmStateManager.createStateChangeIntent(service, AlarmStateManager.ALARM_SNOOZE_TAG,
            instance, AlarmInstance.SNOOZE_STATE);
    snoozeIntent.putExtra(AlarmStateManager.FROM_NOTIFICATION_EXTRA, true);
    PendingIntent snoozePendingIntent = PendingIntent.getService(service, instance.hashCode(), snoozeIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.addAction(R.drawable.ic_snooze_24dp, resources.getString(R.string.alarm_alert_snooze_text),
            snoozePendingIntent);

    // Setup Dismiss Action
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(service,
            AlarmStateManager.ALARM_DISMISS_TAG, instance, AlarmInstance.DISMISSED_STATE);
    dismissIntent.putExtra(AlarmStateManager.FROM_NOTIFICATION_EXTRA, true);
    PendingIntent dismissPendingIntent = PendingIntent.getService(service, instance.hashCode(), dismissIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.addAction(R.drawable.ic_alarm_off_24dp, resources.getString(R.string.alarm_alert_dismiss_text),
            dismissPendingIntent);

    // Setup Content Action
    Intent contentIntent = AlarmInstance.createIntent(service, AlarmActivity.class, instance.mId);
    notification.setContentIntent(PendingIntent.getActivity(service, instance.hashCode(), contentIntent,
            PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup fullscreen intent
    Intent fullScreenIntent = AlarmInstance.createIntent(service, AlarmActivity.class, instance.mId);
    // set action, so we can be different then content pending intent
    fullScreenIntent.setAction("fullscreen_activity");
    fullScreenIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
    notification.setFullScreenIntent(PendingIntent.getActivity(service, instance.hashCode(), fullScreenIntent,
            PendingIntent.FLAG_UPDATE_CURRENT), true);
    notification.setPriority(NotificationCompat.PRIORITY_MAX);

    clearNotification(service, instance);
    service.startForeground(instance.hashCode(), notification.build());
}

From source file:com.example.android.xyztouristattractions.service.UtilityService.java

/**
 * Show the notification. Either the regular notification with wearable features
 * added to enhance, or trigger the full micro app on the wearable.
 *
 * @param cityId The city to trigger the notification for
 * @param microApp If the micro app should be triggered or just enhanced notifications
 *//*from   w w  w  .  ja  v a2 s  . c o m*/
private void showNotification(String cityId, boolean microApp) {

    List<Attraction> attractions = ATTRACTIONS.get(cityId);

    if (microApp) {
        // If micro app we first need to transfer some data over
        sendDataToWearable(attractions);
    }

    // The first (closest) tourist attraction
    Attraction attraction = attractions.get(0);

    // Limit attractions to send
    int count = attractions.size() > Constants.MAX_ATTRACTIONS ? Constants.MAX_ATTRACTIONS : attractions.size();

    // Pull down the tourist attraction images from the network and store
    HashMap<String, Bitmap> bitmaps = new HashMap<>();
    try {
        for (int i = 0; i < count; i++) {
            bitmaps.put(attractions.get(i).name,
                    Glide.with(this).load(attractions.get(i).imageUrl).asBitmap()
                            .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                            .into(Constants.WEAR_IMAGE_SIZE, Constants.WEAR_IMAGE_SIZE).get());
        }
    } catch (InterruptedException | ExecutionException e) {
        Log.e(TAG, "Error fetching image from network: " + e);
    }

    // The intent to trigger when the notification is tapped
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            DetailActivity.getLaunchIntent(this, attraction.name), PendingIntent.FLAG_UPDATE_CURRENT);

    // The intent to trigger when the notification is dismissed, in this case
    // we want to clear remote notifications as well
    PendingIntent deletePendingIntent = PendingIntent.getService(this, 0,
            getClearRemoteNotificationsIntent(this), 0);

    // Construct the main notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmaps.get(attraction.name))
                    .setBigContentTitle(attraction.name).setSummaryText(getString(R.string.nearby_attraction)))
            .setLocalOnly(microApp).setContentTitle(attraction.name)
            .setContentText(getString(R.string.nearby_attraction))
            .setSmallIcon(R.drawable.ic_stat_maps_pin_drop).setContentIntent(pendingIntent)
            .setDeleteIntent(deletePendingIntent).setColor(getResources().getColor(R.color.colorPrimary))
            .setCategory(Notification.CATEGORY_RECOMMENDATION).setAutoCancel(true);

    if (!microApp) {
        // If not a micro app, create some wearable pages for
        // the other nearby tourist attractions.
        ArrayList<Notification> pages = new ArrayList<Notification>();
        for (int i = 1; i < count; i++) {

            // Calculate the distance from current location to tourist attraction
            String distance = Utils.formatDistanceBetween(Utils.getLocation(this), attractions.get(i).location);

            // Construct the notification and add it as a page
            pages.add(new NotificationCompat.Builder(this).setContentTitle(attractions.get(i).name)
                    .setContentText(distance).setSmallIcon(R.drawable.ic_stat_maps_pin_drop)
                    .extend(new NotificationCompat.WearableExtender()
                            .setBackground(bitmaps.get(attractions.get(i).name)))
                    .build());
        }
        builder.extend(new NotificationCompat.WearableExtender().addPages(pages));
    }

    // Trigger the notification
    NotificationManagerCompat.from(this).notify(Constants.MOBILE_NOTIFICATION_ID, builder.build());
}

From source file:com.asburymotors.android.disneysocal.service.UtilityService.java

/**
 * Show the notification. Either the regular notification with wearable features
 * added to enhance, or trigger the full micro app on the wearable.
 *
 * @param cityId The city to trigger the notification for
 * @param microApp If the micro app should be triggered or just enhanced notifications
 *///ww w  .  j av  a  2  s. c o  m
private void showNotification(String cityId, boolean microApp) {

    List<Attraction> attractions = ATTRACTIONS.get(cityId);

    if (microApp) {
        // If micro app we first need to transfer some data over
        sendDataToWearable(attractions);
    }

    // The first (closest) tourist attraction
    Attraction attraction = attractions.get(0);

    // Limit attractions to send
    int count = attractions.size() > Constants.MAX_ATTRACTIONS ? Constants.MAX_ATTRACTIONS : attractions.size();

    // Pull down the tourist attraction images from the network and store
    HashMap<String, Bitmap> bitmaps = new HashMap<>();
    try {
        for (int i = 0; i < count; i++) {
            bitmaps.put(attractions.get(i).name,
                    Glide.with(this).load(attractions.get(i).imageUrl).asBitmap()
                            .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                            .into(Constants.WEAR_IMAGE_SIZE, Constants.WEAR_IMAGE_SIZE).get());
        }
    } catch (InterruptedException | ExecutionException e) {
        Log.e(TAG, "Error fetching image from network: " + e);
    }

    // The intent to trigger when the notification is tapped
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            DetailActivity.getLaunchIntent(this, attraction.name), PendingIntent.FLAG_UPDATE_CURRENT);

    // The intent to trigger when the notification is dismissed, in this case
    // we want to clear remote notifications as well
    PendingIntent deletePendingIntent = PendingIntent.getService(this, 0,
            getClearRemoteNotificationsIntent(this), 0);

    // Construct the main notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmaps.get(attraction.name))
                    .setBigContentTitle(attraction.name).setSummaryText(getString(R.string.nearby_attraction)))
            .setLocalOnly(microApp).setContentTitle(attraction.name)
            .setContentText(getString(R.string.nearby_attraction))
            .setSmallIcon(R.drawable.ic_stat_maps_pin_drop).setContentIntent(pendingIntent)
            .setDeleteIntent(deletePendingIntent)
            .setColor(getResources().getColor(R.color.colorPrimary, getTheme()))
            .setCategory(Notification.CATEGORY_RECOMMENDATION).setAutoCancel(true);

    if (!microApp) {
        // If not a micro app, create some wearable pages for
        // the other nearby tourist attractions.
        ArrayList<Notification> pages = new ArrayList<Notification>();
        for (int i = 1; i < count; i++) {

            // Calculate the distance from current location to tourist attraction
            String distance = Utils.formatDistanceBetween(Utils.getLocation(this), attractions.get(i).location);

            // Construct the notification and add it as a page
            pages.add(new NotificationCompat.Builder(this).setContentTitle(attractions.get(i).name)
                    .setContentText(distance).setSmallIcon(R.drawable.ic_stat_maps_pin_drop)
                    .extend(new NotificationCompat.WearableExtender()
                            .setBackground(bitmaps.get(attractions.get(i).name)))
                    .build());
        }
        builder.extend(new NotificationCompat.WearableExtender().addPages(pages));
    }

    // Trigger the notification
    NotificationManagerCompat.from(this).notify(Constants.MOBILE_NOTIFICATION_ID, builder.build());
}

From source file:com.jjcamera.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./* ww w  .  ja  v a  2s .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.chen.mail.utils.NotificationActionUtils.java

/**
 * Creates a {@link PendingIntent} for the specified notification action.
 *///from   w ww. ja  va  2  s.c  om
private static PendingIntent getNotificationActionPendingIntent(final Context context, final Account account,
        final Conversation conversation, final Message message, final Folder folder,
        final Intent notificationIntent, final NotificationActionType action, final int notificationId,
        final long when) {
    final Uri messageUri = message.uri;

    final NotificationAction notificationAction = new NotificationAction(action, account, conversation, message,
            folder, conversation.id, message.serverId, message.id, when);

    switch (action) {
    case REPLY: {
        // Build a task stack that forces the conversation view on the stack before the
        // reply activity.
        final TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);

        final Intent intent = createReplyIntent(context, account, messageUri, false);
        intent.setPackage(context.getPackageName());
        intent.putExtra(ComposeActivity.EXTRA_NOTIFICATION_FOLDER, folder);
        // To make sure that the reply intents one notification don't clobber over
        // intents for other notification, force a data uri on the intent
        final Uri notificationUri = Uri.parse("mailfrom://mail/account/" + "reply/" + notificationId);
        intent.setData(notificationUri);

        taskStackBuilder.addNextIntent(notificationIntent).addNextIntent(intent);

        return taskStackBuilder.getPendingIntent(notificationId, PendingIntent.FLAG_UPDATE_CURRENT);
    }
    case REPLY_ALL: {
        // Build a task stack that forces the conversation view on the stack before the
        // reply activity.
        final TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);

        final Intent intent = createReplyIntent(context, account, messageUri, true);
        intent.setPackage(context.getPackageName());
        intent.putExtra(ComposeActivity.EXTRA_NOTIFICATION_FOLDER, folder);
        // To make sure that the reply intents one notification don't clobber over
        // intents for other notification, force a data uri on the intent
        final Uri notificationUri = Uri.parse("mailfrom://mail/account/" + "replyall/" + notificationId);
        intent.setData(notificationUri);

        taskStackBuilder.addNextIntent(notificationIntent).addNextIntent(intent);

        return taskStackBuilder.getPendingIntent(notificationId, PendingIntent.FLAG_UPDATE_CURRENT);
    }
    case ARCHIVE_REMOVE_LABEL: {
        final String intentAction = NotificationActionIntentService.ACTION_ARCHIVE_REMOVE_LABEL;

        final Intent intent = new Intent(intentAction);
        intent.setPackage(context.getPackageName());
        putNotificationActionExtra(intent, notificationAction);

        return PendingIntent.getService(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }
    case DELETE: {
        final String intentAction = NotificationActionIntentService.ACTION_DELETE;

        final Intent intent = new Intent(intentAction);
        intent.setPackage(context.getPackageName());
        putNotificationActionExtra(intent, notificationAction);

        return PendingIntent.getService(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }
    }

    throw new IllegalArgumentException("Invalid NotificationActionType");
}

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

private void notifySessionFeedback(boolean debug) {
    LOGD(TAG, "Considering firing notification for session feedback.");

    if (debug) {/*  w  w w. j  a  v a 2s.  c  o m*/
        LOGD(TAG, "Note: this is a debug notification.");
    }

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

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

    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 (UIUtils.isFeedbackNotificationFiredForSession(this, 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);
    }
}

From source file:com.hang.exoplayer.PlayService.java

public void showNotification() {
    String title = "XXXXXXXX";
    String description = "YYYYYYYYYYYYY";
    NotificationCompat.Builder builder = new NotificationCompat.Builder(PlayService.this).setAutoCancel(false)
            .setOngoing(true);/*from   w  ww. j a  v a  2  s  . co  m*/
    Class<?> targetClass = PlayActivity.class;
    Intent notificationIntent = new Intent(PlayService.this, targetClass);
    PendingIntent pendingIntent = PendingIntent.getActivity(PlayService.this, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);
    Intent playPauseIntent = new Intent(ExoApplication.getApplication(), PlayService.class);
    playPauseIntent.putExtra(ACTION_PLAY_PAUSE, true);
    Intent previousIntent = new Intent(ExoApplication.getApplication(), PlayService.class);
    previousIntent.putExtra(ACTION_PREVIOUS, true);
    Intent nextIntent = new Intent(ExoApplication.getApplication(), PlayService.class);
    nextIntent.putExtra(ACTION_NEXT, true);

    Intent dismissIntent = new Intent(ExoApplication.getApplication(), PlayService.class);
    dismissIntent.putExtra(ACTION_EXIT, true);

    PendingIntent playPendingIntent = PendingIntent.getService(PlayService.this, 1, playPauseIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    PendingIntent previousPendingIntent = PendingIntent.getService(PlayService.this, 2, previousIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent nextPendingIntent = PendingIntent.getService(PlayService.this, 3, nextIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent dismissPendingIntent = PendingIntent.getService(PlayService.this, 4, dismissIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification_high_version_no_live);
    contentView.setTextViewText(R.id.songName, title);
    contentView.setTextViewText(R.id.artist, description);
    boolean isPlaying = SimplePlayer.getInstance().isPlaying();
    //        Log.d(TAG, "Notification is Playing?" + isPlaying);
    contentView.setImageViewResource(R.id.play_pause,
            isPlaying ? R.drawable.ic_noti_play_normal : R.drawable.ic_noti_pause_normal);
    contentView.setOnClickPendingIntent(R.id.play_pause, playPendingIntent);
    contentView.setOnClickPendingIntent(R.id.play_pre, previousPendingIntent);
    contentView.setOnClickPendingIntent(R.id.forward, nextPendingIntent);
    contentView.setOnClickPendingIntent(R.id.stop, dismissPendingIntent);
    //        builder.setCustomContentView(contentView);
    builder.setContent(contentView);
    Notification notification = builder.setSmallIcon(R.mipmap.ic_launcher).build();
    startForeground(ID_NOTIFICATION, notification);
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.notify(ID_NOTIFICATION, notification);
}

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

public static void showAlarmNotification(Service service, AlarmInstance instance) {
    LogUtils.v("Displaying alarm notification for alarm instance: " + instance.mId);

    Resources resources = service.getResources();
    NotificationCompat.Builder notification = new NotificationCompat.Builder(service)
            .setContentTitle(instance.getLabelOrDefault(service))
            .setContentText(AlarmUtils.getFormattedTime(service, instance.getAlarmTime()))
            .setColor(ContextCompat.getColor(service, com.wizardsofm.deskclock.R.color.default_background))
            .setSmallIcon(com.wizardsofm.deskclock.R.drawable.stat_notify_alarm).setOngoing(true)
            .setAutoCancel(false).setDefaults(NotificationCompat.DEFAULT_LIGHTS).setWhen(0)
            .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setLocalOnly(true);/* w w w .  j a v  a 2  s .c om*/

    // Setup Snooze Action
    Intent snoozeIntent = AlarmStateManager.createStateChangeIntent(service, AlarmStateManager.ALARM_SNOOZE_TAG,
            instance, AlarmInstance.SNOOZE_STATE);
    snoozeIntent.putExtra(AlarmStateManager.FROM_NOTIFICATION_EXTRA, true);
    PendingIntent snoozePendingIntent = PendingIntent.getService(service, instance.hashCode(), snoozeIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.addAction(com.wizardsofm.deskclock.R.drawable.ic_snooze_24dp,
            resources.getString(com.wizardsofm.deskclock.R.string.alarm_alert_snooze_text),
            snoozePendingIntent);

    // Setup Dismiss Action
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(service,
            AlarmStateManager.ALARM_DISMISS_TAG, instance, AlarmInstance.DISMISSED_STATE);
    dismissIntent.putExtra(AlarmStateManager.FROM_NOTIFICATION_EXTRA, true);
    PendingIntent dismissPendingIntent = PendingIntent.getService(service, instance.hashCode(), dismissIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.addAction(com.wizardsofm.deskclock.R.drawable.ic_alarm_off_24dp,
            resources.getString(com.wizardsofm.deskclock.R.string.alarm_alert_dismiss_text),
            dismissPendingIntent);

    // Setup Content Action
    Intent contentIntent = AlarmInstance.createIntent(service, AlarmActivity.class, instance.mId);
    notification.setContentIntent(PendingIntent.getActivity(service, instance.hashCode(), contentIntent,
            PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup fullscreen intent
    Intent fullScreenIntent = AlarmInstance.createIntent(service, AlarmActivity.class, instance.mId);

    // set action, so we can be different then content pending intent
    fullScreenIntent.setAction("fullscreen_activity");
    fullScreenIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    // |Intent.FLAG_ACTIVITY_NO_USER_ACTION
    //        fullScreenIntent.addFlags(FLAG_FULLSCREEN +FLAG_SHOW_WHEN_LOCKED +  FLAG_TURN_SCREEN_ON
    //                + FLAG_DISMISS_KEYGUARD + FLAG_KEEP_SCREEN_ON);
    service.startActivity(fullScreenIntent);

    //        notification.setFullScreenIntent(PendingIntent.getActivity(service,
    //                instance.hashCode(), fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT), true);
    //        notification.setPriority(NotificationCompat.PRIORITY_MAX);
    //
    //        clearNotification(service, instance);
    //        service.startForeground(instance.hashCode(), notification.build());
}

From source file:com.koma.music.service.MusicService.java

/**
 * {@inheritDoc}// w w w . j a  v a  2s  . c  om
 */
@Override
public void onCreate() {
    LogUtils.d(TAG, "Creating service");
    super.onCreate();

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        stopSelf();
        return;
    } else {
        mReadGranted = true;
    }

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // Initialize the favorites and recents databases
    mRecentlyPlayCache = RecentlyPlay.getInstance(this);

    // gets the song play count cache
    mSongPlayCountCache = SongPlayCount.getInstance(this);

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

    // Initialize the image fetcher
    //  mImageFetcher = ImageFetcher.getInstance(this);
    // Initialize the image cache
    // mImageFetcher.setImageCache(ImageCache.getInstance(this));

    // Start up the thread running the service. Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block. We also make it
    // background priority so CPU-intensive work will not disrupt the UI.
    mHandlerThread = new HandlerThread("MusicPlayerHandler", android.os.Process.THREAD_PRIORITY_BACKGROUND);
    mHandlerThread.start();

    // Initialize the handler
    mPlayerHandler = new MusicPlayerHandler(this, mHandlerThread.getLooper());
    // Initialize the audio manager and register any headset controls for
    // playback
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    // Use the remote control APIs to set the playback state
    setUpMediaSession();

    // Initialize the preferences
    mPreferences = getSharedPreferences("MusicService", 0);
    mCardId = getCardId();

    mShowAlbumArtOnLockscreen = mPreferences.getBoolean(PreferenceUtils.SHOW_ALBUM_ART_ON_LOCKSCREEN, false);
    setShakeToPlayEnabled(mPreferences.getBoolean(PreferenceUtils.SHAKE_TO_PLAY, false));

    registerExternalStorageListener();

    // Initialize the media player
    mPlayer = new MultiPlayer(this);
    mPlayer.setHandler(mPlayerHandler);

    // Initialize the intent filter and each action
    final IntentFilter filter = new IntentFilter();
    filter.addAction(MusicServiceConstants.SERVICECMD);
    filter.addAction(MusicServiceConstants.TOGGLEPAUSE_ACTION);
    filter.addAction(MusicServiceConstants.PAUSE_ACTION);
    filter.addAction(MusicServiceConstants.STOP_ACTION);
    filter.addAction(MusicServiceConstants.NEXT_ACTION);
    filter.addAction(MusicServiceConstants.PREVIOUS_ACTION);
    filter.addAction(MusicServiceConstants.PREVIOUS_FORCE_ACTION);
    filter.addAction(MusicServiceConstants.REPEAT_ACTION);
    filter.addAction(MusicServiceConstants.SHUFFLE_ACTION);
    // Attach the broadcast listener
    registerReceiver(mIntentReceiver, filter);

    // Get events when MediaStore content changes
    mMediaObserver = new MediaObserver(mPlayerHandler);
    getContentResolver().registerContentObserver(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, true,
            mMediaObserver);
    getContentResolver().registerContentObserver(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true,
            mMediaObserver);

    // Initialize the delayed shutdown intent
    final Intent shutdownIntent = new Intent(this, MusicService.class);
    shutdownIntent.setAction(MusicServiceConstants.SHUTDOWN);

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

    // Listen for the idle state
    scheduleDelayedShutdown();

    // Bring the queue back
    reloadQueue();
    notifyChange(MusicServiceConstants.QUEUE_CHANGED);
    notifyChange(META_CHANGED);
}

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

private void notifySessionFeedback(boolean debug) {
    LogUtils.LOGD(TAG, "Considering firing notification for session feedback.");

    if (debug) {//  w  w  w . ja va2 s.co  m
        LogUtils.LOGD(TAG, "Note: this is a debug notification.");
    }

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

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

    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 (UIUtils.isFeedbackNotificationFiredForSession(this, 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(com.saarang.samples.apps.iosched.R.string.session_feedback_notification_ticker);
    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
            .setColor(getResources().getColor(com.saarang.samples.apps.iosched.R.color.theme_primary))
            .setContentText(provideFeedbackTicker).setTicker(provideFeedbackTicker)
            .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR, SessionAlarmService.NOTIFICATION_LED_ON_MS,
                    SessionAlarmService.NOTIFICATION_LED_OFF_MS)
            .setSmallIcon(com.saarang.samples.apps.iosched.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(com.saarang.samples.apps.iosched.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);
    }
}