Example usage for android.app PendingIntent FLAG_UPDATE_CURRENT

List of usage examples for android.app PendingIntent FLAG_UPDATE_CURRENT

Introduction

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

Prototype

int FLAG_UPDATE_CURRENT

To view the source code for android.app PendingIntent FLAG_UPDATE_CURRENT.

Click Source Link

Document

Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.

Usage

From source file:com.bangz.smartmute.services.LocationMuteService.java

private void NotificationUserFailed() {

    NotificationCompat.Builder nb = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_notification)
            .setColor(getResources().getColor(R.color.theme_accent_2))
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setAutoCancel(true);

    //        LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
    //        boolean bProviderEnabled =
    //                lm.isProviderEnabled(LocationManager.GPS_PROVIDER) |
    //                lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    int locationmode = ApiAdapterFactory.getApiAdapter().getLocationMode(this);
    if (locationmode <= ApiAdapter.LOCATION_MODE_SENSORS_ONLY) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        nb.setContentTitle(getResources().getString(R.string.location_provider_disabled_title));
        nb.setContentText(getResources().getString(R.string.location_provider_disabled_text));
        nb.setContentIntent(pi);//from w ww . j a v  a2 s  .co  m
    } else {
        // GPS and Network location provider is OK. let use try again
        Intent intent = new Intent(ACTION_START_GEOFENCES, null, this, LocationMuteService.class);
        PendingIntent pi = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        nb.setContentTitle(getResources().getString(R.string.geo_not_available_retry_title));
        nb.setContentText(getResources().getString(R.string.geo_not_available_retry_text));
        nb.setContentIntent(pi);
    }
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    nm.notify(GEOFENCE_NOT_AVLIABLE_NOTIFICATION_ID, nb.build());

}

From source file:com.daskiworks.ghwatch.backend.UnreadNotificationsService.java

protected void fireAndroidNotification(NotificationStream newStream, NotificationStream oldStream) {
    if (newStream == null || !PreferencesUtils.getBoolean(context, PreferencesUtils.PREF_NOTIFY, true))
        return;/*  ww w  .  j  a  v a 2  s.  com*/

    Log.d(TAG, "fireAndroidNotification count before filter " + newStream.size());
    newStream = filterForAndroidNotification(newStream);
    Log.d(TAG, "fireAndroidNotification count after filter " + newStream.size());
    if (newStream.isNewNotification(oldStream)) {

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.github_notification)
                .setContentTitle(context.getString(R.string.an_title_more))
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);
        mBuilder.setAutoCancel(true);

        if (newStream.size() > 1)
            mBuilder.setNumber(newStream.size());

        boolean allFromOne = newStream.allNotificationsFromSameRepository();

        if (newStream.size() == 1 || allFromOne) {
            // only one repository
            Notification n = newStream.get(0);
            Bitmap b = ImageLoader.getInstance(context).loadImageWithFileLevelCache(n.getRepositoryAvatarUrl());
            if (b != null) {
                mBuilder.setLargeIcon(b);
            } else {
                mBuilder.setLargeIcon(
                        BitmapFactory.decodeResource(context.getResources(), R.drawable.github_notification));
            }
            mBuilder.setContentText(n.getRepositoryFullName());
        } else {
            mBuilder.setLargeIcon(
                    BitmapFactory.decodeResource(context.getResources(), R.drawable.github_notification));
        }

        Intent resultIntent = null;
        if (newStream.size() == 1) {
            mBuilder.setContentTitle(context.getString(R.string.an_title_one));
            Notification n = newStream.get(0);
            mBuilder.setContentText(n.getRepositoryFullName() + ": " + n.getSubjectTitle());
            NotificationCompat.BigTextStyle btStyle = new NotificationCompat.BigTextStyle();
            btStyle.bigText(n.getSubjectTitle());
            btStyle.setSummaryText(n.getRepositoryFullName());
            mBuilder.setStyle(btStyle);
            Intent actionIntent = new Intent(context, MarkNotifiationAsReadReceiver.class);
            actionIntent.putExtra(MarkNotifiationAsReadReceiver.INTENT_EXTRA_KEY_ID, n.getId());
            mBuilder.addAction(R.drawable.ic_action_dismis_all, context.getString(R.string.action_mark_read),
                    PendingIntent.getBroadcast(context, 0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT));

            resultIntent = new Intent(context, MainActivity.class);
        } else {
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            for (Notification n : newStream) {
                if (allFromOne) {
                    inboxStyle.addLine(n.getSubjectTitle());
                } else {
                    inboxStyle.addLine(n.getRepositoryFullName() + ": " + n.getSubjectTitle());
                }
            }
            if (allFromOne)
                inboxStyle.setSummaryText(newStream.get(0).getRepositoryFullName());
            else
                inboxStyle.setSummaryText(" ");
            mBuilder.setStyle(inboxStyle);

            Intent actionIntent = new Intent(context, MainActivity.class);
            actionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            actionIntent.setAction(MainActivity.INTENT_ACTION_DISMISS_ALL);
            mBuilder.addAction(R.drawable.ic_action_dismis_all, context.getString(R.string.action_all_read),
                    PendingIntent.getActivity(context, 0, actionIntent, 0));

            resultIntent = new Intent(context, MainActivity.class);
        }

        resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        resultIntent.setAction(MainActivity.INTENT_ACTION_SHOW);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);
        mBuilder.setContentIntent(resultPendingIntent);

        String nsound = PreferencesUtils.getString(context, PreferencesUtils.PREF_NOTIFY_SOUND, null);
        Log.d(TAG, "Notification sound from preference: " + nsound);
        if (nsound != null) {
            mBuilder.setSound(Uri.parse(nsound));
        }
        if (PreferencesUtils.getBoolean(context, PreferencesUtils.PREF_NOTIFY_VIBRATE, true)) {
            mBuilder.setVibrate(new long[] { 0, 300, 100, 150, 100, 150 });
        }

        mBuilder.setLights(0xffffffff, 100, 4000);

        // mId allows you to update the notification later on.
        Utils.getNotificationManager(context).notify(ANDROID_NOTIFICATION_ID, mBuilder.build());
        ActivityTracker.sendEvent(context, ActivityTracker.CAT_NOTIF, "new_notif",
                "notif count: " + newStream.size(), Long.valueOf(newStream.size()));
    } else if (newStream.isEmpty()) {
        // #54 dismiss previous android notification if no any Github notification is available (as it was read on another device)
        Utils.getNotificationManager(context).cancel(ANDROID_NOTIFICATION_ID);
    }
}

From source file:com.ntsync.android.sync.syncadapter.SyncAdapter.java

private boolean processRestrictions(Restrictions currRestr, Restrictions newRestr, Account account)
        throws OperationApplicationException {
    boolean resync = false;
    if (newRestr != null && (currRestr == null || !currRestr.equals(newRestr))) {
        // Notify User.
        NotificationManager notificationManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        if (currRestr != null && newRestr.isPhotoSyncSupported() && !currRestr.isPhotoSyncSupported()) {

            // Create ViewAccount-Intent
            Intent viewAccountsIntent = new Intent(mContext, ViewAccountsActivity.class);
            // Adds the back stack
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
            stackBuilder.addParentStack(ViewAccountsActivity.class);
            stackBuilder.addNextIntent(viewAccountsIntent);

            // Photo sync possible.
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
                    .setSmallIcon(Constants.NOTIF_ICON)
                    .setContentTitle(mContext.getText(R.string.notif_photosyncenabled_title).toString())
                    .setContentText(account.name).setAutoCancel(true).setOnlyAlertOnce(true)
                    .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
            notificationManager.notify(Constants.NOTIF_PHOTO_SYNC_SUPPORTED, mBuilder.build());
            // Resync to sync Photos
            resync = true;//from   w  ww . ja v  a  2s. com

            setExplicitSavePhoto(account, true);
        }
        if (newRestr.isPhotoSyncSupported()) {
            notificationManager.cancel(Constants.NOTIF_PHOTO_NOT_SYNCED);
        }
        if (!newRestr.isPhotoSyncSupported()) {
            notificationManager.cancel(Constants.NOTIF_PHOTO_SYNC_SUPPORTED);
        }

        if (currRestr != null && newRestr.getMaxContactCount() != currRestr.getMaxContactCount()) {
            // Create ViewAccount-Intent
            Intent viewAccountsIntent = new Intent(mContext, ViewAccountsActivity.class);
            // Adds the back stack
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
            stackBuilder.addParentStack(ViewAccountsActivity.class);
            stackBuilder.addNextIntent(viewAccountsIntent);
            boolean moreAllowed = newRestr.getMaxContactCount() > currRestr.getMaxContactCount();
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
                    .setSmallIcon(Constants.NOTIF_ICON)
                    .setContentTitle(moreAllowed ? getText(R.string.notif_contact_moresupported_title)
                            : getText(R.string.notif_contact_lesssupported_title))
                    .setContentText(String.format(getText(R.string.notif_contact_supported_content),
                            newRestr.getMaxContactCount(), account.name))
                    .setAutoCancel(true).setOnlyAlertOnce(true)
                    .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
            notificationManager.notify(Constants.NOTIF_MAX_CONTACT_SUPPORTED, mBuilder.build());
            // Hide Contacts not syned, but allow the message to show up
            // again if there are still more than allowed.
            notificationManager.cancel(Constants.NOTIF_CONTACTS_NOT_SYNCED);
            unhideMaxContactMessage(mContext, account);
        }

        if (resync) {
            ContactManager.setDirtyFlag(mContext, account);
        }

        SyncUtils.saveRestrictions(account, mAccountManager, newRestr);
    }
    return resync;
}

From source file:me.calebjones.blogsite.network.PostDownloader.java

public void download(final List<String> postID) {
    final DatabaseManager databaseManager = new DatabaseManager(this);

    try {//from   w  w w.  j av a2s  .  c  o m
        final int num = postID.size() - 1;
        final CountDownLatch latch = new CountDownLatch(num);
        final Executor executor = Executors.newFixedThreadPool(15);

        for (int i = 1; i <= postID.size() - 1; i++) {
            final int count = i;
            final int index = Integer.parseInt(postID.get(i));
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        if (index != 404) {
                            String url = String.format(POST_URL, index);
                            Request newReq = new Request.Builder().url(url).build();
                            Response newResp = BlogsiteApplication.getInstance().client.newCall(newReq)
                                    .execute();

                            if (!newResp.isSuccessful() && !(newResp.code() == 404)
                                    && !(newResp.code() == 403)) {
                                Log.e("The Jones Theory", "Error: " + newResp.code() + "URL: " + url);
                                LocalBroadcastManager.getInstance(PostDownloader.this)
                                        .sendBroadcast(new Intent(DOWNLOAD_FAIL));
                                throw new IOException();
                            }

                            if (newResp.code() == 404) {
                                return;
                            }

                            String resp = newResp.body().string();

                            JSONObject jObject = new JSONObject(resp);

                            Posts item1 = new Posts();

                            //If the item is not a post break out of loop and ignore it
                            if (!(jObject.optString("type").equals("post"))) {
                                return;
                            }
                            item1.setTitle(jObject.optString("title"));
                            item1.setContent(jObject.optString("content"));
                            item1.setExcerpt(jObject.optString("excerpt"));
                            item1.setPostID(jObject.optInt("ID"));
                            item1.setURL(jObject.optString("URL"));

                            //Parse the Date!
                            String date = jObject.optString("date");
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                            Date newDate = format.parse(date);

                            format = new SimpleDateFormat("yyyy-MM-dd");
                            date = format.format(newDate);

                            item1.setDate(date);

                            //Cuts out all the Child nodes and gets only the  tags.
                            JSONObject Tobj = new JSONObject(jObject.optString("tags"));
                            JSONArray Tarray = Tobj.names();
                            String tagsList = null;

                            if (Tarray != null && (Tarray.length() > 0)) {

                                for (int c = 0; c < Tarray.length(); c++) {
                                    if (tagsList != null) {
                                        String thisTag = Tarray.getString(c);
                                        tagsList = tagsList + ", " + thisTag;
                                    } else {
                                        String thisTag = Tarray.getString(c);
                                        tagsList = thisTag;
                                    }
                                }
                                item1.setTags(tagsList);
                            } else {
                                item1.setTags("");
                            }

                            JSONObject Cobj = new JSONObject(jObject.optString("categories"));
                            JSONArray Carray = Cobj.names();
                            String catsList = null;

                            if (Carray != null && (Carray.length() > 0)) {

                                for (int c = 0; c < Carray.length(); c++) {
                                    if (catsList != null) {
                                        String thisCat = Carray.getString(c);
                                        catsList = catsList + ", " + thisCat;
                                    } else {
                                        String thisCat = Carray.getString(c);
                                        catsList = thisCat;
                                    }
                                }
                                item1.setCategories(catsList);
                            } else {
                                item1.setCategories("");
                            }

                            Integer ImageLength = jObject.optString("featured_image").length();
                            if (ImageLength == 0) {
                                item1.setFeaturedImage(null);
                            } else {
                                item1.setFeaturedImage(jObject.optString("featured_image"));
                            }
                            if (item1 != null) {
                                databaseManager.addPost(item1);
                                Log.d("PostDownloader", index + " database...");
                                double progress = ((double) count / num) * 100;
                                setProgress((int) progress, item1.getTitle(), count);

                                Intent intent = new Intent(DOWNLOAD_PROGRESS);
                                intent.putExtra(PROGRESS, progress);
                                intent.putExtra(NUMBER, num);
                                intent.putExtra(TITLE, item1.getTitle());

                                LocalBroadcastManager.getInstance(PostDownloader.this).sendBroadcast(intent);
                            }
                        }
                    } catch (IOException | JSONException | ParseException e) {
                        if (SharedPrefs.getInstance().isFirstDownload()) {
                            SharedPrefs.getInstance().setFirstDownload(false);
                        }
                        SharedPrefs.getInstance().setDownloading(false);
                        e.printStackTrace();
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            if (SharedPrefs.getInstance().isFirstDownload()) {
                SharedPrefs.getInstance().setFirstDownload(false);
            }
            SharedPrefs.getInstance().setDownloading(false);
            LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
            mBuilder.setContentText("Download failed.").setSmallIcon(R.drawable.ic_action_file_download)
                    .setAutoCancel(true).setProgress(0, 0, false).setOngoing(false);
            mNotifyManager.notify(NOTIF_ID, mBuilder.build());
            throw new IOException(e);
        }
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);

        Log.d("PostDownloader", "Broadcast Sent!");
        Log.d("The Jones Theory", "download - Downloading = " + SharedPrefs.getInstance().isDownloading());

        Intent mainActIntent = new Intent(this, MainActivity.class);
        PendingIntent clickIntent = PendingIntent.getActivity(this, 57836, mainActIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_SUCCESS));
        mBuilder.setContentText("Download complete").setSmallIcon(R.drawable.ic_action_done)
                .setProgress(0, 0, false).setContentIntent(clickIntent).setAutoCancel(true).setOngoing(false);
        mNotifyManager.notify(NOTIF_ID, mBuilder.build());

    } catch (IOException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setLastRedownladTime(System.currentTimeMillis());
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
        mBuilder.setContentText("Download failed.").setProgress(0, 0, false).setAutoCancel(true)
                .setOngoing(false);
        mNotifyManager.notify(NOTIF_ID, mBuilder.build());
    }
}

From source file:at.ac.uniklu.mobile.sportal.service.MutingService.java

private void notifyUser(int id, boolean ongoing, String tickerText, String contentTitle, String contentText,
        int icon, Intent intent) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = new NotificationCompat.Builder(this).setSmallIcon(icon).setTicker(tickerText)
            .setContentText(contentText).setContentTitle(contentTitle).setContentIntent(contentIntent)
            .setWhen(System.currentTimeMillis()).setOngoing(ongoing).build();

    notificationManager.notify(id, notification);
}

From source file:com.notalenthack.blaster.CommandActivity.java

private void startStatusUpdate() {
    // Setup expiration if we never get a message from the service
    AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent();
    intent.setAction(Constants.ACTION_REFRESH_STATUS);
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Set repeating updating of status, will need to cancel if activity is gone
    Calendar cal = Calendar.getInstance();
    am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), Constants.UPATE_STATUS_PERIOD * 1000, pi);
}

From source file:com.rainmakerlabs.bleepsample.BleepService.java

private void localNotification(String title, String message, Intent notificationIntent, String failMsg,
        int notifyId) {
    if (!testIntent(notificationIntent)) {
        //if (!BleepActivity.isTesting)
        //   return;
        notificationIntent = null;/*from  ww  w . j a v  a  2s  . com*/
        if (!failMsg.equalsIgnoreCase(""))
            message = failMsg;
    }
    if (notificationIntent == null) {
        notificationIntent = new Intent(this, BleepActivity.rootClass);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        notificationIntent.setAction(Intent.ACTION_MAIN);
        notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    }
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    if (message == null || message.equalsIgnoreCase(""))
        return;
    if (title == null || title.equalsIgnoreCase(""))
        title = getString(R.string.app_name);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setTicker(message).setWhen(System.currentTimeMillis())
            .setAutoCancel(true).setContentTitle(title).setContentText(message).setContentIntent(contentIntent)
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(notifyId, builder.build());
}

From source file:com.katamaditya.apps.weather4u.weathersync.Weather4USyncAdapter.java

public void notifyWeather() {
    Context context = getContext();
    //checking the last update and notify if it' the first of the day
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String displayNotificationsKey = context.getString(R.string.pref_enable_notifications_key);
    boolean displayNotifications = prefs.getBoolean(displayNotificationsKey,
            Boolean.parseBoolean(context.getString(R.string.pref_enable_notifications_default)));

    if (displayNotifications) {

        String lastNotificationKey = context.getString(R.string.pref_last_notification);
        long lastSync = prefs.getLong(lastNotificationKey, 0);

        if (System.currentTimeMillis() - lastSync >= getNotificationTimeGap()) {
            // Last sync was more than 1 day ago, let's send a notification with the weather.
            String locationQuery = WeatherUtil.getPreferredLocation(context);

            Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(locationQuery,
                    System.currentTimeMillis());

            // we'll query our contentProvider, as always
            Cursor cursor = context.getContentResolver().query(weatherUri, NOTIFY_WEATHER_PROJECTION, null,
                    null, null);//from   ww  w.j  a va 2s  .co m

            if (cursor.moveToFirst()) {
                int weatherId = cursor.getInt(INDEX_WEATHER_ID);
                double high = cursor.getDouble(INDEX_MAX_TEMP);
                double low = cursor.getDouble(INDEX_MIN_TEMP);
                String desc = cursor.getString(INDEX_SHORT_DESC);

                int iconId = WeatherUtil.getIconResourceForWeatherCondition(weatherId);
                Resources resources = context.getResources();
                Bitmap largeIcon = BitmapFactory.decodeResource(resources,
                        WeatherUtil.getArtResourceForWeatherCondition(weatherId));
                String title = getTitle();

                // Define the text of the forecast.
                String contentText = String.format(context.getString(R.string.format_notification), desc,
                        WeatherUtil.formatTemperature(context, high),
                        WeatherUtil.formatTemperature(context, low));

                // NotificationCompatBuilder is a very convenient way to build backward-compatible
                // notifications.  Just throw in some data.
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getContext())
                        .setColor(resources.getColor(R.color.weather4u_light_blue)).setSmallIcon(iconId)
                        .setLargeIcon(largeIcon).setContentTitle(title).setContentText(contentText);
                mBuilder.setAutoCancel(true);

                // Make something interesting happen when the user clicks on the notification.
                // In this case, opening the app is sufficient.
                Intent resultIntent = new Intent(context, MainActivity.class);

                // The stack builder object will contain an artificial back stack for the
                // started Activity.
                // This ensures that navigating backward from the Activity leads out of
                // your application to the Home screen.
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                stackBuilder.addNextIntent(resultIntent);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                mBuilder.setContentIntent(resultPendingIntent);

                NotificationManager mNotificationManager = (NotificationManager) getContext()
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                // WEATHER_NOTIFICATION_ID allows you to update the notification later on.
                mNotificationManager.notify(WEATHER_NOTIFICATION_ID, mBuilder.build());

                //refreshing last sync
                SharedPreferences.Editor editor = prefs.edit();
                editor.putLong(lastNotificationKey, System.currentTimeMillis());
                editor.commit();
            }
            cursor.close();
        }
    }
}

From source file:com.google.android.gms.location.sample.geofencing.MainActivity.java

/**
 * Gets a PendingIntent to send with the request to add or remove Geofences. Location Services
 * issues the Intent inside this PendingIntent whenever a geofence transition occurs for the
 * current list of geofences.//ww w . j  a v a  2  s  .  c o m
 *
 * @return A PendingIntent for the IntentService that handles geofence transitions.
 */
private PendingIntent getGeofencePendingIntent() {
    // Reuse the PendingIntent if we already have it.
    if (mGeofencePendingIntent != null) {
        return mGeofencePendingIntent;
    }
    Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
    // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
    // addGeofences() and removeGeofences().
    return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

From source file:com.bonsai.btcreceive.WalletService.java

private void showEventNotification(int noteId, int icon, String title, String msg) {
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(icon)
            .setContentTitle(title).setContentText(msg).setAutoCancel(true).setDefaults(
                    Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);

    // Creates an explicit intent for an Activity in your app
    Intent intent = new Intent(this, MainActivity.class);

    // The stack builder object will contain an artificial back
    // stack for the started Activity.  This ensures that
    // navigating backward from the Activity leads out of your
    // application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(MainActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(intent);/*from w w  w .j a  v a2s .  co m*/
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);

    mNM.notify(noteId, mBuilder.build());
}