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.kasungunathilaka.sarigama.service.PlayerService.java

@Override
public void onCreate() {
    localBroadcastManager = LocalBroadcastManager.getInstance(this);
    startIntent = PendingIntent.getBroadcast(PlayerService.this, REQUEST_CODE,
            new Intent(HomeActivity.ACTION_BRING_FRONT), PendingIntent.FLAG_UPDATE_CURRENT);
    playIntent = PendingIntent.getBroadcast(PlayerService.this, REQUEST_CODE,
            new Intent(HomeActivity.ACTION_PLAY), PendingIntent.FLAG_UPDATE_CURRENT);
    previousIntent = PendingIntent.getBroadcast(PlayerService.this, REQUEST_CODE,
            new Intent(HomeActivity.ACTION_PREV), PendingIntent.FLAG_UPDATE_CURRENT);
    nextIntent = PendingIntent.getBroadcast(PlayerService.this, REQUEST_CODE,
            new Intent(HomeActivity.ACTION_NEXT), PendingIntent.FLAG_UPDATE_CURRENT);
    notificationIntentReceiver = new NotificationIntentReceiver();
    registerReceiver(notificationIntentReceiver, new IntentFilter(HomeActivity.ACTION_PLAY));
    registerReceiver(notificationIntentReceiver, new IntentFilter(HomeActivity.ACTION_BRING_FRONT));
    registerReceiver(notificationIntentReceiver, new IntentFilter(HomeActivity.ACTION_NEXT));
    registerReceiver(notificationIntentReceiver, new IntentFilter(HomeActivity.ACTION_PREV));
}

From source file:br.ajmarques.cordova.plugin.localnotification.LocalNotification.java

/**
 * Cancel a specific notification that was previously registered.
 *
 * @param notificationId/* w  ww . ja  va2s . co m*/
 *            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) {
    }
}

From source file:com.cpd.receivers.LibraryRenewAlarmBroadcastReceiver.java

public void cancelAlarm(Context context) {
    Log.d(TAG, "cancelAlarm() called with: " + "context = [" + context + "]");
    Intent intent = new Intent(context, LibraryRenewAlarmBroadcastReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, 1, intent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(sender);//from  ww w .  ja  v  a 2  s .  co m
}

From source file:com.bayapps.android.robophish.MediaNotificationManager.java

public MediaNotificationManager(MusicService service) throws RemoteException {
    mService = service;/*from w ww .  j av  a2s.com*/
    updateSessionToken();

    mNotificationColor = ResourceHelper.getThemeColor(mService, R.attr.colorPrimary, Color.DKGRAY);

    mNotificationManager = NotificationManagerCompat.from(service);

    String pkg = mService.getPackageName();
    mPauseIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE, new Intent(ACTION_PAUSE).setPackage(pkg),
            PendingIntent.FLAG_CANCEL_CURRENT);
    mPlayIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE, new Intent(ACTION_PLAY).setPackage(pkg),
            PendingIntent.FLAG_CANCEL_CURRENT);
    mPreviousIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
            new Intent(ACTION_PREV).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    mNextIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE, new Intent(ACTION_NEXT).setPackage(pkg),
            PendingIntent.FLAG_CANCEL_CURRENT);
    mStopCastIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
            new Intent(ACTION_STOP_CASTING).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);

    // Cancel all notifications to handle the case where the Service was killed and
    // restarted by the system.
    mNotificationManager.cancelAll();
}

From source file:com.keylesspalace.tusky.util.NotificationManager.java

/**
 * Takes a given Mastodon notification and either creates a new Android notification or updates
 * the state of the existing notification to reflect the new interaction.
 *
 * @param context  to access application preferences and services
 * @param notifyId an arbitrary number to reference this notification for any future action
 * @param body     a new Mastodon notification
 *///from  ww  w.  j  a  v a  2 s. co  m
public static void make(final Context context, final int notifyId, Notification body) {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    final SharedPreferences notificationPreferences = context.getSharedPreferences("Notifications",
            Context.MODE_PRIVATE);

    if (!filterNotification(preferences, body)) {
        return;
    }

    createNotificationChannels(context);

    String rawCurrentNotifications = notificationPreferences.getString("current", "[]");
    JSONArray currentNotifications;

    try {
        currentNotifications = new JSONArray(rawCurrentNotifications);
    } catch (JSONException e) {
        currentNotifications = new JSONArray();
    }

    boolean alreadyContains = false;

    for (int i = 0; i < currentNotifications.length(); i++) {
        try {
            if (currentNotifications.getString(i).equals(body.account.getDisplayName())) {
                alreadyContains = true;
            }
        } catch (JSONException e) {
            Log.d(TAG, Log.getStackTraceString(e));
        }
    }

    if (!alreadyContains) {
        currentNotifications.put(body.account.getDisplayName());
    }

    notificationPreferences.edit().putString("current", currentNotifications.toString()).apply();

    Intent resultIntent = new Intent(context, MainActivity.class);
    resultIntent.putExtra("tab_position", 1);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent deleteIntent = new Intent(context, NotificationClearBroadcastReceiver.class);
    PendingIntent deletePendingIntent = PendingIntent.getBroadcast(context, 0, deleteIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context, getChannelId(body))
            .setSmallIcon(R.drawable.ic_notify).setContentIntent(resultPendingIntent)
            .setDeleteIntent(deletePendingIntent).setColor(ContextCompat.getColor(context, (R.color.primary)))
            .setDefaults(0); // So it doesn't ring twice, notify only in Target callback

    setupPreferences(preferences, builder);

    if (currentNotifications.length() == 1) {
        builder.setContentTitle(titleForType(context, body))
                .setContentText(truncateWithEllipses(bodyForType(body), 40));

        //load the avatar synchronously
        Bitmap accountAvatar;
        try {
            accountAvatar = Picasso.with(context).load(body.account.avatar)
                    .transform(new RoundedTransformation(7, 0)).get();
        } catch (IOException e) {
            Log.d(TAG, "error loading account avatar", e);
            accountAvatar = BitmapFactory.decodeResource(context.getResources(), R.drawable.avatar_default);
        }

        builder.setLargeIcon(accountAvatar);

    } else {
        try {
            String format = context.getString(R.string.notification_title_summary);
            String title = String.format(format, currentNotifications.length());
            String text = truncateWithEllipses(joinNames(context, currentNotifications), 40);
            builder.setContentTitle(title).setContentText(text);
        } catch (JSONException e) {
            Log.d(TAG, Log.getStackTraceString(e));
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setVisibility(android.app.Notification.VISIBILITY_PRIVATE);
        builder.setCategory(android.app.Notification.CATEGORY_SOCIAL);
    }

    android.app.NotificationManager notificationManager = (android.app.NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    //noinspection ConstantConditions
    notificationManager.notify(notifyId, builder.build());
}

From source file:com.cc.basefunction.service.MyFirebaseMessagingService.java

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 *///from ww  w .  j  a  v  a 2 s  .c o m
private void sendNotification(String messageBody) {
    Intent intentClick = new Intent(this, NotificationBroadCast.class);
    intentClick.setAction("BASEFUNCTION_NOTIFICATION_CLICK");
    intentClick.putExtra("message", messageBody);
    PendingIntent pendingIntentClick = PendingIntent.getBroadcast(this, 0, intentClick,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Intent intentCancel = new Intent(this, NotificationBroadCast.class);
    intentCancel.setAction("BASEFUNCTION_NOTIFICATION_CANCEL");
    intentCancel.putExtra("message", messageBody);
    PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(this, 0, intentCancel,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        notificationBuilder.setSmallIcon(R.drawable.notification_iocn);
        notificationBuilder.setColor(getResources().getColor(R.color.blue_B0E0E6));
    } else {
        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
    }
    notificationBuilder.setContentTitle("BaseFunction Notification").setContentText(messageBody)
            .setSound(defaultSoundUri).setContentIntent(pendingIntentClick)
            .setDeleteIntent(pendingIntentCancel);

    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    notificationManager.notify(10086 /* ID of notification */, notificationBuilder.build());
}

From source file:com.frapim.windwatch.Notifier.java

private NotificationCompat.Builder getNotificationBuilder(Context context) {
    Intent viewIntent = new Intent(context, SettingsActivity.class);
    PendingIntent viewPendingIntent = PendingIntent.getActivity(context, 0, viewIntent, 0);

    Intent disableIntent = new Intent(ACTION_DISABLE);
    PendingIntent disablePendingIntent = PendingIntent.getBroadcast(mContext, 0, disableIntent, 0);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher).setContentIntent(viewPendingIntent).addAction(
                    R.drawable.btn_cancel, mContext.getString(R.string.action_disable), disablePendingIntent);
    return notificationBuilder;
}

From source file:android.support.v7.media.RemotePlaybackClient.java

/**
 * Creates a remote playback client for a route.
 *
 * @param route The media route./*from   w  ww .  j  a  va  2 s .c  o m*/
 */
public RemotePlaybackClient(Context context, MediaRouter.RouteInfo route) {
    if (context == null) {
        throw new IllegalArgumentException("context must not be null");
    }
    if (route == null) {
        throw new IllegalArgumentException("route must not be null");
    }

    mContext = context;
    mRoute = route;

    IntentFilter actionFilter = new IntentFilter();
    actionFilter.addAction(ActionReceiver.ACTION_ITEM_STATUS_CHANGED);
    actionFilter.addAction(ActionReceiver.ACTION_SESSION_STATUS_CHANGED);
    actionFilter.addAction(ActionReceiver.ACTION_MESSAGE_RECEIVED);
    mActionReceiver = new ActionReceiver();
    context.registerReceiver(mActionReceiver, actionFilter);

    Intent itemStatusIntent = new Intent(ActionReceiver.ACTION_ITEM_STATUS_CHANGED);
    itemStatusIntent.setPackage(context.getPackageName());
    mItemStatusPendingIntent = PendingIntent.getBroadcast(context, 0, itemStatusIntent, 0);

    Intent sessionStatusIntent = new Intent(ActionReceiver.ACTION_SESSION_STATUS_CHANGED);
    sessionStatusIntent.setPackage(context.getPackageName());
    mSessionStatusPendingIntent = PendingIntent.getBroadcast(context, 0, sessionStatusIntent, 0);

    Intent messageIntent = new Intent(ActionReceiver.ACTION_MESSAGE_RECEIVED);
    messageIntent.setPackage(context.getPackageName());
    mMessagePendingIntent = PendingIntent.getBroadcast(context, 0, messageIntent, 0);
    detectFeatures();
}

From source file:com.dpcsoftware.mn.Widget1Config.java

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.item1:
        //Save Widget Preferences
        SharedPreferences.Editor pEditor = wPrefs.edit();
        int idSelected = ((RadioGroup) findViewById(R.id.radioGroup1)).getCheckedRadioButtonId();
        boolean byMonth = false;
        if (idSelected == R.id.radio0)
            byMonth = true;/*from ww  w . j  av a 2  s. c  o m*/
        pEditor.putBoolean(wId + "_BYMONTH", byMonth);
        pEditor.putLong(wId + "_GROUPID", sp.getSelectedItemId());
        pEditor.commit();

        //Update widget
        Intent updateIntent = new Intent(this, Widget1.class);
        updateIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { wId });
        try {
            PendingIntent.getBroadcast(this, 0, updateIntent, PendingIntent.FLAG_UPDATE_CURRENT).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }

        setResult(RESULT_OK, resultIntent);
        finish();
        break;
    }
    return true;
}

From source file:cw.kop.autobackground.files.DownloadThread.java

@Override
public void run() {
    super.run();/*from w  w  w . j ava  2s. c o m*/

    Looper.prepare();

    if (AppSettings.useDownloadNotification()) {
        PendingIntent pendingStopIntent = PendingIntent.getBroadcast(appContext, 0,
                new Intent(LiveWallpaperService.STOP_DOWNLOAD), 0);

        notificationManager = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
        notifyProgress = new Notification.Builder(appContext).setContentTitle("AutoBackground")
                .setContentText("Downloading images...").setSmallIcon(R.drawable.ic_photo_white_24dp);

        if (Build.VERSION.SDK_INT >= 16) {
            notifyProgress.setPriority(Notification.PRIORITY_MIN);
            notifyProgress.addAction(R.drawable.ic_cancel_white_24dp, "Stop Download", pendingStopIntent);
        }

        updateNotification(0);
    }

    String downloadCacheDir = AppSettings.getDownloadPath();

    File cache = new File(downloadCacheDir);

    if (!cache.exists() || !cache.isDirectory()) {
        cache.mkdir();
    }

    List<Integer> indexes = new ArrayList<>();
    for (int index = 0; index < AppSettings.getNumberSources(); index++) {

        Source source = AppSettings.getSource(index);

        if (!source.getType().equals(AppSettings.FOLDER) && source.isUse()) {
            indexes.add(index);
            progressMax += source.getNum();
        }
    }

    usedLinks = new HashSet<>();

    if (AppSettings.checkDuplicates()) {
        Set<String> rawLinks = AppSettings.getUsedLinks();
        for (String link : rawLinks) {
            if (link.lastIndexOf("Time:") > 0) {
                link = link.substring(0, link.lastIndexOf("Time:"));
            }
            usedLinks.add(link);
        }
    }

    downloadedFiles = new ArrayList<>();

    for (int index : indexes) {

        Source source = AppSettings.getSource(index);

        if (isInterrupted()) {
            cancel();
            return;
        }

        try {

            if (AppSettings.deleteOldImages()) {
                FileHandler.deleteBitmaps(appContext, source);
            }

            String title = source.getTitle();
            File file = new File(downloadCacheDir + "/" + title + " " + AppSettings.getImagePrefix());

            if (!file.exists() || !file.isDirectory()) {
                file.mkdir();
            }

            String sourceType = source.getType();
            String sourceData = source.getData();

            switch (sourceType) {
            case AppSettings.WEBSITE:
                downloadWebsite(sourceData, source);
                break;
            case AppSettings.IMGUR_SUBREDDIT:
                downloadImgurSubreddit(sourceData, source);
                break;
            case AppSettings.IMGUR_ALBUM:
                downloadImgurAlbum(sourceData, source);
                break;
            case AppSettings.GOOGLE_ALBUM:
                downloadPicasa(sourceData, source);
                break;
            case AppSettings.TUMBLR_BLOG:
                downloadTumblrBlog(sourceData, source);
                break;
            case AppSettings.TUMBLR_TAG:
                downloadTumblrTag(sourceData, source);
                break;
            case AppSettings.REDDIT_SUBREDDIT:
                downloadRedditSubreddit(sourceData, source);
                break;
            }

            totalTarget += source.getNum();

            updateNotification(totalTarget);

        } catch (IOException | IllegalArgumentException e) {
            sendToast("Invalid URL: " + source.getData());
            Log.i(TAG, "Invalid URL");
        }
    }
    finish();
}