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.dzt.musicplay.player.AudioService.java

/**
 * Set up the remote control and tell the system we want to be the default
 * receiver for the MEDIA buttons//from  w  w  w.ja  va  2s . c om
 * 
 * @see http 
 *      ://android-developers.blogspot.fr/2010/06/allowing-applications-to
 *      -play-nicer.html
 */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void setUpRemoteControlClient() {
    Context context = getApplicationContext();
    AudioManager audioManager = (AudioManager) context.getSystemService(AUDIO_SERVICE);

    if (LibVlcUtil.isICSOrLater()) {
        audioManager.registerMediaButtonEventReceiver(mRemoteControlClientReceiverComponent);

        if (mRemoteControlClient == null) {
            Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
            mediaButtonIntent.setComponent(mRemoteControlClientReceiverComponent);
            PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(context, 0, mediaButtonIntent, 0);

            // create and register the remote control client
            mRemoteControlClient = new RemoteControlClient(mediaPendingIntent);
            audioManager.registerRemoteControlClient(mRemoteControlClient);
        }

        mRemoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY
                | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
                | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_STOP);
    } else if (LibVlcUtil.isFroyoOrLater()) {
        audioManager.registerMediaButtonEventReceiver(mRemoteControlClientReceiverComponent);
    }
}

From source file:com.actinarium.nagbox.service.NagboxService.java

private void rescheduleAlarm() {
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    // Prepare pending intent. Setting, updating, or cancelling the alarm - we need it in either case
    Intent intent = new Intent(this, NagAlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    long nextTimestamp = NagboxDbOps.getClosestNagTimestamp(mDatabase);
    if (nextTimestamp == 0) {
        alarmManager.cancel(pendingIntent);
    } else {//from  w ww. j av  a2 s  .c o  m
        // todo: deal with exact/inexact reminders later
        if (Build.VERSION.SDK_INT >= 23) {
            alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nextTimestamp, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= 19) {
            alarmManager.setWindow(AlarmManager.RTC_WAKEUP, nextTimestamp, ALARM_TOLERANCE, pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, nextTimestamp, pendingIntent);
        }
    }
}

From source file:air.com.snagfilms.cast.chromecast.notifications.VideoCastNotificationService.java

private void addPendingIntents(RemoteViews rv, boolean isPlaying, MediaInfo info) {
    Intent playbackIntent = new Intent(ACTION_TOGGLE_PLAYBACK);
    playbackIntent.setPackage(getPackageName());
    PendingIntent playbackPendingIntent = PendingIntent.getBroadcast(this, 0, playbackIntent, 0);

    Intent stopIntent = new Intent(ACTION_STOP);
    stopIntent.setPackage(getPackageName());
    PendingIntent stopPendingIntent = PendingIntent.getBroadcast(this, 0, stopIntent, 0);

    rv.setOnClickPendingIntent(R.id.playPauseView, playbackPendingIntent);
    rv.setOnClickPendingIntent(R.id.removeView, stopPendingIntent);

    if (isPlaying) {
        if (info.getStreamType() == MediaInfo.STREAM_TYPE_LIVE) {
            rv.setImageViewResource(R.id.playPauseView, R.drawable.ic_av_stop_sm_dark);
        } else {//ww w .  j a v  a  2  s.  c  o m
            rv.setImageViewResource(R.id.playPauseView, R.drawable.ic_av_pause_sm_dark);
        }

    } else {
        rv.setImageViewResource(R.id.playPauseView, R.drawable.ic_av_play_sm_dark);
    }
}

From source file:co.codecrunch.musicplayerlite.manager.MusicPlayerService.java

public void setListeners(RemoteViews view) {
    try {/*from  w w  w . ja  v a2s  .c o m*/
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
                new Intent(NOTIFY_PREVIOUS), PendingIntent.FLAG_UPDATE_CURRENT);
        view.setOnClickPendingIntent(R.id.player_previous, pendingIntent);
        pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_CLOSE),
                PendingIntent.FLAG_UPDATE_CURRENT);
        view.setOnClickPendingIntent(R.id.player_close, pendingIntent);
        pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_PAUSE),
                PendingIntent.FLAG_UPDATE_CURRENT);
        view.setOnClickPendingIntent(R.id.player_pause, pendingIntent);
        pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_NEXT),
                PendingIntent.FLAG_UPDATE_CURRENT);
        view.setOnClickPendingIntent(R.id.player_next, pendingIntent);
        pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_PLAY),
                PendingIntent.FLAG_UPDATE_CURRENT);
        view.setOnClickPendingIntent(R.id.player_play, pendingIntent);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.geotrackin.gpslogger.GpsLoggingService.java

/**
 * Sets up the auto email timers based on user preferences.
 *//*from   w ww  .  ja  v  a  2  s .c o  m*/
public void SetupAutoSendTimers() {
    tracer.debug(
            "Setting up autosend timers. Auto Send Enabled - " + String.valueOf(AppSettings.isAutoSendEnabled())
                    + ", Auto Send Delay - " + String.valueOf(Session.getAutoSendDelay()));

    if (AppSettings.isAutoSendEnabled() && Session.getAutoSendDelay() > 0) {
        tracer.debug("Setting up autosend alarm");
        long triggerTime = System.currentTimeMillis() + (long) (Session.getAutoSendDelay() * 60 * 60 * 1000);

        alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
        CancelAlarm();

        PendingIntent sender = PendingIntent.getBroadcast(this, 0, alarmIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, triggerTime, sender);
        tracer.debug("Autosend alarm has been set");

    } else {
        if (alarmIntent != null) {
            tracer.debug("alarmIntent was null, canceling alarm");
            CancelAlarm();
        }
    }
}

From source file:cn.studyjams.s2.sj0132.bowenyan.mygirlfriend.nononsenseapps.notepad.data.receiver.NotificationHelper.java

/**
 * Needs the builder that contains non-note specific values.
 *
 *//*from  ww w.j  a  v a 2  s.  c  om*/
private static void notifyBigText(final Context context, final NotificationManager notificationManager,
        final NotificationCompat.Builder builder,
        final cn.studyjams.s2.sj0132.bowenyan.mygirlfriend.nononsenseapps.notepad.data.model.sql.Notification note) {
    final Intent delIntent = new Intent(Intent.ACTION_DELETE, note.getUri());
    if (note.repeats != 0) {
        delIntent.setAction(ACTION_RESCHEDULE);
    }
    // Add extra so we don't delete all
    // if (note.time != null) {
    // delIntent.putExtra(ARG_MAX_TIME, note.time);
    // }
    delIntent.putExtra(ARG_TASKID, note.taskID);
    // Delete it on clear
    PendingIntent deleteIntent = PendingIntent.getBroadcast(context, 0, delIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Open intent
    final Intent openIntent = new Intent(Intent.ACTION_VIEW, Task.getUri(note.taskID));
    // Should create a new instance to avoid fragment problems
    openIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

    // Delete intent on non-location repeats
    // Opening the note should delete/reschedule the notification
    openIntent.putExtra(NOTIFICATION_DELETE_ARG, note._id);

    // Opening always cancels the notification though
    openIntent.putExtra(NOTIFICATION_CANCEL_ARG, note._id);

    // Open note on click
    PendingIntent clickIntent = PendingIntent.getActivity(context, 0, openIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Action to complete
    PendingIntent completeIntent = PendingIntent.getBroadcast(context, 0,
            new Intent(ACTION_COMPLETE, note.getUri()).putExtra(ARG_TASKID, note.taskID),
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Action to snooze
    PendingIntent snoozeIntent = PendingIntent.getBroadcast(context, 0,
            new Intent(ACTION_SNOOZE, note.getUri()).putExtra(ARG_TASKID, note.taskID),
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Build notification
    builder.setContentTitle(note.taskTitle).setContentText(note.taskNote).setContentIntent(clickIntent)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(note.taskNote));

    // Delete intent on non-location repeats
    builder.setDeleteIntent(deleteIntent);

    // Snooze button only on time non-repeating
    if (note.time != null && note.repeats == 0) {
        builder.addAction(R.drawable.ic_alarm_24dp_white, context.getText(R.string.snooze), snoozeIntent);
    }
    // Complete button only on non-repeating, both time and location
    if (note.repeats == 0) {
        builder.addAction(R.drawable.ic_check_24dp_white, context.getText(R.string.completed), completeIntent);
    }

    final Notification noti = builder.build();

    notificationManager.notify((int) note._id, noti);
}

From source file:com.atlas.mars.weatherradar.MainActivity.java

void morningAlarm() {

    //todo  ?   ??
    //startService(new Intent(this, MorningService.class));

    long time = db.getMorningWakeUp();
    alarmManagerMorning = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    morningIntent = createIntent("morningAction", "extraMorning", MorningBroadCast.class);
    startService(morningIntent);//from ww  w  .jav  a 2  s  .  c o m
    pIntent2 = PendingIntent.getBroadcast(this, 0, morningIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    alarmManagerMorning.cancel(pIntent2);

    alarmManagerMorning.set(AlarmManager.RTC_WAKEUP, time, pIntent2);
    //todo ?   ?  ??
    // alarmManagerMorning.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+1*1000, pIntent2);
}

From source file:com.cityfreqs.littlesirecho.MainActivity.java

private void setAlarmNotification() {
    Context context = getBaseContext();
    Intent notifyIntent = new Intent();
    notifyIntent.setAction(ALARM_ACTION);

    if (alarmIntent != null) {
        // already set
        return;// w  w w .  j a  va  2 s  .c  om
    } else {
        alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmIntent = PendingIntent.getBroadcast(context, 0, notifyIntent, 0);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + userSelectedWaitTime,
                userSelectedWaitTime, alarmIntent);
    }
}

From source file:com.atlas.mars.weatherradar.MainActivity.java

void morningAlarmCancel() {
    if (pIntent2 != null && alarmManagerMorning != null) {
        pIntent2 = PendingIntent.getBroadcast(this, 0, morningIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmManagerMorning.cancel(pIntent1);
    }//from   ww w  .  ja  v a  2 s .c  om
}

From source file:com.google.android.apps.muzei.notifications.NewWallpaperNotificationReceiver.java

public static void maybeShowNewArtworkNotification(Context context) {
    ArtDetailOpenedClosedEvent adoce = EventBus.getDefault().getStickyEvent(ArtDetailOpenedClosedEvent.class);
    if (adoce != null && adoce.isArtDetailOpened()) {
        return;//w ww.  ja v  a  2s .  c o  m
    }

    if (!isNewWallpaperNotificationEnabled(context)) {
        return;
    }

    ContentResolver contentResolver = context.getContentResolver();
    ArtworkSource artworkSource = MuzeiDatabase.getInstance(context).artworkDao()
            .getCurrentArtworkWithSourceBlocking();
    if (artworkSource == null) {
        return;
    }

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    long currentArtworkId = artworkSource.artwork.id;
    long lastReadArtworkId = sp.getLong(PREF_LAST_READ_NOTIFICATION_ARTWORK_ID, -1);
    String currentImageUri = artworkSource.artwork.imageUri != null ? artworkSource.artwork.imageUri.toString()
            : null;
    String lastReadImageUri = sp.getString(PREF_LAST_READ_NOTIFICATION_ARTWORK_IMAGE_URI, null);
    String currentToken = artworkSource.artwork.token;
    String lastReadToken = sp.getString(PREF_LAST_READ_NOTIFICATION_ARTWORK_TOKEN, null);
    // We've already dismissed the notification if the IDs match
    boolean previouslyDismissedNotification = lastReadArtworkId == currentArtworkId;
    // We've already dismissed the notification if the image URIs match and both are not empty
    previouslyDismissedNotification = previouslyDismissedNotification || (!TextUtils.isEmpty(lastReadImageUri)
            && !TextUtils.isEmpty(currentImageUri) && TextUtils.equals(lastReadImageUri, currentImageUri));
    // We've already dismissed the notification if the tokens match and both are not empty
    previouslyDismissedNotification = previouslyDismissedNotification || (!TextUtils.isEmpty(lastReadToken)
            && !TextUtils.isEmpty(currentToken) && TextUtils.equals(lastReadToken, currentToken));
    if (previouslyDismissedNotification) {
        return;
    }

    Bitmap largeIcon;
    Bitmap background;
    try {
        BitmapFactory.Options options = new BitmapFactory.Options();
        // Check if there's rotation
        int rotation = 0;
        try (InputStream in = contentResolver.openInputStream(MuzeiContract.Artwork.CONTENT_URI)) {
            if (in == null) {
                return;
            }
            ExifInterface exifInterface = new ExifInterface(in);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotation = 90;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                rotation = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                rotation = 270;
                break;
            }
        } catch (IOException | NumberFormatException | StackOverflowError e) {
            Log.w(TAG, "Couldn't open EXIF interface on artwork", e);
        }
        BitmapRegionLoader regionLoader = BitmapRegionLoader
                .newInstance(contentResolver.openInputStream(MuzeiContract.Artwork.CONTENT_URI), rotation);
        int width = regionLoader.getWidth();
        int height = regionLoader.getHeight();
        int shortestLength = Math.min(width, height);
        options.inJustDecodeBounds = false;
        int largeIconHeight = context.getResources()
                .getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
        options.inSampleSize = ImageUtil.calculateSampleSize(shortestLength, largeIconHeight);
        largeIcon = regionLoader.decodeRegion(new Rect(0, 0, width, height), options);

        // Use the suggested 400x400 for Android Wear background images per
        // http://developer.android.com/training/wearables/notifications/creating.html#AddWearableFeatures
        options.inSampleSize = ImageUtil.calculateSampleSize(height, 400);
        background = regionLoader.decodeRegion(new Rect(0, 0, width, height), options);
    } catch (IOException e) {
        Log.e(TAG, "Unable to load artwork to show notification", e);
        return;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        createNotificationChannel(context);
    }

    String artworkTitle = artworkSource.artwork.title;
    String title = TextUtils.isEmpty(artworkTitle) ? context.getString(R.string.app_name) : artworkTitle;
    NotificationCompat.Builder nb = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL)
            .setSmallIcon(R.drawable.ic_stat_muzei)
            .setColor(ContextCompat.getColor(context, R.color.notification))
            .setPriority(NotificationCompat.PRIORITY_MIN).setAutoCancel(true).setContentTitle(title)
            .setContentText(context.getString(R.string.notification_new_wallpaper)).setLargeIcon(largeIcon)
            .setContentIntent(PendingIntent.getActivity(context, 0,
                    context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()),
                    PendingIntent.FLAG_UPDATE_CURRENT))
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0,
                    new Intent(context, NewWallpaperNotificationReceiver.class)
                            .setAction(ACTION_MARK_NOTIFICATION_READ),
                    PendingIntent.FLAG_UPDATE_CURRENT));
    NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle().bigLargeIcon(null)
            .setBigContentTitle(title).setSummaryText(artworkSource.artwork.byline).bigPicture(background);
    nb.setStyle(style);

    NotificationCompat.WearableExtender extender = new NotificationCompat.WearableExtender();

    // Support Next Artwork
    if (artworkSource.supportsNextArtwork) {
        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(context, 0,
                new Intent(context, NewWallpaperNotificationReceiver.class).setAction(ACTION_NEXT_ARTWORK),
                PendingIntent.FLAG_UPDATE_CURRENT);
        nb.addAction(R.drawable.ic_notif_next_artwork,
                context.getString(R.string.action_next_artwork_condensed), nextPendingIntent);
        // Android Wear uses larger action icons so we build a
        // separate action
        extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_notif_full_next_artwork,
                context.getString(R.string.action_next_artwork_condensed), nextPendingIntent)
                        .extend(new NotificationCompat.Action.WearableExtender().setAvailableOffline(false))
                        .build());
    }
    List<UserCommand> commands = artworkSource.commands;
    // Show custom actions as a selectable list on Android Wear devices
    if (!commands.isEmpty()) {
        String[] actions = new String[commands.size()];
        for (int h = 0; h < commands.size(); h++) {
            actions[h] = commands.get(h).getTitle();
        }
        PendingIntent userCommandPendingIntent = PendingIntent.getBroadcast(context, 0,
                new Intent(context, NewWallpaperNotificationReceiver.class).setAction(ACTION_USER_COMMAND),
                PendingIntent.FLAG_UPDATE_CURRENT);
        RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_USER_COMMAND).setAllowFreeFormInput(false)
                .setLabel(context.getString(R.string.action_user_command_prompt)).setChoices(actions).build();
        extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_notif_full_user_command,
                context.getString(R.string.action_user_command), userCommandPendingIntent)
                        .addRemoteInput(remoteInput)
                        .extend(new NotificationCompat.Action.WearableExtender().setAvailableOffline(false))
                        .build());
    }
    Intent viewIntent = artworkSource.artwork.viewIntent;
    if (viewIntent != null) {
        viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            PendingIntent nextPendingIntent = PendingIntent.getActivity(context, 0, viewIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            nb.addAction(R.drawable.ic_notif_info, context.getString(R.string.action_artwork_info),
                    nextPendingIntent);
            // Android Wear uses larger action icons so we build a
            // separate action
            extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_notif_full_info,
                    context.getString(R.string.action_artwork_info), nextPendingIntent)
                            .extend(new NotificationCompat.Action.WearableExtender().setAvailableOffline(false))
                            .build());
        } catch (RuntimeException ignored) {
            // This is actually meant to catch a FileUriExposedException, but you can't
            // have catch statements for exceptions that don't exist at your minSdkVersion
        }
    }
    nb.extend(extender);

    // Hide the image and artwork title for the public version
    NotificationCompat.Builder publicBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL)
            .setSmallIcon(R.drawable.ic_stat_muzei)
            .setColor(ContextCompat.getColor(context, R.color.notification))
            .setPriority(NotificationCompat.PRIORITY_MIN).setAutoCancel(true)
            .setContentTitle(context.getString(R.string.app_name))
            .setContentText(context.getString(R.string.notification_new_wallpaper))
            .setContentIntent(PendingIntent.getActivity(context, 0,
                    context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()),
                    PendingIntent.FLAG_UPDATE_CURRENT))
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0,
                    new Intent(context, NewWallpaperNotificationReceiver.class)
                            .setAction(ACTION_MARK_NOTIFICATION_READ),
                    PendingIntent.FLAG_UPDATE_CURRENT));
    nb.setPublicVersion(publicBuilder.build());

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    nm.notify(NOTIFICATION_ID, nb.build());
}