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.nextgis.maplibui.service.LayerFillService.java

@Override
public void onCreate() {
    mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Bitmap largeIcon = NotificationHelper.getLargeIcon(R.drawable.ic_notification_download, getResources());

    mProgressIntent = new Intent(ACTION_UPDATE);
    Intent intent = new Intent(this, LayerFillService.class);
    intent.setAction(ACTION_STOP);/*from w w w .j  a va 2s. com*/
    PendingIntent stopService = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    intent.setAction(ACTION_SHOW);
    PendingIntent showProgressDialog = PendingIntent.getService(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder = new NotificationCompat.Builder(this);
    mBuilder.setSmallIcon(R.drawable.ic_notification_download).setLargeIcon(largeIcon).setAutoCancel(false)
            .setOngoing(true).setContentIntent(showProgressDialog)
            .addAction(R.drawable.ic_action_cancel_dark, getString(R.string.tracks_stop), stopService);
    mIsCanceled = false;

    mQueue = new LinkedList<>();
    mIsRunning = false;
    mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle resultData = msg.getData();
            Toast.makeText(LayerFillService.this, resultData.getString(BUNDLE_MSG_KEY), Toast.LENGTH_LONG)
                    .show();
        }
    };

}

From source file:com.snappy.GCMIntentService.java

@SuppressWarnings("deprecation")
public void triggerNotification(Context context, String message, String fromName, Bundle pushExtras,
        String messageData) {/*ww w .jav  a 2  s. c om*/

    if (fromName != null) {
        final NotificationManager notificationManager = (NotificationManager) getSystemService(
                NOTIFICATION_SERVICE);

        Notification notification = new Notification(R.drawable.icon_notification, message,
                System.currentTimeMillis());

        notification.number = mNotificationCounter + 1;
        mNotificationCounter = mNotificationCounter + 1;

        Intent intent = new Intent(this, SplashScreenActivity.class);
        intent.replaceExtras(pushExtras);
        intent.putExtra(Const.PUSH_INTENT, true);
        intent.setAction(Long.toString(System.currentTimeMillis()));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_FROM_BACKGROUND
                | Intent.FLAG_ACTIVITY_TASK_ON_HOME);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, notification.number, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(this, context.getString(R.string.app_name), messageData, pendingIntent);

        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.defaults |= Notification.DEFAULT_LIGHTS;
        String notificationId = Double.toString(Math.random());
        notificationManager.notify(notificationId, 0, notification);

    }

    Log.i(LOG_TAG, message);
    Log.i(LOG_TAG, fromName);

}

From source file:edu.mines.letschat.GcmIntentService.java

private void sendNotification(String msg, String senderID) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra(MainActivity.EXTRA_NOTIFICATION_RETRIEVE, senderID);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    notificationCounter++;/*from   w w w  .j  ava2s.c  om*/

    if (messages.size() > 1) {
        msg = msg + "...";
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setVibrate(new long[] { 0, 500, 250, 500, 250 }).setLights(Color.BLUE, 200, 200)
            .setSmallIcon(R.drawable.logo).setContentTitle("Let's Chat Notification")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setNumber(notificationCounter)
            .setTicker(msg).setContentText(msg);

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    // Sets a title for the Inbox style big view
    inboxStyle.setBigContentTitle("Unread messages (" + notificationCounter + "):");
    // Moves events into the big view
    ArrayList<String> temp = new ArrayList<String>();
    for (int i = 0; i < 5; ++i) {
        if (i == messages.size()) {
            break;
        }
        temp.add(messages.get(i));
    }
    Collections.reverse(temp);
    messages = temp;
    for (String s : messages) {
        inboxStyle.addLine(s);
    }

    mBuilder.setStyle(inboxStyle);

    mBuilder.setAutoCancel(true);
    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    //        AwesomeAdapter.animate = true;
}

From source file:com.brayanarias.alarmproject.receiver.AlarmReceiver.java

public static PendingIntent createPendingIntent(Context context, Alarm alarm) {
    PendingIntent pendingIntent = null;/*  w  ww . java2 s  . c o  m*/
    try {
        Intent intent = new Intent(context, AlarmService.class);
        intent.putExtra(Constant.alarmIdKey, alarm.getId());
        intent.putExtra(Constant.alarmNameKey, alarm.getName());
        intent.putExtra(Constant.alarmHourKey, alarm.getHour());
        intent.putExtra(Constant.alarmMinuteKey, alarm.getMinute());
        intent.putExtra(Constant.alarmToneKey, alarm.getTone());
        intent.putExtra(Constant.alarmHourFormattedKey, alarm.getHourFormatted());
        intent.putExtra(Constant.alarmVibrateKey, alarm.getVibrate());
        intent.putExtra(Constant.alarmAmPmKey, alarm.getAmPm());
        intent.putExtra(Constant.alarmSoundHolidayKey, alarm.getOnHoliday());
        intent.putExtra(Constant.alarmDaysKey, alarm.getDaysOfAlamr());
        intent.putExtra(Constant.alarmDeleteAfterKey, alarm.getDeleteOnSound());
        intent.putExtra(Constant.alarmPostponeKey, alarm.getPostpone());
        pendingIntent = PendingIntent.getService(context, alarm.getId(), intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    } catch (Exception e) {
        Log.e(tag, e.getLocalizedMessage(), e);
    }
    return pendingIntent;
}

From source file:com.android.deskclock.data.TimerNotificationBuilderN.java

@Override
public Notification build(Context context, NotificationModel nm, List<Timer> unexpired) {
    final Timer timer = unexpired.get(0);
    final int count = unexpired.size();

    // Compute some values required below.
    final boolean running = timer.isRunning();
    final Resources res = context.getResources();

    final long base = getChronometerBase(timer);
    final String pname = context.getPackageName();
    final RemoteViews content = new RemoteViews(pname, R.layout.chronometer_notif_content);
    content.setChronometerCountDown(R.id.chronometer, true);
    content.setChronometer(R.id.chronometer, base, null, running);

    final List<Notification.Action> actions = new ArrayList<>(2);

    final CharSequence stateText;
    if (count == 1) {
        if (running) {
            // Single timer is running.
            if (TextUtils.isEmpty(timer.getLabel())) {
                stateText = res.getString(R.string.timer_notification_label);
            } else {
                stateText = timer.getLabel();
            }/*from w  ww  .j  av  a2  s  .  c  om*/

            // Left button: Pause
            final Intent pause = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_PAUSE_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());

            final Icon icon1 = Icon.createWithResource(context, R.drawable.ic_pause_24dp);
            final CharSequence title1 = res.getText(R.string.timer_pause);
            final PendingIntent intent1 = Utils.pendingServiceIntent(context, pause);
            actions.add(new Notification.Action.Builder(icon1, title1, intent1).build());

            // Right Button: +1 Minute
            final Intent addMinute = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_ADD_MINUTE_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());

            final Icon icon2 = Icon.createWithResource(context, R.drawable.ic_add_24dp);
            final CharSequence title2 = res.getText(R.string.timer_plus_1_min);
            final PendingIntent intent2 = Utils.pendingServiceIntent(context, addMinute);
            actions.add(new Notification.Action.Builder(icon2, title2, intent2).build());

        } else {
            // Single timer is paused.
            stateText = res.getString(R.string.timer_paused);

            // Left button: Start
            final Intent start = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_START_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());

            final Icon icon1 = Icon.createWithResource(context, R.drawable.ic_start_24dp);
            final CharSequence title1 = res.getText(R.string.sw_resume_button);
            final PendingIntent intent1 = Utils.pendingServiceIntent(context, start);
            actions.add(new Notification.Action.Builder(icon1, title1, intent1).build());

            // Right Button: Reset
            final Intent reset = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_RESET_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());

            final Icon icon2 = Icon.createWithResource(context, R.drawable.ic_reset_24dp);
            final CharSequence title2 = res.getText(R.string.sw_reset_button);
            final PendingIntent intent2 = Utils.pendingServiceIntent(context, reset);
            actions.add(new Notification.Action.Builder(icon2, title2, intent2).build());
        }
    } else {
        if (running) {
            // At least one timer is running.
            stateText = res.getString(R.string.timers_in_use, count);
        } else {
            // All timers are paused.
            stateText = res.getString(R.string.timers_stopped, count);
        }

        final Intent reset = TimerService.createResetUnexpiredTimersIntent(context);

        final Icon icon1 = Icon.createWithResource(context, R.drawable.ic_reset_24dp);
        final CharSequence title1 = res.getText(R.string.timer_reset_all);
        final PendingIntent intent1 = Utils.pendingServiceIntent(context, reset);
        actions.add(new Notification.Action.Builder(icon1, title1, intent1).build());
    }

    content.setTextViewText(R.id.state, stateText);

    // Intent to load the app and show the timer when the notification is tapped.
    final Intent showApp = new Intent(context, HandleDeskClockApiCalls.class)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setAction(HandleDeskClockApiCalls.ACTION_SHOW_TIMERS)
            .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId())
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, R.string.label_notification);

    final PendingIntent pendingShowApp = PendingIntent.getActivity(context, 0, showApp,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

    return new Notification.Builder(context).setOngoing(true).setLocalOnly(true).setShowWhen(false)
            .setAutoCancel(false).setCustomContentView(content).setContentIntent(pendingShowApp)
            .setPriority(Notification.PRIORITY_HIGH).setCategory(Notification.CATEGORY_ALARM)
            .setSmallIcon(R.drawable.stat_notify_timer).setGroup(nm.getTimerNotificationGroupKey())
            .setVisibility(Notification.VISIBILITY_PUBLIC).setStyle(new Notification.DecoratedCustomViewStyle())
            .setActions(actions.toArray(new Notification.Action[actions.size()]))
            .setColor(ContextCompat.getColor(context, R.color.default_background)).build();
}

From source file:com.chaitu.lmscalendar.ui.UrlDialog.java

@Override
public void onStart() {
    super.onStart();
    final AlertDialog dlg = (AlertDialog) getDialog();
    if (dlg == null)
        return;/*  w w w .ja  v a 2 s  . co m*/

    View.OnClickListener onClickTask;
    onClickTask = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String url = mTextCalendarUrl.getText().toString();
            String username = mTextUsername.getText().toString();
            String password = mTextPassword.getText().toString();
            String calendar = mTextPassword.getText().toString();
            long sync_interval = mSpinnerSyncInterval.getSelectedItemId();
            CalendarModel calendarModel = (CalendarModel) mSpinnerCalendar.getSelectedItem();
            int calID = calendarModel.getId();
            String calName = calendarModel.getName();

            /*if (!mActivity.setSource(url, null, username, password)) {
            TextView label = (TextView) dlg.findViewById(R.id.TextViewUrlError);
            label.setText(R.string.invalid_url);
            return;
            }*/

            Intent intent = new Intent(getActivity(), AlarmReceiver.class);
            intent.putExtra(AlarmReceiver.ACTION_ALARM, AlarmReceiver.ACTION_ALARM);
            final PendingIntent pIntent = PendingIntent.getBroadcast(getActivity(), 1234567, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager alarms = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
            alarms.cancel(pIntent);

            Settings settings = mActivity.getSettings();
            settings.putString(Settings.PREF_LASTURL, url);

            settings.putString(Settings.PREF_LASTURLUSERNAME, username);
            settings.putString(Settings.PREF_LASTURLPASSWORD, password);
            settings.putString(Settings.PREF_LASTCALENDARNAME, calName);
            settings.putInt(Settings.PREF_LASTCALENDARID, calID);
            settings.putInt(Settings.PREF_LASTSYNCINTERVAL, (int) sync_interval);
            mActivity.startIntent();
            dlg.dismiss();

        }
    };

    dlg.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(onClickTask);

}

From source file:org.cvasilak.jboss.mobile.app.service.UploadToJBossServerService.java

@Override
protected void onHandleIntent(Intent intent) {
    // initialize

    // extract details
    Server server = intent.getParcelableExtra("server");
    String directory = intent.getStringExtra("directory");
    String filename = intent.getStringExtra("filename");

    // get the json parser from the application
    JsonParser jsonParser = new JsonParser();

    // start the ball rolling...
    final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    builder.setTicker(String.format(getString(R.string.notif_ticker), filename))
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notif_large))
            .setSmallIcon(R.drawable.ic_stat_notif_small)
            .setContentTitle(String.format(getString(R.string.notif_title), filename))
            .setContentText(getString(R.string.notif_content_init))
            // to avoid NPE on android 2.x where content intent is required
            // set an empty content intent
            .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0)).setOngoing(true);

    // notify user that upload is starting
    mgr.notify(NOTIFICATION_ID, builder.build());

    // reset ticker for any subsequent notifications
    builder.setTicker(null);/*from w w  w.ja  va2  s  .c o m*/

    AbstractHttpClient client = CustomHTTPClient.getHttpClient();

    // enable digest authentication
    if (server.getUsername() != null && !server.getUsername().equals("")) {
        Credentials credentials = new UsernamePasswordCredentials(server.getUsername(), server.getPassword());

        client.getCredentialsProvider().setCredentials(
                new AuthScope(server.getHostname(), server.getPort(), AuthScope.ANY_REALM), credentials);
    }

    final File file = new File(directory, filename);
    final long length = file.length();

    try {
        CustomMultiPartEntity multipart = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                new CustomMultiPartEntity.ProgressListener() {
                    @Override
                    public void transferred(long num) {
                        // calculate percentage

                        //System.out.println("transferred: " + num);

                        int progress = (int) ((num * 100) / length);

                        builder.setContentText(String.format(getString(R.string.notif_content), progress));

                        mgr.notify(NOTIFICATION_ID, builder.build());
                    }
                });

        multipart.addPart(file.getName(), new FileBody(file));

        HttpPost httpRequest = new HttpPost(server.getHostPort() + "/management/add-content");
        httpRequest.setEntity(multipart);

        HttpResponse serverResponse = client.execute(httpRequest);

        BasicResponseHandler handler = new BasicResponseHandler();
        JsonObject reply = jsonParser.parse(handler.handleResponse(serverResponse)).getAsJsonObject();

        if (!reply.has("outcome")) {
            throw new RuntimeException(getString(R.string.invalid_response));
        } else {
            // remove the 'upload in-progress' notification
            mgr.cancel(NOTIFICATION_ID);

            String outcome = reply.get("outcome").getAsString();

            if (outcome.equals("success")) {

                String BYTES_VALUE = reply.get("result").getAsJsonObject().get("BYTES_VALUE").getAsString();

                Intent resultIntent = new Intent(this, UploadCompletedActivity.class);
                // populate it
                resultIntent.putExtra("server", server);
                resultIntent.putExtra("BYTES_VALUE", BYTES_VALUE);
                resultIntent.putExtra("filename", filename);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

                // the notification id for the 'completed upload' notification
                // each completed upload will have a different id
                int notifCompletedID = (int) System.currentTimeMillis();

                builder.setContentTitle(getString(R.string.notif_title_uploaded))
                        .setContentText(String.format(getString(R.string.notif_content_uploaded), filename))
                        .setContentIntent(
                                // we set the (2nd param request code to completedID)
                                // see http://tinyurl.com/kkcedju
                                PendingIntent.getActivity(this, notifCompletedID, resultIntent,
                                        PendingIntent.FLAG_UPDATE_CURRENT))
                        .setAutoCancel(true).setOngoing(false);

                mgr.notify(notifCompletedID, builder.build());

            } else {
                JsonElement elem = reply.get("failure-description");

                if (elem.isJsonPrimitive()) {
                    throw new RuntimeException(elem.getAsString());
                } else if (elem.isJsonObject())
                    throw new RuntimeException(
                            elem.getAsJsonObject().get("domain-failure-description").getAsString());
            }
        }

    } catch (Exception e) {
        builder.setContentText(e.getMessage()).setAutoCancel(true).setOngoing(false);

        mgr.notify(NOTIFICATION_ID, builder.build());
    }
}

From source file:com.nanostuffs.yurdriver.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *///from   w ww.j av  a2 s .c  o  m
private void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, MapActivity.class);
    notificationIntent.putExtra("fromNotification", "notification");
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    System.out.println("notification====>" + message);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    // notification.defaults |= Notification.DEFAULT_LIGHTS;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    notification.ledARGB = 0x00000000;
    notification.ledOnMS = 0;
    notification.ledOffMS = 0;
    notificationManager.notify(AndyConstants.NOTIFICATION_ID, notification);
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(
            PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,
            "WakeLock");
    wakeLock.acquire();
    wakeLock.release();

}

From source file:cm.android.download.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);/*w w w  .  jav a2 s .co 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;
                        Long l = mDownloadSpeed.get(info.mId);
                        if (l == null) {
                            l = 0L;
                        }
                        speed += l;
                    }
                }
            }

            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
                            "" + Helpers.formatDuration(mContext, 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:com.hybris.mobile.lib.location.geofencing.service.GeofencingIntentService.java

/**
 * Send a notification when a geofence is triggered
 *
 * @param geofence           the geofence triggered
 * @param notification       the notification object
 * @param geofenceTransition the geofence transition type
 *///  w w  w . j av  a 2s.c  o m
protected void sendNotification(Geofence geofence, GeofenceObject.Notification notification,
        int geofenceTransition) {

    if (notification != null) {

        // Notification
        String notificationContentTitle = notification.getNotificationTitle();
        String notificationContentText = notification.getNotificationText();
        int notificationIconResId = notification.getNotificationIconResId();

        Notification.Builder builder = new Notification.Builder(this);

        builder.setContentTitle(notificationContentTitle).setContentText(notificationContentText);

        if (notificationIconResId > 0) {
            builder.setSmallIcon(notificationIconResId);
        }

        try {
            // Intent on click on the notification
            if (StringUtils.isNotBlank(notification.getIntentClassDestination())) {
                Class<?> intentClassDestination = Class.forName(notification.getIntentClassDestination());

                // Create an explicit content Intent that starts the Activity defined in intentClassDestination
                Intent notificationIntent = new Intent(this, intentClassDestination);

                // Geofence Id to pass to the activity in order to retrieve the object
                if (notification.getIntentBundle() != null) {
                    GeofenceObject.IntentBundle intentBundle = notification.getIntentBundle();
                    notificationIntent.putExtra(intentBundle.getKeyName(), intentBundle.getBundle());

                    // Easter egg :)
                    if (intentBundle.getBundle().getBoolean(GeofencingConstants.EXTRA_PLAY_SOUND)) {
                        MediaPlayer mediaPlayer;
                        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
                            Log.d(TAG, "Playing entering geofence sound");
                            mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.entering_geofence);
                        } else {
                            Log.d(TAG, "Playing exiting geofence sound");
                            mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.leaving_geofence);
                        }

                        mediaPlayer.start();
                    }
                }

                PendingIntent notificationPendingIntent = PendingIntent.getActivity(this,
                        geofence.getRequestId().hashCode(), notificationIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT);

                builder.setContentIntent(notificationPendingIntent);
            }

        } catch (ClassNotFoundException e) {
            Log.e(TAG, "Unable to find class " + notification.getIntentClassDestination() + "."
                    + e.getLocalizedMessage());
        }

        // Constructing the Notification and setting the flag to auto remove the notification when the user click on it
        Notification notificationView;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            notificationView = builder.build();
        } else {
            notificationView = builder.getNotification();
        }

        notificationView.flags = Notification.FLAG_AUTO_CANCEL;
        notificationView.defaults = Notification.DEFAULT_ALL;

        // Get an instance of the Notification manager
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);

        // Issue the notification
        mNotificationManager.notify(UUID.randomUUID().toString().hashCode(), notificationView);
    } else {
        Log.e(TAG, "Notification empty for Geofence " + geofence);
    }

}