Example usage for android.app PendingIntent getBroadcast

List of usage examples for android.app PendingIntent getBroadcast

Introduction

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

Prototype

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

Source Link

Document

Retrieve a PendingIntent that will perform a broadcast, like calling Context#sendBroadcast(Intent) Context.sendBroadcast() .

Usage

From source file:com.deepak.myclock.alarms.AlarmNotifications.java

public static void showSnoozeNotification(Context context, AlarmInstance instance) {
    Log.v("Displaying snoozed notification for alarm instance: " + instance.mId);
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Resources resources = context.getResources();
    NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
            .setContentTitle(instance.getLabelOrDefault(context))
            .setContentText(resources.getString(R.string.alarm_alert_snooze_until,
                    AlarmUtils.getFormattedTime(context, instance.getAlarmTime())))
            .setSmallIcon(R.drawable.stat_notify_alarm).setOngoing(true).setAutoCancel(false)
            .setPriority(NotificationCompat.PRIORITY_MAX);

    // Setup up dismiss action
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(context, "DISMISS_TAG", instance,
            AlarmInstance.DISMISSED_STATE);
    notification.addAction(android.R.drawable.ic_menu_close_clear_cancel,
            resources.getString(R.string.alarm_alert_dismiss_text), PendingIntent.getBroadcast(context,
                    instance.hashCode(), dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup content action if instance is owned by alarm
    long alarmId = instance.mAlarmId == null ? Alarm.INVALID_ID : instance.mAlarmId;
    Intent viewAlarmIntent = Alarm.createIntent(context, MainActivity.class, alarmId);
    //viewAlarmIntent.putExtra(DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.ALARM_TAB_INDEX);
    viewAlarmIntent.putExtra(AlarmClockFragment.SCROLL_TO_ALARM_INTENT_EXTRA, alarmId);
    viewAlarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    notification.setContentIntent(PendingIntent.getActivity(context, instance.hashCode(), viewAlarmIntent,
            PendingIntent.FLAG_UPDATE_CURRENT));
    nm.cancel(instance.hashCode());/* w  ww .  j a  v  a  2 s  . co  m*/
    nm.notify(instance.hashCode(), notification.build());
}

From source file:com.devbrackets.android.exomedia.EMLockScreen.java

private PendingIntent getMediaButtonReceiverPendingIntent(ComponentName componentName) {
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(componentName);

    mediaButtonIntent.putExtra(RECEIVER_EXTRA_CLASS, mediaServiceClass.getName());
    return PendingIntent.getBroadcast(context, 0, mediaButtonIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:net.peterkuterna.android.apps.devoxxfrsched.service.CfpSyncManager.java

/**
 * Create a {@link PendingIntent} for the alarm.
 * /*from w w w  .jav a  2s .  c o  m*/
 * @return
 */
private PendingIntent createAlarmPendingIntent() {
    final Context context = getContext();
    final Intent intent = new Intent(context, OnAlarmReceiver.class);
    return PendingIntent.getBroadcast(context, 0, intent, 0);
}

From source file:com.better.alarm.presenter.alert.AlarmAlertReceiver.java

private void onSnoozed(int id) {

    // What to do, when a user clicks on the notification bar
    Intent cancelSnooze = new Intent(mContext, AlarmAlertReceiver.class);
    cancelSnooze.setAction(ACTION_CANCEL_NOTIFICATION);
    cancelSnooze.putExtra(Intents.EXTRA_ID, id);
    PendingIntent pCancelSnooze = PendingIntent.getBroadcast(mContext, id, cancelSnooze, 0);

    // When button Reschedule is clicked, the TransparentActivity with
    // TimePickerFragment to set new alarm time is launched
    Intent reschedule = new Intent(mContext, TransparentActivity.class);
    reschedule.putExtra(Intents.EXTRA_ID, id);
    PendingIntent pendingReschedule = PendingIntent.getActivity(mContext, id, reschedule, 0);

    PendingIntent pendingDismiss = PresentationToModelIntents.createPendingIntent(mContext,
            PresentationToModelIntents.ACTION_REQUEST_DISMISS, id);

    String label = alarm.getLabelOrDefault(mContext);

    //@formatter:off
    Notification status = new NotificationCompat.Builder(mContext)
            // Get the display time for the snooze and update the notification.
            .setContentTitle(mContext.getString(R.string.alarm_notify_snooze_label, label))
            .setContentText(mContext.getString(R.string.alarm_notify_snooze_text, formatTimeString()))
            .setSmallIcon(R.drawable.stat_notify_alarm).setContentIntent(pCancelSnooze).setOngoing(true)
            .addAction(R.drawable.ic_action_reschedule_snooze,
                    mContext.getString(R.string.alarm_alert_reschedule_text), pendingReschedule)
            .addAction(R.drawable.ic_action_dismiss, mContext.getString(R.string.alarm_alert_dismiss_text),
                    pendingDismiss)// w w w .  ja  va  2  s .c  o  m
            .setDefaults(Notification.DEFAULT_LIGHTS).build();
    //@formatter:on

    // Send the notification using the alarm id to easily identify the
    // correct notification.
    nm.notify(id + NOTIFICATION_OFFSET, status);
}

From source file:com.android.providers.downloads.DownloadNotifier.java

private void updateWithLocked(Collection<DownloadInfo> downloads) {
    final Resources res = mContext.getResources();

    // Cluster downloads together
    final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create();
    for (DownloadInfo info : downloads) {
        final String tag = buildNotificationTag(info);
        if (tag != null) {
            clustered.put(tag, info);//from   ww  w . ja  va  2s. c o m
        }
    }

    // Build notification for each cluster
    for (String tag : clustered.keySet()) {
        final int type = getNotificationTagType(tag);
        final Collection<DownloadInfo> cluster = clustered.get(tag);

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);

        // Use time when cluster was first shown to avoid shuffling
        final long firstShown;
        if (mActiveNotifs.containsKey(tag)) {
            firstShown = mActiveNotifs.get(tag);
        } else {
            firstShown = System.currentTimeMillis();
            mActiveNotifs.put(tag, firstShown);
        }
        builder.setWhen(firstShown);

        // Show relevant icon
        if (type == TYPE_ACTIVE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download);
        } else if (type == TYPE_WAITING) {
            builder.setSmallIcon(android.R.drawable.stat_sys_warning);
        } else if (type == TYPE_COMPLETE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
        }

        // Build action intents
        if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
            // build a synthetic uri for intent identification purposes
            final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build();
            final Intent intent = new Intent(Constants.ACTION_LIST, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
            builder.setOngoing(true);

        } else if (type == TYPE_COMPLETE) {
            final DownloadInfo info = cluster.iterator().next();
            final Uri uri = ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId);
            builder.setAutoCancel(true);

            final String action;
            if (Downloads.Impl.isStatusError(info.mStatus)) {
                action = Constants.ACTION_LIST;
            } else {
                if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) {
                    action = Constants.ACTION_OPEN;
                } else {
                    action = Constants.ACTION_LIST;
                }
            }

            final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));

            final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class);
            builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
        }

        // Calculate and show progress
        String remainingText = null;
        String percentText = null;
        if (type == TYPE_ACTIVE) {
            long current = 0;
            long total = 0;
            long speed = 0;
            synchronized (mDownloadSpeed) {
                for (DownloadInfo info : cluster) {
                    if (info.mTotalBytes != -1) {
                        current += info.mCurrentBytes;
                        total += info.mTotalBytes;
                        speed += mDownloadSpeed.get(info.mId);
                    }
                }
            }

            if (total > 0) {
                final int percent = (int) ((current * 100) / total);
                percentText = res.getString(R.string.download_percent, percent);

                if (speed > 0) {
                    final long remainingMillis = ((total - current) * 1000) / speed;
                    remainingText = res.getString(R.string.download_remaining,
                            //                                DateUtils.formatDuration(remainingMillis)); // FIXME 
                            "" + remainingMillis);
                }

                builder.setProgress(100, percent, false);
            } else {
                builder.setProgress(100, 0, true);
            }
        }

        // Build titles and description
        final Notification notif;
        if (cluster.size() == 1) {
            final DownloadInfo info = cluster.iterator().next();

            builder.setContentTitle(getDownloadTitle(res, info));

            if (type == TYPE_ACTIVE) {
                if (!TextUtils.isEmpty(info.mDescription)) {
                    builder.setContentText(info.mDescription);
                } else {
                    builder.setContentText(remainingText);
                }
                builder.setContentInfo(percentText);

            } else if (type == TYPE_WAITING) {
                builder.setContentText(res.getString(R.string.notification_need_wifi_for_size));

            } else if (type == TYPE_COMPLETE) {
                if (Downloads.Impl.isStatusError(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_failed));
                } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_complete));
                }
            }

            notif = builder.build();

        } else {
            final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);

            for (DownloadInfo info : cluster) {
                inboxStyle.addLine(getDownloadTitle(res, info));
            }

            if (type == TYPE_ACTIVE) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_active, cluster.size(), cluster.size()));
                builder.setContentText(remainingText);
                builder.setContentInfo(percentText);
                inboxStyle.setSummaryText(remainingText);

            } else if (type == TYPE_WAITING) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
                builder.setContentText(res.getString(R.string.notification_need_wifi_for_size));
                inboxStyle.setSummaryText(res.getString(R.string.notification_need_wifi_for_size));
            }

            notif = inboxStyle.build();
        }

        mNotifManager.notify(tag, 0, notif);
    }

    // Remove stale tags that weren't renewed
    final Iterator<String> it = mActiveNotifs.keySet().iterator();
    while (it.hasNext()) {
        final String tag = it.next();
        if (!clustered.containsKey(tag)) {
            mNotifManager.cancel(tag, 0);
            it.remove();
        }
    }
}

From source file:ca.etsmtl.applets.etsmobile.NewsListActivity.java

private void setAlarm() {
    final Intent toAlarm = new Intent(this, NewsAlarmReceiver.class);
    final PendingIntent toDownload = PendingIntent.getBroadcast(this, 0, toAlarm,
            PendingIntent.FLAG_CANCEL_CURRENT);
    final AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    final Calendar updateTime = Calendar.getInstance();
    updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));

    updateTime.set(Calendar.HOUR_OF_DAY, 6);
    updateTime.set(Calendar.MINUTE, 00);
    alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            toDownload);/* w ww.j ava2s .c  o  m*/

    updateTime.set(Calendar.HOUR_OF_DAY, 12);
    alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            toDownload);

    updateTime.set(Calendar.HOUR_OF_DAY, 18);
    alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            toDownload);
}

From source file:com.javadog.cgeowear.MobileService.java

@Override
public void onCreate() {
    super.onCreate();

    //Register listener for INTENT_STOP events (from persistent notification)
    IntentFilter filter = new IntentFilter(INTENT_STOP);
    registerReceiver(intentReceiver, filter);

    //Register listener for when watch app closes
    IntentFilter localFilter = new IntentFilter(ListenerService.PATH_KILL_APP);
    LocalBroadcastManager.getInstance(this).registerReceiver(localReceiver, localFilter);

    //Show a persistent notification
    Intent stopServiceIntent = new Intent(INTENT_STOP);
    PendingIntent nIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, stopServiceIntent, 0);
    Notification notification = new NotificationCompat.Builder(getApplicationContext()).setOngoing(true)
            .setContentIntent(nIntent).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(getText(R.string.app_name)).setContentText(getText(R.string.notification_text))
            .build();//from   w  ww.  j  a  v a  2  s .com

    //Start service in foreground
    startForeground(R.string.app_name, notification);
}

From source file:com.gmail.at.faint545.fragments.QueueFragment.java

private void setRecurringAlarm() {
    if (getRemote().getRefreshInterval() != -1) {
        updateTime = Calendar.getInstance();
        updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
        updateTime.set(Calendar.MINUTE, 1);

        Intent downloader = new Intent(getActivity(), AlarmReciever.class);
        downloader.putExtra("url", getRemote().buildURL());
        downloader.putExtra("api", getRemote().getApiKey());
        downloader.putExtra("messenger", new Messenger(handler));

        PendingIntent recurringDownload = PendingIntent.getBroadcast(getActivity(), 0, downloader,
                PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager alarms = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
        alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(),
                getRemote().getRefreshInterval(), recurringDownload);
    } else {//from  w w  w .ja va  2s .c  om
        downloadQueue(null);
    }
}

From source file:vrisini.cordova.plugin.schedule.Schedule.java

/**
 * Cancel a specific notification that was previously registered.
 *
 * @param notificationId//from  w w w. j  av  a 2 s.  com
 *            The original ID of the notification that was used when it was
 *            registered using add()
 */
public static void cancel(String notificationId) {
    /*
     * Create an intent that looks similar, to the one that was registered
     * using add. Making sure the notification id in the action is the same.
     * Now we can search for such an intent using the 'getService' method
     * and cancel it.
     */
    Intent intent = new Intent(context, Receiver.class).setAction("" + notificationId);

    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager am = getAlarmManager();
    NotificationManager nc = getNotificationManager();

    am.cancel(pi);

    try {
        nc.cancel(Integer.parseInt(notificationId));
    } catch (Exception e) {
    }

    fireEvent("cancel", notificationId, "");
}

From source file:io.coldstart.android.GCMIntentService.java

private void sendBatchNotification(String batchCount) {
    if (null == batchCount)
        batchCount = "1+";

    Intent intent = new Intent(this, TrapListActivity.class);
    intent.putExtra("forceDownload", true);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

    Intent broadcastDownload = new Intent();
    broadcastDownload.setAction(BatchDownloadReceiver.BROADCAST_ACTION);
    PendingIntent pBroadcastDownload = PendingIntent.getBroadcast(this, 0, broadcastDownload, 0);

    Intent broadcastIgnore = new Intent();
    broadcastIgnore.setAction(BatchIgnoreReceiver.BROADCAST_ACTION);
    PendingIntent pBroadcastIgnore = PendingIntent.getBroadcast(this, 0, broadcastIgnore, 0);

    Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    Notification notification = null;

    if (Build.VERSION.SDK_INT >= 16) {
        notification = new Notification.InboxStyle(
                new Notification.Builder(this).setContentTitle("A batch of Traps has been sent")
                        .setContentText("\"Batched traps are waiting to be downloaded")
                        .setSmallIcon(R.drawable.ic_stat_ratelimit).setVibrate(new long[] { 0, 100, 200, 300 })
                        .setAutoCancel(true).setSound(uri).setPriority(Notification.PRIORITY_HIGH)
                        .setTicker("A batch of Traps has been sent")
                        .addAction(R.drawable.ic_download_batch, "Get Batched Traps", pBroadcastDownload)
                        .addAction(R.drawable.ic_ignore, "Ignore Batch", pBroadcastIgnore))
                                .setBigContentTitle("A batch of Traps has been sent")
                                .setSummaryText("Launch ColdStart.io to Manage These Events")
                                .addLine("A number of traps have been sent and batched for delivery")
                                .addLine("The current number of items queued is " + batchCount).addLine(" ")
                                .addLine("Tap \"Get Batched Traps\" to download the cached traps")
                                .addLine("Tap \"Ignore Batch\" to delete them from the server.")

                                .build();
    } else {//from  w  w w .jav  a2  s. com
        notification = new Notification.Builder(this).setContentTitle("A batch of Traps has been sent")
                .setContentText(
                        "A number of traps have been sent and batched for delivery. The current number of items queued is "
                                + batchCount
                                + "\nTap \"Get Alerts\" to batch download the outstanding traps or tap \"Ignore\" to delete them from the server.")
                .setSmallIcon(R.drawable.ic_stat_ratelimit).setContentIntent(pIntent)
                .setVibrate(new long[] { 0, 100, 200, 300 }).setAutoCancel(true).setSound(uri).build();
    }

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    notificationManager.notify(43524, notification);
}