Example usage for android.app PendingIntent FLAG_ONE_SHOT

List of usage examples for android.app PendingIntent FLAG_ONE_SHOT

Introduction

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

Prototype

int FLAG_ONE_SHOT

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

Click Source Link

Document

Flag indicating that this PendingIntent can be used only once.

Usage

From source file:com.synox.android.files.services.FileUploader.java

/**
 * Updates the status notification with the result of an upload operation.
 *
 * @param uploadResult Result of the upload operation.
 * @param upload Finished upload operation
 *//* w ww . ja va2 s  .co  m*/
private void notifyUploadResult(RemoteOperationResult uploadResult, UploadFileOperation upload) {
    Log_OC.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode());
    // / cancelled operation or success -> silent removal of progress notification
    mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);

    // Show the result: success or fail notification
    if (!uploadResult.isCancelled()) {
        int tickerId = (uploadResult.isSuccess()) ? R.string.uploader_upload_succeeded_ticker
                : R.string.uploader_upload_failed_ticker;

        String content;

        // check credentials error
        boolean needsToUpdateCredentials = (uploadResult.getCode() == ResultCode.UNAUTHORIZED
                || uploadResult.isIdPRedirection());
        tickerId = (needsToUpdateCredentials) ? R.string.uploader_upload_failed_credentials_error : tickerId;

        mNotificationBuilder.setTicker(getString(tickerId)).setContentTitle(getString(tickerId))
                .setAutoCancel(true).setOngoing(false).setProgress(0, 0, false);

        content = ErrorMessageAdapter.getErrorCauseMessage(uploadResult, upload, getResources());

        if (needsToUpdateCredentials) {
            // let the user update credentials with one click
            Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
            updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount());
            updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
                    AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
            updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
            mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this,
                    (int) System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT));

            mUploadClient = null;
            // grant that future retries on the same account will get the fresh credentials
        } else {
            mNotificationBuilder.setContentText(content);

            if (upload.isInstant()) {
                DbHandler db = null;
                try {
                    db = new DbHandler(this.getBaseContext());
                    String message = uploadResult.getLogMessage() + " errorCode: " + uploadResult.getCode();
                    Log_OC.e(TAG, message + " Http-Code: " + uploadResult.getHttpCode());
                    if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
                        //message = getString(R.string.failed_upload_quota_exceeded_text);
                        if (db.updateFileState(upload.getOriginalStoragePath(), message) == 0) {
                            db.putFileForLater(upload.getOriginalStoragePath(), upload.getAccount().name,
                                    message);
                        }
                    }
                } finally {
                    if (db != null) {
                        db.close();
                    }
                }
            }
        }

        mNotificationBuilder.setContentText(content);
        mNotificationManager.notify(tickerId, mNotificationBuilder.build());

        if (uploadResult.isSuccess()) {

            DbHandler db = new DbHandler(this.getBaseContext());
            db.removeIUPendingFile(mCurrentUpload.getOriginalStoragePath());
            db.close();

            // remove success notification, with a delay of 2 seconds
            NotificationDelayer.cancelWithDelay(mNotificationManager, R.string.uploader_upload_succeeded_ticker,
                    2000);

        }
    }
}

From source file:com.cerema.cloud2.files.services.FileUploader.java

/**
 * Updates the status notification with the result of an upload operation.
 *
 * @param uploadResult  Result of the upload operation.
 * @param upload        Finished upload operation
 *///from   w  w w.  ja va 2s  . c o  m
private void notifyUploadResult(UploadFileOperation upload, RemoteOperationResult uploadResult) {
    Log_OC.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode());
    // / cancelled operation or success -> silent removal of progress notification
    mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);

    // Show the result: success or fail notification
    if (!uploadResult.isCancelled()) {
        int tickerId = (uploadResult.isSuccess()) ? R.string.uploader_upload_succeeded_ticker
                : R.string.uploader_upload_failed_ticker;

        String content;

        // check credentials error
        boolean needsToUpdateCredentials = (uploadResult.getCode() == ResultCode.UNAUTHORIZED
                || uploadResult.isIdPRedirection());
        tickerId = (needsToUpdateCredentials) ? R.string.uploader_upload_failed_credentials_error : tickerId;

        mNotificationBuilder.setTicker(getString(tickerId)).setContentTitle(getString(tickerId))
                .setAutoCancel(true).setOngoing(false).setProgress(0, 0, false);

        content = ErrorMessageAdapter.getErrorCauseMessage(uploadResult, upload, getResources());

        if (needsToUpdateCredentials) {
            // let the user update credentials with one click
            Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
            updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount());
            updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
                    AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
            updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
            mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this,
                    (int) System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT));

            mUploadClient = null;
            // grant that future retries on the same account will get the fresh credentials
        } else {
            mNotificationBuilder.setContentText(content);

            if (upload.isInstant()) {
                DbHandler db = null;
                try {
                    db = new DbHandler(this.getBaseContext());
                    String message = uploadResult.getLogMessage() + " errorCode: " + uploadResult.getCode();
                    Log_OC.e(TAG, message + " Http-Code: " + uploadResult.getHttpCode());
                    if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
                        //message = getString(R.string.failed_upload_quota_exceeded_text);
                        if (db.updateFileState(upload.getOriginalStoragePath(),
                                DbHandler.UPLOAD_STATUS_UPLOAD_FAILED, message) == 0) {
                            db.putFileForLater(upload.getOriginalStoragePath(), upload.getAccount().name,
                                    message);
                        }
                    }
                } finally {
                    if (db != null) {
                        db.close();
                    }
                }
            }
        }

        mNotificationBuilder.setContentText(content);
        mNotificationManager.notify(tickerId, mNotificationBuilder.build());

        if (uploadResult.isSuccess()) {

            DbHandler db = new DbHandler(this.getBaseContext());
            db.removeIUPendingFile(mCurrentUpload.getOriginalStoragePath());
            db.close();

            // remove success notification, with a delay of 2 seconds
            NotificationDelayer.cancelWithDelay(mNotificationManager, R.string.uploader_upload_succeeded_ticker,
                    2000);

        }
    }
}

From source file:me.cpwc.nibblegram.android.NotificationsController.java

public void showWearNotifications(boolean notifyAboutLast) {
    if (Build.VERSION.SDK_INT < 19) {
        return;/*  w ww .  ja v a 2s.c o m*/
    }
    ArrayList<Long> sortedDialogs = new ArrayList<Long>();
    HashMap<Long, ArrayList<MessageObject>> messagesByDialogs = new HashMap<Long, ArrayList<MessageObject>>();
    for (MessageObject messageObject : pushMessages) {
        long dialog_id = messageObject.getDialogId();
        if ((int) dialog_id == 0) {
            continue;
        }

        ArrayList<MessageObject> arrayList = messagesByDialogs.get(dialog_id);
        if (arrayList == null) {
            arrayList = new ArrayList<MessageObject>();
            messagesByDialogs.put(dialog_id, arrayList);
            sortedDialogs.add(0, dialog_id);
        }
        arrayList.add(messageObject);
    }

    HashMap<Long, Integer> oldIds = new HashMap<Long, Integer>();
    oldIds.putAll(wearNoticationsIds);
    wearNoticationsIds.clear();

    for (long dialog_id : sortedDialogs) {
        ArrayList<MessageObject> messageObjects = messagesByDialogs.get(dialog_id);
        int max_id = messageObjects.get(0).messageOwner.id;
        TLRPC.Chat chat = null;
        TLRPC.User user = null;
        String name = null;
        if (dialog_id > 0) {
            user = MessagesController.getInstance().getUser((int) dialog_id);
            if (user == null) {
                continue;
            }
        } else {
            chat = MessagesController.getInstance().getChat(-(int) dialog_id);
            if (chat == null) {
                continue;
            }
        }
        if (chat != null) {
            name = chat.title;
        } else {
            name = ContactsController.formatName(user.first_name, user.last_name);
        }

        Integer notificationId = oldIds.get(dialog_id);
        if (notificationId == null) {
            notificationId = wearNotificationId++;
        } else {
            oldIds.remove(dialog_id);
        }

        Intent replyIntent = new Intent(ApplicationLoader.applicationContext, WearReplyReceiver.class);
        replyIntent.putExtra("dialog_id", dialog_id);
        replyIntent.putExtra("max_id", max_id);
        PendingIntent replyPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext,
                notificationId, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
                .setLabel(LocaleController.getString("Reply", R.string.Reply)).build();
        String replyToString;
        if (chat != null) {
            replyToString = LocaleController.formatString("ReplyToGroup", R.string.ReplyToGroup, name);
        } else {
            replyToString = LocaleController.formatString("ReplyToUser", R.string.ReplyToUser, name);
        }
        NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon,
                replyToString, replyPendingIntent).addRemoteInput(remoteInput).build();

        String text = "";
        for (MessageObject messageObject : messageObjects) {
            String message = getStringForMessage(messageObject, false);
            if (message == null) {
                continue;
            }
            if (chat != null) {
                message = message.replace(" @ " + name, "");
            } else {
                message = message.replace(name + ": ", "").replace(name + " ", "");
            }
            if (text.length() > 0) {
                text += "\n\n";
            }
            text += message;
        }

        Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
        intent.setFlags(32768);
        if (chat != null) {
            intent.putExtra("chatId", chat.id);
        } else if (user != null) {
            intent.putExtra("userId", user.id);
        }
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                ApplicationLoader.applicationContext).setContentTitle(name)
                        .setSmallIcon(R.drawable.notification).setGroup("messages").setContentText(text)
                        .setGroupSummary(false).setContentIntent(contentIntent)
                        .extend(new NotificationCompat.WearableExtender().addAction(action))
                        .setCategory(NotificationCompat.CATEGORY_MESSAGE);

        if (chat == null && user != null && user.phone != null && user.phone.length() > 0) {
            builder.addPerson("tel:+" + user.phone);
        }

        notificationManager.notify(notificationId, builder.build());
        wearNoticationsIds.put(dialog_id, notificationId);
    }

    for (HashMap.Entry<Long, Integer> entry : oldIds.entrySet()) {
        notificationManager.cancel(entry.getValue());
    }
}

From source file:com.negaheno.android.NotificationsController.java

public void showWearNotifications(boolean notifyAboutLast) {
    if (Build.VERSION.SDK_INT < 19) {
        return;/*from   w ww . j  av  a  2  s.co  m*/
    }
    ArrayList<Long> sortedDialogs = new ArrayList<>();
    HashMap<Long, ArrayList<MessageObject>> messagesByDialogs = new HashMap<>();
    for (MessageObject messageObject : pushMessages) {
        long dialog_id = messageObject.getDialogId();
        if ((int) dialog_id == 0) {
            continue;
        }

        ArrayList<MessageObject> arrayList = messagesByDialogs.get(dialog_id);
        if (arrayList == null) {
            arrayList = new ArrayList<>();
            messagesByDialogs.put(dialog_id, arrayList);
            sortedDialogs.add(0, dialog_id);
        }
        arrayList.add(messageObject);
    }

    HashMap<Long, Integer> oldIds = new HashMap<>();
    oldIds.putAll(wearNoticationsIds);
    wearNoticationsIds.clear();

    for (long dialog_id : sortedDialogs) {
        ArrayList<MessageObject> messageObjects = messagesByDialogs.get(dialog_id);
        int max_id = messageObjects.get(0).messageOwner.id;
        TLRPC.Chat chat = null;
        TLRPC.User user = null;
        String name = null;
        if (dialog_id > 0) {
            user = MessagesController.getInstance().getUser((int) dialog_id);
            if (user == null) {
                continue;
            }
        } else {
            chat = MessagesController.getInstance().getChat(-(int) dialog_id);
            if (chat == null) {
                continue;
            }
        }
        if (chat != null) {
            name = chat.title;
        } else {
            name = ContactsController.formatName(user.first_name, user.last_name);
        }

        Integer notificationId = oldIds.get(dialog_id);
        if (notificationId == null) {
            notificationId = wearNotificationId++;
        } else {
            oldIds.remove(dialog_id);
        }

        Intent replyIntent = new Intent(ApplicationLoader.applicationContext, WearReplyReceiver.class);
        replyIntent.putExtra("dialog_id", dialog_id);
        replyIntent.putExtra("max_id", max_id);
        PendingIntent replyPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext,
                notificationId, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
                .setLabel(LocaleController.getString("Reply", R.string.Reply)).build();
        String replyToString;
        if (chat != null) {
            replyToString = LocaleController.formatString("ReplyToGroup", R.string.ReplyToGroup, name);
        } else {
            replyToString = LocaleController.formatString("ReplyToUser", R.string.ReplyToUser, name);
        }
        NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon,
                replyToString, replyPendingIntent).addRemoteInput(remoteInput).build();

        String text = "";
        for (MessageObject messageObject : messageObjects) {
            String message = getStringForMessage(messageObject, false);
            if (message == null) {
                continue;
            }
            if (chat != null) {
                message = message.replace(" @ " + name, "");
            } else {
                message = message.replace(name + ": ", "").replace(name + " ", "");
            }
            if (text.length() > 0) {
                text += "\n\n";
            }
            text += message;
        }

        Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
        intent.setFlags(32768);
        if (chat != null) {
            intent.putExtra("chatId", chat.id);
        } else if (user != null) {
            intent.putExtra("userId", user.id);
        }
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                ApplicationLoader.applicationContext).setContentTitle(name)
                        .setSmallIcon(R.drawable.notification).setGroup("messages").setContentText(text)
                        .setGroupSummary(false).setContentIntent(contentIntent)
                        .extend(new NotificationCompat.WearableExtender().addAction(action))
                        .setCategory(NotificationCompat.CATEGORY_MESSAGE);

        if (chat == null && user != null && user.phone != null && user.phone.length() > 0) {
            builder.addPerson("tel:+" + user.phone);
        }

        notificationManager.notify(notificationId, builder.build());
        wearNoticationsIds.put(dialog_id, notificationId);
    }

    for (HashMap.Entry<Long, Integer> entry : oldIds.entrySet()) {
        notificationManager.cancel(entry.getValue());
    }
}

From source file:com.delexus.imitationzhihu.MySearchView.java

/**
 * Create and return an Intent that can launch the voice search activity, perform a specific
 * voice transcription, and forward the results to the searchable activity.
 *
 * @param baseIntent The voice app search intent to start from
 * @return A completely-configured intent ready to send to the voice search activity
 *///from   w  ww  .  ja v  a 2 s .  c o  m
private Intent createVoiceAppSearchIntent(Intent baseIntent, SearchableInfo searchable) {
    ComponentName searchActivity = searchable.getSearchActivity();

    // create the necessary intent to set up a search-and-forward operation
    // in the voice search system.   We have to keep the bundle separate,
    // because it becomes immutable once it enters the PendingIntent
    Intent queryIntent = new Intent(Intent.ACTION_SEARCH);
    queryIntent.setComponent(searchActivity);
    PendingIntent pending = PendingIntent.getActivity(getContext(), 0, queryIntent,
            PendingIntent.FLAG_ONE_SHOT);

    // Now set up the bundle that will be inserted into the pending intent
    // when it's time to do the search.  We always build it here (even if empty)
    // because the voice search activity will always need to insert "QUERY" into
    // it anyway.
    Bundle queryExtras = new Bundle();
    if (mAppSearchData != null) {
        queryExtras.putParcelable(SearchManager.APP_DATA, mAppSearchData);
    }

    // Now build the intent to launch the voice search.  Add all necessary
    // extras to launch the voice recognizer, and then all the necessary extras
    // to forward the results to the searchable activity
    Intent voiceIntent = new Intent(baseIntent);

    // Add all of the configuration options supplied by the searchable's metadata
    String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM;
    String prompt = null;
    String language = null;
    int maxResults = 1;

    Resources resources = getResources();
    if (searchable.getVoiceLanguageModeId() != 0) {
        languageModel = resources.getString(searchable.getVoiceLanguageModeId());
    }
    if (searchable.getVoicePromptTextId() != 0) {
        prompt = resources.getString(searchable.getVoicePromptTextId());
    }
    if (searchable.getVoiceLanguageId() != 0) {
        language = resources.getString(searchable.getVoiceLanguageId());
    }
    if (searchable.getVoiceMaxResults() != 0) {
        maxResults = searchable.getVoiceMaxResults();
    }

    voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel);
    voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
    voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
    voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults);
    voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
            searchActivity == null ? null : searchActivity.flattenToShortString());

    // Add the values that configure forwarding the results
    voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending);
    voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras);

    return voiceIntent;
}

From source file:com.b44t.messenger.NotificationsController.java

private void showOrUpdateNotification(boolean notifyAboutLast) {
    if (pushMessages.isEmpty()) {
        dismissNotification();// w  w w .j av a  2  s.c o  m
        return;
    }

    try {
        ConnectionsManager.getInstance().resumeNetworkMaybe();

        MessageObject lastMessageObject = pushMessages.get(0);
        SharedPreferences preferences = ApplicationLoader.applicationContext
                .getSharedPreferences("Notifications", Context.MODE_PRIVATE);
        int dismissDate = preferences.getInt("dismissDate", 0);
        if (lastMessageObject.messageOwner.date <= dismissDate) {
            dismissNotification();
            return;
        }

        final long dialog_id = lastMessageObject.getDialogId();

        //int mid = lastMessageObject.getId();
        final int user_id = lastMessageObject.messageOwner.from_id;

        //TLRPC.User user = MessagesController.getInstance().getUser(user_id);

        MrChat mrChat = MrMailbox.getChat((int) dialog_id);
        boolean isGroupChat = mrChat.getType() == MrChat.MR_CHAT_GROUP;

        //TLRPC.FileLocation photoPath = null;

        boolean notifyDisabled = false;
        int needVibrate = 0;
        String choosenSoundPath = null;
        int ledColor = 0xff00ff00;
        boolean inAppSounds;
        boolean inAppVibrate;
        //boolean inAppPreview = false;
        int priority = 0;
        int priorityOverride;
        int vibrateOverride;

        int notifyOverride = getNotifyOverride(preferences, dialog_id);
        if (!notifyAboutLast || notifyOverride == 2
                || (!preferences.getBoolean("EnableAll", true)
                        || isGroupChat && !preferences.getBoolean("EnableGroup", true))
                        && notifyOverride == 0) {
            notifyDisabled = true;
        }

        if (!notifyDisabled && isGroupChat) {
            int notifyMaxCount = preferences.getInt("smart_max_count_" + dialog_id, 0);
            int notifyDelay = preferences.getInt("smart_delay_" + dialog_id, 3 * 60);
            if (notifyMaxCount != 0) {
                Point dialogInfo = smartNotificationsDialogs.get(dialog_id);
                if (dialogInfo == null) {
                    dialogInfo = new Point(1, (int) (System.currentTimeMillis() / 1000));
                    smartNotificationsDialogs.put(dialog_id, dialogInfo);
                } else {
                    int lastTime = dialogInfo.y;
                    if (lastTime + notifyDelay < System.currentTimeMillis() / 1000) {
                        dialogInfo.set(1, (int) (System.currentTimeMillis() / 1000));
                    } else {
                        int count = dialogInfo.x;
                        if (count < notifyMaxCount) {
                            dialogInfo.set(count + 1, (int) (System.currentTimeMillis() / 1000));
                        } else {
                            notifyDisabled = true;
                        }
                    }
                }
            }
        }

        String defaultPath = Settings.System.DEFAULT_NOTIFICATION_URI.getPath();
        if (!notifyDisabled) {
            inAppSounds = preferences.getBoolean("EnableInAppSounds", true);
            inAppVibrate = preferences.getBoolean("EnableInAppVibrate", true);
            vibrateOverride = preferences.getInt("vibrate_" + dialog_id, 0);
            priorityOverride = preferences.getInt("priority_" + dialog_id, 3);
            boolean vibrateOnlyIfSilent = false;

            choosenSoundPath = preferences.getString("sound_path_" + dialog_id, null);
            if (isGroupChat) {
                if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) {
                    choosenSoundPath = null;
                } else if (choosenSoundPath == null) {
                    choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath);
                }
                needVibrate = preferences.getInt("vibrate_group", 0);
                priority = preferences.getInt("priority_group", 1);
                ledColor = preferences.getInt("GroupLed", 0xff00ff00);
            } else {
                if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) {
                    choosenSoundPath = null;
                } else if (choosenSoundPath == null) {
                    choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath);
                }
                needVibrate = preferences.getInt("vibrate_messages", 0);
                priority = preferences.getInt("priority_messages", 1);
                ledColor = preferences.getInt("MessagesLed", 0xff00ff00);
            }
            if (preferences.contains("color_" + dialog_id)) {
                ledColor = preferences.getInt("color_" + dialog_id, 0);
            }

            if (priorityOverride != 3) {
                priority = priorityOverride;
            }

            if (needVibrate == 4) {
                vibrateOnlyIfSilent = true;
                needVibrate = 0;
            }
            if (needVibrate == 2 && (vibrateOverride == 1 || vibrateOverride == 3 || vibrateOverride == 5)
                    || needVibrate != 2 && vibrateOverride == 2 || vibrateOverride != 0) {
                needVibrate = vibrateOverride;
            }
            if (!ApplicationLoader.mainInterfacePaused) {
                if (!inAppSounds) {
                    choosenSoundPath = null;
                }
                if (!inAppVibrate) {
                    needVibrate = 2;
                }
                priority = preferences.getInt("priority_inapp", 0);
            }
            if (vibrateOnlyIfSilent && needVibrate != 2) {
                try {
                    int mode = audioManager.getRingerMode();
                    if (mode != AudioManager.RINGER_MODE_SILENT && mode != AudioManager.RINGER_MODE_VIBRATE) {
                        needVibrate = 2;
                    }
                } catch (Exception e) {
                    FileLog.e("messenger", e);
                }
            }
        }

        Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent.setAction("com.b44t.messenger.openchat" + (pushDialogs.size() == 1 ? dialog_id : 0));
        intent.setFlags(32768);
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        boolean showPreview = preferences.getBoolean("EnablePreviewAll", true);
        if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
            showPreview = false;
        }

        String name;
        if (pushDialogs.size() > 1 || !showPreview) {
            name = mContext.getString(R.string.AppName);
        } else {
            if (isGroupChat) {
                name = mrChat.getName();
            } else {
                name = MrMailbox.getContact(user_id).getDisplayName();
            }
        }

        String detailText;
        if (pushDialogs.size() == 1) {
            detailText = mContext.getResources().getQuantityString(R.plurals.NewMessages, total_unread_count,
                    total_unread_count);
        } else {
            String newMessages = mContext.getResources().getQuantityString(R.plurals.NewMessages,
                    total_unread_count, total_unread_count);
            detailText = mContext.getResources().getQuantityString(R.plurals.NewMessagesInChats,
                    pushDialogs.size(), newMessages, pushDialogs.size());
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                ApplicationLoader.applicationContext).setContentTitle(name)
                        .setSmallIcon(R.drawable.notification).setAutoCancel(true).setNumber(total_unread_count)
                        .setContentIntent(contentIntent).setGroup("messages").setGroupSummary(true)
                        .setColor(Theme.ACTION_BAR_COLOR);

        mBuilder.setCategory(NotificationCompat.CATEGORY_MESSAGE);

        int silent = 2;
        String lastMessage = null;
        boolean hasNewMessages = false;
        if (!showPreview) {
            mBuilder.setContentText(detailText);
            lastMessage = detailText;
        } else if (pushMessages.size() == 1) {
            MessageObject messageObject = pushMessages.get(0);
            String message = lastMessage = getStringForMessage(messageObject, isGroupChat ? ADD_USER : 0);
            silent = messageObject.messageOwner.silent ? 1 : 0;
            if (message == null) {
                return;
            }

            mBuilder.setContentText(message);
            mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
        } else {
            mBuilder.setContentText(detailText);
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            inboxStyle.setBigContentTitle(name);
            int count = Math.min(10, pushMessages.size());

            int string_flags = 0;
            if (pushDialogs.size() > 1) {
                string_flags |= ADD_GROUP;
            }
            for (int i = 1/*user_id is #0*/; i < pushMessages.size(); i++) {
                MessageObject messageObject = pushMessages.get(i);
                if (messageObject.messageOwner.from_id != user_id) {
                    string_flags |= ADD_USER;
                    break;
                }
            }

            for (int i = 0; i < count; i++) {
                MessageObject messageObject = pushMessages.get(i);
                String message = getStringForMessage(messageObject, string_flags);
                if (message == null || messageObject.messageOwner.date <= dismissDate) {
                    continue;
                }
                if (silent == 2) {
                    lastMessage = message;
                    silent = messageObject.messageOwner.silent ? 1 : 0;
                }
                /*if (pushDialogs.size() == 1) {
                if (replace) {
                    if (chat != null) {
                        message = message.replace(" @ " + name, "");
                    } else {
                        message = message.replace(name + ": ", "").replace(name + " ", "");
                    }
                }
                }*/
                inboxStyle.addLine(message);
            }
            inboxStyle.setSummaryText(detailText);
            mBuilder.setStyle(inboxStyle);
        }

        Intent dismissIntent = new Intent(ApplicationLoader.applicationContext,
                NotificationDismissReceiver.class);
        dismissIntent.putExtra("messageDate", lastMessageObject.messageOwner.date);
        mBuilder.setDeleteIntent(PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 1,
                dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT));

        /*if (photoPath != null) {
        BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(photoPath, null, "50_50");
        if (img != null) {
            mBuilder.setLargeIcon(img.getBitmap());
        } else {
            try {
                float scaleFactor = 160.0f / AndroidUtilities.dp(50);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = scaleFactor < 1 ? 1 : (int) scaleFactor;
                Bitmap bitmap = BitmapFactory.decodeFile(FileLoader.getPathToAttach(photoPath, true).toString(), options);
                if (bitmap != null) {
                    mBuilder.setLargeIcon(bitmap);
                }
            } catch (Throwable e) {
                //ignore
            }
        }
        }*/

        if (!notifyAboutLast || silent == 1) {
            mBuilder.setPriority(NotificationCompat.PRIORITY_LOW);
        } else {
            if (priority == 0) {
                mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
            } else if (priority == 1) {
                mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
            } else if (priority == 2) {
                mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
            }
        }

        if (silent != 1 && !notifyDisabled) {
            /*if (ApplicationLoader.mainInterfacePaused || inAppPreview)*/ {
                if (lastMessage.length() > 100) {
                    lastMessage = lastMessage.substring(0, 100).replace('\n', ' ').trim() + "...";
                }
                mBuilder.setTicker(lastMessage);
            }
            if (!MediaController.getInstance().isRecordingAudio()) {
                if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) {
                    if (choosenSoundPath.equals(defaultPath)) {
                        mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI,
                                AudioManager.STREAM_NOTIFICATION);
                    } else {
                        mBuilder.setSound(Uri.parse(choosenSoundPath), AudioManager.STREAM_NOTIFICATION);
                    }
                }
            }
            if (ledColor != 0) {
                mBuilder.setLights(ledColor, 1000, 1000);
            }
            if (needVibrate == 2 || MediaController.getInstance().isRecordingAudio()) {
                mBuilder.setVibrate(new long[] { 0, 0 });
            } else if (needVibrate == 1) {
                mBuilder.setVibrate(new long[] { 0, 100, 0, 100 });
            } else if (needVibrate == 0 || needVibrate == 4) {
                mBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE);
            } else if (needVibrate == 3) {
                mBuilder.setVibrate(new long[] { 0, 1000 });
            }
        } else {
            mBuilder.setVibrate(new long[] { 0, 0 });
        }

        //showExtraNotifications(mBuilder, notifyAboutLast);
        notificationManager.notify(1, mBuilder.build());

        scheduleNotificationRepeat();

        if (preferences.getBoolean("badgeNumber", true)) {
            setBadge(total_unread_count);
        }

    } catch (Exception e) {
        FileLog.e("messenger", e);
    }

}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Creates a system notification./*from  w w w  .  ja  va2  s  . c  o  m*/
 *    
 * @param context            Context.
 * @param notSound            Enable or disable the sound
 * @param notSoundRawId         Custom raw sound id. If enabled and not set 
 *                         default notification sound will be used. Set to -1 to 
 *                         default system notification.
 * @param multipleNot         Setting to True allows showing multiple notifications.
 * @param groupMultipleNotKey   If is set, multiple notifications can be grupped by this key.
 * @param notAction            Action for this notification
 * @param notTitle            Title
 * @param notMessage         Message
 * @param notClazz            Class to be executed
 * @param extras            Extra information
 * 
 */
public static void notification_generate(Context context, boolean notSound, int notSoundRawId,
        boolean multipleNot, String groupMultipleNotKey, String notAction, String notTitle, String notMessage,
        Class<?> notClazz, Bundle extras, boolean wakeUp) {

    try {
        int iconResId = notification_getApplicationIcon(context);
        long when = System.currentTimeMillis();

        Notification notification = new Notification(iconResId, notMessage, when);

        // Hide the notification after its selected
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        if (notSound) {
            if (notSoundRawId > 0) {
                try {
                    notification.sound = Uri.parse("android.resource://"
                            + context.getApplicationContext().getPackageName() + "/" + notSoundRawId);
                } catch (Exception e) {
                    if (LOG_ENABLE) {
                        Log.w(TAG, "Custom sound " + notSoundRawId + "could not be found. Using default.");
                    }
                    notification.defaults |= Notification.DEFAULT_SOUND;
                    notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                }
            } else {
                notification.defaults |= Notification.DEFAULT_SOUND;
                notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            }
        }

        Intent notificationIntent = new Intent(context, notClazz);
        notificationIntent.setAction(notClazz.getName() + "." + notAction);
        if (extras != null) {
            notificationIntent.putExtras(extras);
        }

        //Set intent so it does not start a new activity
        //
        //Notes:
        //   - The flag FLAG_ACTIVITY_SINGLE_TOP makes that only one instance of the activity exists(each time the
        //      activity is summoned no onCreate() method is called instead, onNewIntent() is called.
        //  - If we use FLAG_ACTIVITY_CLEAR_TOP it will make that the last "snapshot"/TOP of the activity it will 
        //     be this called this intent. We do not want this because the HOME button will call this "snapshot". 
        //     To avoid this behaviour we use FLAG_ACTIVITY_BROUGHT_TO_FRONT that simply takes to foreground the 
        //     activity.
        //
        //See http://developer.android.com/reference/android/content/Intent.html           
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        int REQUEST_UNIQUE_ID = 0;
        if (multipleNot) {
            if (groupMultipleNotKey != null && groupMultipleNotKey.length() > 0) {
                REQUEST_UNIQUE_ID = groupMultipleNotKey.hashCode();
            } else {
                if (random == null) {
                    random = new Random();
                }
                REQUEST_UNIQUE_ID = random.nextInt();
            }
            PendingIntent.getActivity(context, REQUEST_UNIQUE_ID, notificationIntent,
                    PendingIntent.FLAG_ONE_SHOT);
        }

        notification.setLatestEventInfo(context, notTitle, notMessage, intent);

        //This makes the device to wake-up is is idle with the screen off.
        if (wakeUp) {
            powersaving_wakeUp(context);
        }

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        //We check if the sound is disabled to enable just for a moment
        AudioManager amanager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int previousAudioMode = amanager.getRingerMode();
        ;
        if (notSound && previousAudioMode != AudioManager.RINGER_MODE_NORMAL) {
            amanager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }

        notificationManager.notify(REQUEST_UNIQUE_ID, notification);

        //We restore the sound setting
        if (previousAudioMode != AudioManager.RINGER_MODE_NORMAL) {
            //We wait a little so sound is played
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
            }
        }
        amanager.setRingerMode(previousAudioMode);

        Log.d(TAG, "Android Notification created.");

    } catch (Exception e) {
        if (LOG_ENABLE)
            Log.e(TAG, "The notification could not be created (" + e.getMessage() + ")", e);
    }
}

From source file:com.paywith.ibeacon.service.IBeaconService.java

protected void generateNotification(String title, String merchanttext, String murl, String location_id) {

    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

    Builder mNotifyBuilder = new NotificationCompat.Builder(this);

    //int icon = R.drawable.ic_launcher;
    //CharSequence tickerText = "PayWith";
    //long when = System.currentTimeMillis();

    //@SuppressWarnings("deprecation")
    //Notification notification = new Notification(icon,
    //        tickerText, when);

    mNotifyBuilder.setContentText(merchanttext).setContentTitle(title).setSmallIcon(R.drawable.ic_launcher);//logo

    //notification.flags |= Notification.FLAG_AUTO_CANCEL;
    Context context = getApplicationContext();
    Intent notificationIntent = new Intent("android.intent.category.LAUNCHER");
    //CharSequence contentTitle = title;
    //CharSequence contentText = merchanttext;

    notificationIntent.putExtra("OpenUrl", murl);
    notificationIntent.putExtra("MerchantName", merchanttext);
    notificationIntent.setClassName("com.paywith.paywith", "com.paywith.paywith.MainActivity");

    //PendingIntent contentIntent = PendingIntent
    //         .getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

    //notification.setLatestEventInfo(context, contentTitle,
    //        contentText, contentIntent);

    //mNotificationManager.notify(ongoing_notification_id, notification);

    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
    // PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT

    // this gives us flexibility to add vibration and sound etc:
    Notification note = mNotifyBuilder.build();

    // THIS line is what makes the notification tappable to launch app and generate mCard payment:
    note.setLatestEventInfo(context, title, merchanttext, contentIntent);

    // make phone vibrate and make sound on notification:
    note.defaults |= Notification.DEFAULT_VIBRATE;
    note.defaults |= Notification.DEFAULT_SOUND;

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    //Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP

    note.flags |= Notification.FLAG_AUTO_CANCEL;
    // Because the ID remains unchanged, the existing notification is updated.
    mNotificationManager.notify(ongoing_notification_id, note);
    //Log.e("notification","sent");
}

From source file:com.apptentive.android.sdk.ApptentiveInternal.java

public static PendingIntent prepareMessageCenterPendingIntent(Context context) {
    Intent intent;//  w ww  .  ja v a  2  s . c o  m
    if (Apptentive.canShowMessageCenter()) {
        intent = new Intent();
        intent.setClass(context, ApptentiveViewActivity.class);
        intent.putExtra(Constants.FragmentConfigKeys.TYPE, Constants.FragmentTypes.ENGAGE_INTERNAL_EVENT);
        intent.putExtra(Constants.FragmentConfigKeys.EXTRA,
                MessageCenterInteraction.DEFAULT_INTERNAL_EVENT_NAME);
    } else {
        intent = MessageCenterInteraction.generateMessageCenterErrorIntent(context);
    }
    return (intent != null)
            ? PendingIntent.getActivity(context, 0, intent,
                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT)
            : null;
}