Example usage for android.media AudioManager STREAM_NOTIFICATION

List of usage examples for android.media AudioManager STREAM_NOTIFICATION

Introduction

In this page you can find the example usage for android.media AudioManager STREAM_NOTIFICATION.

Prototype

int STREAM_NOTIFICATION

To view the source code for android.media AudioManager STREAM_NOTIFICATION.

Click Source Link

Document

Used to identify the volume of audio streams for notifications

Usage

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * handle the receipt of suggestions from the spell checker
 * colour the text in the editor as required
 * pass information to the keyboard view so it can draw the colour bar
 * initiate audio and haptic feedback as required
 *///from   w  ww.j  a  va2s .co m
@Override
public void onGetSuggestions(SuggestionsInfo[] results) {
    // TODO Auto-generated method stub
    int colortype = -1;
    final StringBuilder sb = new StringBuilder();

    if (updateSuggestionList) {
        updateSuggestionList = false;
        ArrayList<String> s = new ArrayList<String>();
        for (int i = 0; i < results.length; ++i) {
            final int length = results[i].getSuggestionsCount();
            for (int j = 0; j < length; ++j) {
                s.add(results[i].getSuggestionAt(j));
            }
        }
        updateSuggestionListWithSpellChecker(s);
    } else {

        for (int i = 0; i < results.length; ++i) {
            // Returned suggestions are contained in SuggestionsInfo

            final int len = results[i].getSuggestionsCount();
            sb.append("Suggestion Attribs: " + results[i].getSuggestionsAttributes());
            if ((results[i].getSuggestionsAttributes()
                    & SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY) == SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY) {
                sb.append("The word was found in the dictionary\n");
                mInputView.wordcompletedtype = 3;
            } else {

                if ((results[i].getSuggestionsAttributes()
                        & SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO) == SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO) {
                    if ((results[i].getSuggestionsAttributes()
                            & SuggestionsInfo.RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS) == SuggestionsInfo.RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS) {
                        colortype = 1; //yellow
                        mInputView.wordcompletedtype = 1;
                        sb.append("There are strong candidates for this word\n");
                        currentSession.nLowErrors++;
                    } else {
                        colortype = 2; //red
                        mInputView.wordcompletedtype = 2;
                        sb.append("The word looks like a typo\n");
                        currentSession.nHighErrors++;

                    }
                }

            }

            sb.append("\n--These are the suggestions--\n");
            for (int j = 0; j < len; ++j) {
                sb.append("," + results[i].getSuggestionAt(j));
            }
            sb.append(" (" + len + ")");
        }
        //Log.i("Spelling suggestions", sb.toString());

        //this comes after a word separator, hence just add 1 to the cursor
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        SpannableString text = new SpannableString(mComposingTemp);

        if (sharedPrefs.getBoolean("highlightwords", true)) {
            switch (colortype) {
            case 1:
                text.setSpan(new BackgroundColorSpan(small_err), 0, mComposingTemp.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            case 2:
                text.setSpan(new BackgroundColorSpan(big_err), 0, mComposingTemp.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            default:
                break;
            }
        }

        if (sharedPrefs.getBoolean("autocorrect", true) && mInputView.wordcompletedtype == 1) //handle autocorrection
        {
            SpannableString autoc = autocorrect(results);
            autocorrected_words.put(autoc.toString(), text.toString()); //autocorrected word, original input
            //Log.i("Autocorrecting","Key= "+autoc.toString()+", Value= "+text.toString());
            text = autoc;
            if (sharedPrefs.getBoolean("highlightwords", true))
                text.setSpan(new BackgroundColorSpan(autocorrect), 0, text.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            mInputView.wordcompletedtype = 4;
        } else //autocorrection is turned off
        {
            if (!sharedPrefs.getBoolean("autocorrect", true) && colortype >= 1) //a mistake word
            {
                //Log.i("OnGetSentenceSuggestions","Key= "+text.toString()+", Value= "+text.toString());
                //no autocorrects, just put the word in and itself as the replacement
                autocorrected_words.put(text.toString(), text.toString());
            }
        }

        if (sharedPrefs.getBoolean("vibrator", false)) {
            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            final int on_time = Integer.parseInt(sharedPrefs.getString("shortvibe", "35"));

            switch (mInputView.wordcompletedtype) {
            case 1: //small err
                // Vibrate for 300 milliseconds
                v.vibrate(on_time);
                break;
            case 2: //big err
                //v.vibrate(Integer.parseInt(sharedPrefs.getString("longvibe", "300")));
                v.vibrate(new long[] { 0, on_time, 200, on_time }, -1);
                break;
            case 4: //autocorr
                v.vibrate(on_time);
                break;
            default:
                break;

            }
        }

        if (sharedPrefs.getBoolean("audio", false)) {
            final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
            switch (mInputView.wordcompletedtype) {
            case 1: //small err
                tg.startTone(ToneGenerator.TONE_PROP_BEEP);
                break;
            case 2: //big err
                tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
                break;
            case 4: //autocorr
                tg.startTone(ToneGenerator.TONE_PROP_BEEP);
                break;
            default:
                break;

            }
        }

        mInputView.invalidateAllKeys();
        ic.commitText(text, 1);
        sendKey(wordSeparatorKeyCode);
        coreEngine.resetCoreString();
        updateCandidates();
    }

}

From source file:com.panahit.telegramma.NotificationsController.java

private void showOrUpdateNotification(boolean notifyAboutLast) {
    if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) {
        dismissNotification();/*w w  w.j a  va 2  s. c om*/
        return;
    }
    try {
        ConnectionsManager.getInstance().resumeNetworkMaybe();

        MessageObject lastMessageObject = pushMessages.get(0);

        long dialog_id = lastMessageObject.getDialogId();
        long override_dialog_id = dialog_id;
        if (lastMessageObject.messageOwner.mentioned) {
            override_dialog_id = lastMessageObject.messageOwner.from_id;
        }
        int mid = lastMessageObject.getId();
        int chat_id = lastMessageObject.messageOwner.to_id.chat_id != 0
                ? lastMessageObject.messageOwner.to_id.chat_id
                : lastMessageObject.messageOwner.to_id.channel_id;
        int user_id = lastMessageObject.messageOwner.to_id.user_id;
        if (user_id == 0) {
            user_id = lastMessageObject.messageOwner.from_id;
        } else if (user_id == UserConfig.getClientUserId()) {
            user_id = lastMessageObject.messageOwner.from_id;
        }

        TLRPC.User user = MessagesController.getInstance().getUser(user_id);
        TLRPC.Chat chat = null;
        if (chat_id != 0) {
            chat = MessagesController.getInstance().getChat(chat_id);
        }
        TLRPC.FileLocation photoPath = null;

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

        SharedPreferences preferences = ApplicationLoader.applicationContext
                .getSharedPreferences("Notifications", Context.MODE_PRIVATE);
        int notifyOverride = getNotifyOverride(preferences, override_dialog_id);
        if (!notifyAboutLast || notifyOverride == 2
                || (!preferences.getBoolean("EnableAll", true)
                        || chat_id != 0 && !preferences.getBoolean("EnableGroup", true))
                        && notifyOverride == 0) {
            notifyDisabled = true;
        }

        if (!notifyDisabled && dialog_id == override_dialog_id && chat != null) {
            int notifyMaxCount = preferences.getInt("smart_max_count_" + dialog_id, 2);
            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);
            inAppPreview = preferences.getBoolean("EnableInAppPreview", true);
            inAppPriority = preferences.getBoolean("EnableInAppPriority", false);
            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 (chat_id != 0) {
                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 (user_id != 0) {
                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_group", 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;
                }
                if (!inAppPriority) {
                    priority = 0;
                } else if (priority == 2) {
                    priority = 1;
                }
            }
            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("tmessages", e);
                }
            }
        }

        Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
        intent.setFlags(32768);
        if ((int) dialog_id != 0) {
            if (pushDialogs.size() == 1) {
                if (chat_id != 0) {
                    intent.putExtra("chatId", chat_id);
                } else if (user_id != 0) {
                    intent.putExtra("userId", user_id);
                }
            }
            if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
                photoPath = null;
            } else {
                if (pushDialogs.size() == 1) {
                    if (chat != null) {
                        if (chat.photo != null && chat.photo.photo_small != null
                                && chat.photo.photo_small.volume_id != 0
                                && chat.photo.photo_small.local_id != 0) {
                            photoPath = chat.photo.photo_small;
                        }
                    } else if (user != null) {
                        if (user.photo != null && user.photo.photo_small != null
                                && user.photo.photo_small.volume_id != 0
                                && user.photo.photo_small.local_id != 0) {
                            photoPath = user.photo.photo_small;
                        }
                    }
                }
            }
        } else {
            if (pushDialogs.size() == 1) {
                intent.putExtra("encId", (int) (dialog_id >> 32));
            }
        }
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String name;
        boolean replace = true;
        if ((int) dialog_id == 0 || pushDialogs.size() > 1 || AndroidUtilities.needShowPasscode(false)
                || UserConfig.isWaitingForPasscodeEnter) {
            name = LocaleController.getString("AppName", R.string.AppName);
            replace = false;
        } else {
            if (chat != null) {
                name = chat.title;
            } else {
                name = UserObject.getUserName(user);
            }
        }

        String detailText;
        if (pushDialogs.size() == 1) {
            detailText = LocaleController.formatPluralString("NewMessages", total_unread_count);
        } else {
            detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder",
                    R.string.NotificationMessagesPeopleDisplayOrder,
                    LocaleController.formatPluralString("NewMessages", total_unread_count),
                    LocaleController.formatPluralString("FromChats", 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(0xff2ca5e0);

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

        int silent = 2;
        String lastMessage = null;
        if (pushMessages.size() == 1) {
            MessageObject messageObject = pushMessages.get(0);
            String message = lastMessage = getStringForMessage(messageObject, false);
            silent = messageObject.messageOwner.silent ? 1 : 0;
            if (message == null) {
                return;
            }
            if (replace) {
                if (chat != null) {
                    message = message.replace(" @ " + name, "");
                } else {
                    message = message.replace(name + ": ", "").replace(name + " ", "");
                }
            }
            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());
            for (int i = 0; i < count; i++) {
                MessageObject messageObject = pushMessages.get(i);
                String message = getStringForMessage(messageObject, false);
                if (message == null) {
                    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);
        }

        if (photoPath != null) {
            BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(photoPath, null, "50_50");
            if (img != null) {
                mBuilder.setLargeIcon(img.getBitmap());
            }
        }

        if (silent == 1) {
            FileLog.e("tmessages", "don't notify " + lastMessage);
        } else {
            FileLog.e("tmessages", "notify" + lastMessage);
        }

        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();
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:org.cafemember.messenger.NotificationsController.java

private void showOrUpdateNotification(boolean notifyAboutLast) {
    if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) {
        dismissNotification();/*  ww w  . j  ava 2s  . c  o m*/
        return;
    }
    try {
        ConnectionsManager.getInstance().resumeNetworkMaybe();

        MessageObject lastMessageObject = pushMessages.get(0);

        long dialog_id = lastMessageObject.getDialogId();
        long override_dialog_id = dialog_id;
        if (lastMessageObject.messageOwner.mentioned) {
            override_dialog_id = lastMessageObject.messageOwner.from_id;
        }
        int mid = lastMessageObject.getId();
        int chat_id = lastMessageObject.messageOwner.to_id.chat_id != 0
                ? lastMessageObject.messageOwner.to_id.chat_id
                : lastMessageObject.messageOwner.to_id.channel_id;
        int user_id = lastMessageObject.messageOwner.to_id.user_id;
        if (user_id == 0) {
            user_id = lastMessageObject.messageOwner.from_id;
        } else if (user_id == UserConfig.getClientUserId()) {
            user_id = lastMessageObject.messageOwner.from_id;
        }

        TLRPC.User user = MessagesController.getInstance().getUser(user_id);
        TLRPC.Chat chat = null;
        if (chat_id != 0) {
            chat = MessagesController.getInstance().getChat(chat_id);
        }
        TLRPC.FileLocation photoPath = null;

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

        SharedPreferences preferences = ApplicationLoader.applicationContext
                .getSharedPreferences("Notifications", Context.MODE_PRIVATE);
        int notifyOverride = getNotifyOverride(preferences, override_dialog_id);
        if (!notifyAboutLast || notifyOverride == 2
                || (!preferences.getBoolean("EnableAll", true)
                        || chat_id != 0 && !preferences.getBoolean("EnableGroup", true))
                        && notifyOverride == 0) {
            notifyDisabled = true;
        }

        if (!notifyDisabled && dialog_id == override_dialog_id && chat != null) {
            int notifyMaxCount = preferences.getInt("smart_max_count_" + dialog_id, 2);
            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);
            inAppPreview = preferences.getBoolean("EnableInAppPreview", true);
            inAppPriority = preferences.getBoolean("EnableInAppPriority", false);
            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 (chat_id != 0) {
                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 (user_id != 0) {
                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_group", 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;
                }
                if (!inAppPriority) {
                    priority = 0;
                } else if (priority == 2) {
                    priority = 1;
                }
            }
            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("tmessages", e);
                }
            }
        }

        Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
        intent.setFlags(32768);
        if ((int) dialog_id != 0) {
            if (pushDialogs.size() == 1) {
                if (chat_id != 0) {
                    intent.putExtra("chatId", chat_id);
                } else if (user_id != 0) {
                    intent.putExtra("userId", user_id);
                }
            }
            if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
                photoPath = null;
            } else {
                if (pushDialogs.size() == 1) {
                    if (chat != null) {
                        if (chat.photo != null && chat.photo.photo_small != null
                                && chat.photo.photo_small.volume_id != 0
                                && chat.photo.photo_small.local_id != 0) {
                            photoPath = chat.photo.photo_small;
                        }
                    } else if (user != null) {
                        if (user.photo != null && user.photo.photo_small != null
                                && user.photo.photo_small.volume_id != 0
                                && user.photo.photo_small.local_id != 0) {
                            photoPath = user.photo.photo_small;
                        }
                    }
                }
            }
        } else {
            if (pushDialogs.size() == 1) {
                intent.putExtra("encId", (int) (dialog_id >> 32));
            }
        }
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String name;
        boolean replace = true;
        if ((int) dialog_id == 0 || pushDialogs.size() > 1 || AndroidUtilities.needShowPasscode(false)
                || UserConfig.isWaitingForPasscodeEnter) {
            name = LocaleController.getString("AppName", R.string.AppName);
            replace = false;
        } else {
            if (chat != null) {
                name = chat.title;
            } else {
                name = UserObject.getUserName(user);
            }
        }

        String detailText;
        if (pushDialogs.size() == 1) {
            detailText = LocaleController.formatPluralString("NewMessages", total_unread_count);
        } else {
            detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder",
                    R.string.NotificationMessagesPeopleDisplayOrder,
                    LocaleController.formatPluralString("NewMessages", total_unread_count),
                    LocaleController.formatPluralString("FromChats", 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(0xff2ca5e0);

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

        int silent = 2;
        String lastMessage = null;
        if (pushMessages.size() == 1) {
            MessageObject messageObject = pushMessages.get(0);
            String message = lastMessage = getStringForMessage(messageObject, false);
            silent = messageObject.messageOwner.silent ? 1 : 0;
            if (message == null) {
                return;
            }
            if (replace) {
                if (chat != null) {
                    message = message.replace(" @ " + name, "");
                } else {
                    message = message.replace(name + ": ", "").replace(name + " ", "");
                }
            }
            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());
            for (int i = 0; i < count; i++) {
                MessageObject messageObject = pushMessages.get(i);
                String message = getStringForMessage(messageObject, false);
                if (message == null) {
                    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);
        }

        if (photoPath != null) {
            BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(photoPath, null, "50_50");
            if (img != null) {
                mBuilder.setLargeIcon(img.getBitmap());
            }
        }

        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();
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:org.giffftalk.messenger.NotificationsController.java

private void showOrUpdateNotification(boolean notifyAboutLast) {
    if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) {
        dismissNotification();/*from  ww w  .  j  ava  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;
        }

        long dialog_id = lastMessageObject.getDialogId();
        long override_dialog_id = dialog_id;
        if (lastMessageObject.messageOwner.mentioned) {
            override_dialog_id = lastMessageObject.messageOwner.from_id;
        }
        int mid = lastMessageObject.getId();
        int chat_id = lastMessageObject.messageOwner.to_id.chat_id != 0
                ? lastMessageObject.messageOwner.to_id.chat_id
                : lastMessageObject.messageOwner.to_id.channel_id;
        int user_id = lastMessageObject.messageOwner.to_id.user_id;
        if (user_id == 0) {
            user_id = lastMessageObject.messageOwner.from_id;
        } else if (user_id == UserConfig.getClientUserId()) {
            user_id = lastMessageObject.messageOwner.from_id;
        }

        TLRPC.User user = MessagesController.getInstance().getUser(user_id);
        TLRPC.Chat chat = null;
        if (chat_id != 0) {
            chat = MessagesController.getInstance().getChat(chat_id);
        }
        TLRPC.FileLocation photoPath = null;

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

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

        if (!notifyDisabled && dialog_id == override_dialog_id && chat != null) {
            int notifyMaxCount = preferences.getInt("smart_max_count_" + dialog_id, 2);
            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);
            inAppPreview = preferences.getBoolean("EnableInAppPreview", true);
            inAppPriority = preferences.getBoolean("EnableInAppPriority", false);
            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 (chat_id != 0) {
                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 (user_id != 0) {
                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_group", 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;
                }
                if (!inAppPriority) {
                    priority = 0;
                } else if (priority == 2) {
                    priority = 1;
                }
            }
            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("tmessages", e);
                }
            }
        }

        Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
        intent.setFlags(32768);
        if ((int) dialog_id != 0) {
            if (pushDialogs.size() == 1) {
                if (chat_id != 0) {
                    intent.putExtra("chatId", chat_id);
                } else if (user_id != 0) {
                    intent.putExtra("userId", user_id);
                }
            }
            if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
                photoPath = null;
            } else {
                if (pushDialogs.size() == 1) {
                    if (chat != null) {
                        if (chat.photo != null && chat.photo.photo_small != null
                                && chat.photo.photo_small.volume_id != 0
                                && chat.photo.photo_small.local_id != 0) {
                            photoPath = chat.photo.photo_small;
                        }
                    } else if (user != null) {
                        if (user.photo != null && user.photo.photo_small != null
                                && user.photo.photo_small.volume_id != 0
                                && user.photo.photo_small.local_id != 0) {
                            photoPath = user.photo.photo_small;
                        }
                    }
                }
            }
        } else {
            if (pushDialogs.size() == 1) {
                intent.putExtra("encId", (int) (dialog_id >> 32));
            }
        }
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String name;
        boolean replace = true;
        if ((int) dialog_id == 0 || pushDialogs.size() > 1 || AndroidUtilities.needShowPasscode(false)
                || UserConfig.isWaitingForPasscodeEnter) {
            name = LocaleController.getString("AppName", R.string.AppName);
            replace = false;
        } else {
            if (chat != null) {
                name = chat.title;
            } else {
                name = UserObject.getUserName(user);
            }
        }

        String detailText;
        if (pushDialogs.size() == 1) {
            detailText = LocaleController.formatPluralString("NewMessages", total_unread_count);
        } else {
            detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder",
                    R.string.NotificationMessagesPeopleDisplayOrder,
                    LocaleController.formatPluralString("NewMessages", total_unread_count),
                    LocaleController.formatPluralString("FromChats", 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)
                        // Customized by Digant .setColor(0xff2ca5e0)
                        .setColor(Theme.PRIMARY_COLOR);

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

        int silent = 2;
        String lastMessage = null;
        boolean hasNewMessages = false;
        if (pushMessages.size() == 1) {
            MessageObject messageObject = pushMessages.get(0);
            String message = lastMessage = getStringForMessage(messageObject, false);
            silent = messageObject.messageOwner.silent ? 1 : 0;
            if (message == null) {
                return;
            }
            if (replace) {
                if (chat != null) {
                    message = message.replace(" @ " + name, "");
                } else {
                    message = message.replace(name + ": ", "").replace(name + " ", "");
                }
            }
            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());
            for (int i = 0; i < count; i++) {
                MessageObject messageObject = pushMessages.get(i);
                String message = getStringForMessage(messageObject, false);
                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();
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:ir.irani.telecam.messenger.NotificationsController.java

private void showOrUpdateNotification(boolean notifyAboutLast) {
    if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) {
        dismissNotification();/*ww w .j a v  a  2s . c om*/
        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;
        }

        long dialog_id = lastMessageObject.getDialogId();
        long override_dialog_id = dialog_id;
        if (lastMessageObject.messageOwner.mentioned) {
            override_dialog_id = lastMessageObject.messageOwner.from_id;
        }
        int mid = lastMessageObject.getId();
        int chat_id = lastMessageObject.messageOwner.to_id.chat_id != 0
                ? lastMessageObject.messageOwner.to_id.chat_id
                : lastMessageObject.messageOwner.to_id.channel_id;
        int user_id = lastMessageObject.messageOwner.to_id.user_id;
        if (user_id == 0) {
            user_id = lastMessageObject.messageOwner.from_id;
        } else if (user_id == UserConfig.getClientUserId()) {
            user_id = lastMessageObject.messageOwner.from_id;
        }

        TLRPC.User user = MessagesController.getInstance().getUser(user_id);
        TLRPC.Chat chat = null;
        if (chat_id != 0) {
            chat = MessagesController.getInstance().getChat(chat_id);
        }
        TLRPC.FileLocation photoPath = null;

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

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

        if (!notifyDisabled && dialog_id == override_dialog_id && chat != null) {
            int notifyMaxCount = preferences.getInt("smart_max_count_" + dialog_id, 2);
            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);
            inAppPreview = preferences.getBoolean("EnableInAppPreview", true);
            inAppPriority = preferences.getBoolean("EnableInAppPriority", false);
            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 (chat_id != 0) {
                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 (user_id != 0) {
                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_group", 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;
                }
                if (!inAppPriority) {
                    priority = 0;
                } else if (priority == 2) {
                    priority = 1;
                }
            }
            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("tmessages", e);
                }
            }
        }

        Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
        intent.setFlags(32768);
        if ((int) dialog_id != 0) {
            if (pushDialogs.size() == 1) {
                if (chat_id != 0) {
                    intent.putExtra("chatId", chat_id);
                } else if (user_id != 0) {
                    intent.putExtra("userId", user_id);
                }
            }
            if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
                photoPath = null;
            } else {
                if (pushDialogs.size() == 1) {
                    if (chat != null) {
                        if (chat.photo != null && chat.photo.photo_small != null
                                && chat.photo.photo_small.volume_id != 0
                                && chat.photo.photo_small.local_id != 0) {
                            photoPath = chat.photo.photo_small;
                        }
                    } else if (user != null) {
                        if (user.photo != null && user.photo.photo_small != null
                                && user.photo.photo_small.volume_id != 0
                                && user.photo.photo_small.local_id != 0) {
                            photoPath = user.photo.photo_small;
                        }
                    }
                }
            }
        } else {
            if (pushDialogs.size() == 1) {
                intent.putExtra("encId", (int) (dialog_id >> 32));
            }
        }
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String name;
        boolean replace = true;
        if ((int) dialog_id == 0 || pushDialogs.size() > 1 || AndroidUtilities.needShowPasscode(false)
                || UserConfig.isWaitingForPasscodeEnter) {
            name = LocaleController.getString("AppName", R.string.AppName);
            replace = false;
        } else {
            if (chat != null) {
                name = chat.title;
            } else {
                name = UserObject.getUserName(user);
            }
        }

        String detailText;
        if (pushDialogs.size() == 1) {
            detailText = LocaleController.formatPluralString("NewMessages", total_unread_count);
        } else {
            detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder",
                    R.string.NotificationMessagesPeopleDisplayOrder,
                    LocaleController.formatPluralString("NewMessages", total_unread_count),
                    LocaleController.formatPluralString("FromChats", 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(0xff2ca5e0);

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

        int silent = 2;
        String lastMessage = null;
        boolean hasNewMessages = false;
        if (pushMessages.size() == 1) {
            MessageObject messageObject = pushMessages.get(0);
            String message = lastMessage = getStringForMessage(messageObject, false);
            silent = messageObject.messageOwner.silent ? 1 : 0;
            if (message == null) {
                return;
            }
            if (replace) {
                if (chat != null) {
                    message = message.replace(" @ " + name, "");
                } else {
                    message = message.replace(name + ": ", "").replace(name + " ", "");
                }
            }
            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());
            for (int i = 0; i < count; i++) {
                MessageObject messageObject = pushMessages.get(i);
                String message = getStringForMessage(messageObject, false);
                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();
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:ir.besteveryeverapp.telegram.NotificationsController.java

private void showOrUpdateNotification(boolean notifyAboutLast) {
    if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) {
        dismissNotification();/*from   w  w w.  j a  v  a 2  s. co  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;
        }

        long dialog_id = lastMessageObject.getDialogId();
        long override_dialog_id = dialog_id;
        if (lastMessageObject.messageOwner.mentioned) {
            override_dialog_id = lastMessageObject.messageOwner.from_id;
        }
        int mid = lastMessageObject.getId();
        int chat_id = lastMessageObject.messageOwner.to_id.chat_id != 0
                ? lastMessageObject.messageOwner.to_id.chat_id
                : lastMessageObject.messageOwner.to_id.channel_id;
        int user_id = lastMessageObject.messageOwner.to_id.user_id;
        if (user_id == 0) {
            user_id = lastMessageObject.messageOwner.from_id;
        } else if (user_id == UserConfig.getClientUserId()) {
            user_id = lastMessageObject.messageOwner.from_id;
        }

        TLRPC.User user = MessagesController.getInstance().getUser(user_id);
        TLRPC.Chat chat = null;
        if (chat_id != 0) {
            chat = MessagesController.getInstance().getChat(chat_id);
        }
        TLRPC.FileLocation photoPath = null;

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

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

        if (!notifyDisabled && dialog_id == override_dialog_id && chat != null) {
            int notifyMaxCount = preferences.getInt("smart_max_count_" + dialog_id, 2);
            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);
            inAppPreview = preferences.getBoolean("EnableInAppPreview", true);
            inAppPriority = preferences.getBoolean("EnableInAppPriority", false);
            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 (chat_id != 0) {
                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 (user_id != 0) {
                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_group", 1);
                ledColor = preferences.getInt("MessagesLed", 0xff00ff00);
                //:ramin
                ledColor = ChitSettings.ledColor(ledColor);
            }
            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;
                }
                if (!inAppPriority) {
                    priority = 0;
                } else if (priority == 2) {
                    priority = 1;
                }
            }
            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("tmessages", e);
                }
            }
        }

        Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
        intent.setFlags(32768);
        if ((int) dialog_id != 0) {
            if (pushDialogs.size() == 1) {
                if (chat_id != 0) {
                    intent.putExtra("chatId", chat_id);
                } else if (user_id != 0) {
                    intent.putExtra("userId", user_id);
                }
            }
            if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
                photoPath = null;
            } else {
                if (pushDialogs.size() == 1) {
                    if (chat != null) {
                        if (chat.photo != null && chat.photo.photo_small != null
                                && chat.photo.photo_small.volume_id != 0
                                && chat.photo.photo_small.local_id != 0) {
                            photoPath = chat.photo.photo_small;
                        }
                    } else if (user != null) {
                        if (user.photo != null && user.photo.photo_small != null
                                && user.photo.photo_small.volume_id != 0
                                && user.photo.photo_small.local_id != 0) {
                            photoPath = user.photo.photo_small;
                        }
                    }
                }
            }
        } else {
            if (pushDialogs.size() == 1) {
                intent.putExtra("encId", (int) (dialog_id >> 32));
            }
        }
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String name;
        boolean replace = true;
        if ((int) dialog_id == 0 || pushDialogs.size() > 1 || AndroidUtilities.needShowPasscode(false)
                || UserConfig.isWaitingForPasscodeEnter) {
            name = LocaleController.getString("AppName", R.string.AppName);
            replace = false;
        } else {
            if (chat != null) {
                name = chat.title;
            } else {
                name = UserObject.getUserName(user);
            }
        }

        String detailText;
        if (pushDialogs.size() == 1) {
            detailText = LocaleController.formatPluralString("NewMessages", total_unread_count);
        } else {
            detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder",
                    R.string.NotificationMessagesPeopleDisplayOrder,
                    LocaleController.formatPluralString("NewMessages", total_unread_count),
                    LocaleController.formatPluralString("FromChats", 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(0xff2ca5e0);

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

        int silent = 2;
        String lastMessage = null;
        boolean hasNewMessages = false;
        if (pushMessages.size() == 1) {
            MessageObject messageObject = pushMessages.get(0);
            String message = lastMessage = getStringForMessage(messageObject, false);
            silent = messageObject.messageOwner.silent ? 1 : 0;
            if (message == null) {
                return;
            }
            if (replace) {
                if (chat != null) {
                    message = message.replace(" @ " + name, "");
                } else {
                    message = message.replace(name + ": ", "").replace(name + " ", "");
                }
            }
            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());
            for (int i = 0; i < count; i++) {
                MessageObject messageObject = pushMessages.get(i);
                String message = getStringForMessage(messageObject, false);
                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")
                        && !NightModeUtil.blockSound()) {
                    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 (!NightModeUtil.blockVibrate()) {
                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();
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:kr.wdream.storyshop.NotificationsController.java

private void showOrUpdateNotification(boolean notifyAboutLast) {
    if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) {
        dismissNotification();//from w  w w  .j a  va  2s.  c om
        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;
        }

        long dialog_id = lastMessageObject.getDialogId();
        long override_dialog_id = dialog_id;
        if (lastMessageObject.messageOwner.mentioned) {
            override_dialog_id = lastMessageObject.messageOwner.from_id;
        }
        int mid = lastMessageObject.getId();
        int chat_id = lastMessageObject.messageOwner.to_id.chat_id != 0
                ? lastMessageObject.messageOwner.to_id.chat_id
                : lastMessageObject.messageOwner.to_id.channel_id;
        int user_id = lastMessageObject.messageOwner.to_id.user_id;
        if (user_id == 0) {
            user_id = lastMessageObject.messageOwner.from_id;
        } else if (user_id == UserConfig.getClientUserId()) {
            user_id = lastMessageObject.messageOwner.from_id;
        }

        TLRPC.User user = MessagesController.getInstance().getUser(user_id);
        TLRPC.Chat chat = null;
        if (chat_id != 0) {
            chat = MessagesController.getInstance().getChat(chat_id);
        }
        TLRPC.FileLocation photoPath = null;

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

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

        if (!notifyDisabled && dialog_id == override_dialog_id && chat != null) {
            int notifyMaxCount = preferences.getInt("smart_max_count_" + dialog_id, 2);
            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);
            inAppPreview = preferences.getBoolean("EnableInAppPreview", true);
            inAppPriority = preferences.getBoolean("EnableInAppPriority", false);
            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 (chat_id != 0) {
                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 (user_id != 0) {
                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_group", 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;
                }
                if (!inAppPriority) {
                    priority = 0;
                } else if (priority == 2) {
                    priority = 1;
                }
            }
            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("tmessages", e);
                }
            }
        }

        Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
        intent.setFlags(32768);
        if ((int) dialog_id != 0) {
            if (pushDialogs.size() == 1) {
                if (chat_id != 0) {
                    intent.putExtra("chatId", chat_id);
                } else if (user_id != 0) {
                    intent.putExtra("userId", user_id);
                }
            }
            if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
                photoPath = null;
            } else {
                if (pushDialogs.size() == 1) {
                    if (chat != null) {
                        if (chat.photo != null && chat.photo.photo_small != null
                                && chat.photo.photo_small.volume_id != 0
                                && chat.photo.photo_small.local_id != 0) {
                            photoPath = chat.photo.photo_small;
                        }
                    } else if (user != null) {
                        if (user.photo != null && user.photo.photo_small != null
                                && user.photo.photo_small.volume_id != 0
                                && user.photo.photo_small.local_id != 0) {
                            photoPath = user.photo.photo_small;
                        }
                    }
                }
            }
        } else {
            if (pushDialogs.size() == 1) {
                intent.putExtra("encId", (int) (dialog_id >> 32));
            }
        }
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String name;
        boolean replace = true;
        if ((int) dialog_id == 0 || pushDialogs.size() > 1 || AndroidUtilities.needShowPasscode(false)
                || UserConfig.isWaitingForPasscodeEnter) {
            name = LocaleController.getString("AppName", R.string.AppName);
            replace = false;
        } else {
            if (chat != null) {
                name = chat.title;
            } else {
                name = UserObject.getUserName(user);
            }
        }

        String detailText;
        if (pushDialogs.size() == 1) {
            detailText = LocaleController.formatPluralString("NewMessages", total_unread_count);
        } else {
            detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder",
                    R.string.NotificationMessagesPeopleDisplayOrder,
                    LocaleController.formatPluralString("NewMessages", total_unread_count),
                    LocaleController.formatPluralString("FromChats", 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(0xff2ca5e0);

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

        int silent = 2;
        String lastMessage = null;
        boolean hasNewMessages = false;
        if (pushMessages.size() == 1) {
            MessageObject messageObject = pushMessages.get(0);
            String message = lastMessage = getStringForMessage(messageObject, false);
            silent = messageObject.messageOwner.silent ? 1 : 0;
            if (message == null) {
                return;
            }
            if (replace) {
                if (chat != null) {
                    message = message.replace(" @ " + name, "");
                } else {
                    message = message.replace(name + ": ", "").replace(name + " ", "");
                }
            }
            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());
            for (int i = 0; i < count; i++) {
                MessageObject messageObject = pushMessages.get(i);
                String message = getStringForMessage(messageObject, false);
                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 });
        }

        if (Build.VERSION.SDK_INT < 24 && UserConfig.passcodeHash.length() == 0 && hasMessagesToReply()) {
            Intent replyIntent = new Intent(ApplicationLoader.applicationContext, PopupReplyReceiver.class);
            if (Build.VERSION.SDK_INT <= 19) {
                mBuilder.addAction(R.drawable.ic_ab_reply2, LocaleController.getString("Reply", R.string.Reply),
                        PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 2, replyIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT));
            } else {
                mBuilder.addAction(R.drawable.ic_ab_reply, LocaleController.getString("Reply", R.string.Reply),
                        PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 2, replyIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT));
            }
        }
        showExtraNotifications(mBuilder, notifyAboutLast);
        notificationManager.notify(1, mBuilder.build());

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

From source file:com.ferdi2005.secondgram.NotificationsController.java

private void showOrUpdateNotification(boolean notifyAboutLast) {
    if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) {
        dismissNotification();//from   w  ww  .  j a  v  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;
        }

        long dialog_id = lastMessageObject.getDialogId();
        long override_dialog_id = dialog_id;
        if (lastMessageObject.messageOwner.mentioned) {
            override_dialog_id = lastMessageObject.messageOwner.from_id;
        }
        int mid = lastMessageObject.getId();
        int chat_id = lastMessageObject.messageOwner.to_id.chat_id != 0
                ? lastMessageObject.messageOwner.to_id.chat_id
                : lastMessageObject.messageOwner.to_id.channel_id;
        int user_id = lastMessageObject.messageOwner.to_id.user_id;
        if (user_id == 0) {
            user_id = lastMessageObject.messageOwner.from_id;
        } else if (user_id == UserConfig.getClientUserId()) {
            user_id = lastMessageObject.messageOwner.from_id;
        }

        TLRPC.User user = MessagesController.getInstance().getUser(user_id);
        TLRPC.Chat chat = null;
        if (chat_id != 0) {
            chat = MessagesController.getInstance().getChat(chat_id);
        }
        TLRPC.FileLocation photoPath = null;

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

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

        if (!notifyDisabled && dialog_id == override_dialog_id && chat != null) {
            int notifyMaxCount;
            int notifyDelay;
            if (preferences.getBoolean("custom_" + dialog_id, false)) {
                notifyMaxCount = preferences.getInt("smart_max_count_" + dialog_id, 2);
                notifyDelay = preferences.getInt("smart_delay_" + dialog_id, 3 * 60);
            } else {
                notifyMaxCount = 2;
                notifyDelay = 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);
            inAppPreview = preferences.getBoolean("EnableInAppPreview", true);
            inAppPriority = preferences.getBoolean("EnableInAppPriority", false);
            boolean custom;
            if (custom = preferences.getBoolean("custom_" + dialog_id, false)) {
                vibrateOverride = preferences.getInt("vibrate_" + dialog_id, 0);
                priorityOverride = preferences.getInt("priority_" + dialog_id, 3);
                choosenSoundPath = preferences.getString("sound_path_" + dialog_id, null);
            } else {
                vibrateOverride = 0;
                priorityOverride = 3;
                choosenSoundPath = null;
            }
            boolean vibrateOnlyIfSilent = false;

            if (chat_id != 0) {
                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", 0xff0000ff);
            } else if (user_id != 0) {
                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_group", 1);
                ledColor = preferences.getInt("MessagesLed", 0xff0000ff);
            }
            if (custom) {
                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)
                    || needVibrate != 2 && vibrateOverride == 2
                    || vibrateOverride != 0 && vibrateOverride != 4) {
                needVibrate = vibrateOverride;
            }
            if (!ApplicationLoader.mainInterfacePaused) {
                if (!inAppSounds) {
                    choosenSoundPath = null;
                }
                if (!inAppVibrate) {
                    needVibrate = 2;
                }
                if (!inAppPriority) {
                    priority = 0;
                } else if (priority == 2) {
                    priority = 1;
                }
            }
            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(e);
                }
            }
        }

        Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
        intent.setFlags(32768);
        if ((int) dialog_id != 0) {
            if (pushDialogs.size() == 1) {
                if (chat_id != 0) {
                    intent.putExtra("chatId", chat_id);
                } else if (user_id != 0) {
                    intent.putExtra("userId", user_id);
                }
            }
            if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
                photoPath = null;
            } else {
                if (pushDialogs.size() == 1) {
                    if (chat != null) {
                        if (chat.photo != null && chat.photo.photo_small != null
                                && chat.photo.photo_small.volume_id != 0
                                && chat.photo.photo_small.local_id != 0) {
                            photoPath = chat.photo.photo_small;
                        }
                    } else if (user != null) {
                        if (user.photo != null && user.photo.photo_small != null
                                && user.photo.photo_small.volume_id != 0
                                && user.photo.photo_small.local_id != 0) {
                            photoPath = user.photo.photo_small;
                        }
                    }
                }
            }
        } else {
            if (pushDialogs.size() == 1) {
                intent.putExtra("encId", (int) (dialog_id >> 32));
            }
        }
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String name;
        boolean replace = true;
        if ((int) dialog_id == 0 || pushDialogs.size() > 1 || AndroidUtilities.needShowPasscode(false)
                || UserConfig.isWaitingForPasscodeEnter) {
            name = LocaleController.getString("AppName", R.string.AppName);
            replace = false;
        } else {
            if (chat != null) {
                name = chat.title;
            } else {
                name = UserObject.getUserName(user);
            }
        }

        String detailText;
        if (pushDialogs.size() == 1) {
            detailText = LocaleController.formatPluralString("NewMessages", total_unread_count);
        } else {
            detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder",
                    R.string.NotificationMessagesPeopleDisplayOrder,
                    LocaleController.formatPluralString("NewMessages", total_unread_count),
                    LocaleController.formatPluralString("FromChats", 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(0xff2ca5e0);

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

        int silent = 2;
        String lastMessage = null;
        boolean hasNewMessages = false;
        if (pushMessages.size() == 1) {
            MessageObject messageObject = pushMessages.get(0);
            String message = lastMessage = getStringForMessage(messageObject, false);
            silent = messageObject.messageOwner.silent ? 1 : 0;
            if (message == null) {
                return;
            }
            if (replace) {
                if (chat != null) {
                    message = message.replace(" @ " + name, "");
                } else {
                    message = message.replace(name + ": ", "").replace(name + " ", "");
                }
            }
            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());
            for (int i = 0; i < count; i++) {
                MessageObject messageObject = pushMessages.get(i);
                String message = getStringForMessage(messageObject, false);
                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 });
        }

        if (Build.VERSION.SDK_INT < 24 && UserConfig.passcodeHash.length() == 0 && hasMessagesToReply()) {
            Intent replyIntent = new Intent(ApplicationLoader.applicationContext, PopupReplyReceiver.class);
            if (Build.VERSION.SDK_INT <= 19) {
                mBuilder.addAction(R.drawable.ic_ab_reply2, LocaleController.getString("Reply", R.string.Reply),
                        PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 2, replyIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT));
            } else {
                mBuilder.addAction(R.drawable.ic_ab_reply, LocaleController.getString("Reply", R.string.Reply),
                        PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 2, replyIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT));
            }
        }
        showExtraNotifications(mBuilder, notifyAboutLast);
        notificationManager.notify(1, mBuilder.build());

        scheduleNotificationRepeat();
    } catch (Exception e) {
        FileLog.e(e);
    }
}

From source file:jmri.enginedriver.throttle.java

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@SuppressLint({ "Recycle", "SetJavaScriptEnabled", "ClickableViewAccessibility" })
@Override// w w  w  .jav  a2 s  . c  o m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        try {
            // restore the requested throttle direction so we can update the
            // direction indication while we wait for an update from WiT
            for (int throttleIndex = 0; throttleIndex < mainapp.maxThrottlesCurrentScreen; throttleIndex++) {
                if (savedInstanceState
                        .getSerializable("dir" + mainapp.throttleIntToString(throttleIndex)) != null)
                    dirs[throttleIndex] = (int) savedInstanceState.getSerializable("dir" + throttleIndex);
            }
        } catch (Exception ignored) { // log the error, but otherwise keep going.
            Log.d("Engine_Driver",
                    "Restore of saved instance state failed " + android.os.Build.VERSION.SDK_INT);
        }
    }

    mainapp = (threaded_application) this.getApplication();

    prefs = getSharedPreferences("jmri.enginedriver_preferences", 0);

    if (mainapp.isForcingFinish()) { // expedite
        mainapp.appIsFinishing = true;
        return;
    }

    mainapp.applyTheme(this);
    setTitle(getApplicationContext().getResources().getString(R.string.app_name_throttle)); // needed in case the language was changed from the default

    //        setContentView(R.layout.throttle);
    setContentView(layoutViewId);

    getCommonPrefs(true); // get all the common preferences
    setThottleNumLimits();

    getDirectionButtonPrefs();

    webViewIsOn = !webViewLocation.equals(WEB_VIEW_LOCATION_NONE);
    keepWebViewLocation = webViewLocation;

    isScreenLocked = false;

    // get the screen brightness on create
    screenBrightnessOriginal = getScreenBrightness();
    screenBrightnessModeOriginal = getScreenBrightnessMode();

    // myGesture = new GestureDetector(this);
    GestureOverlayView ov = findViewById(R.id.throttle_overlay);
    ov.addOnGestureListener(this);
    ov.setGestureVisible(false);

    direction_button_touch_listener dbtl;
    function_button_touch_listener fbtl;
    select_function_button_touch_listener sfbt;
    arrow_speed_button_touch_listener asbl;

    bSels = new Button[mainapp.maxThrottles];
    bRSpds = new Button[mainapp.maxThrottles];
    bLSpds = new Button[mainapp.maxThrottles];

    tvLeftDirInds = new TextView[mainapp.maxThrottles];
    tvRightDirInds = new TextView[mainapp.maxThrottles];

    bFwds = new Button[mainapp.maxThrottles];
    bStops = new Button[mainapp.maxThrottles];
    bRevs = new Button[mainapp.maxThrottles];
    sbs = new SeekBar[mainapp.maxThrottles];

    tvGamePads = new TextView[mainapp.maxThrottles];
    tvSpdLabs = new TextView[mainapp.maxThrottles];
    tvSpdVals = new TextView[mainapp.maxThrottles];
    tvVols = new TextView[mainapp.maxThrottles];

    lls = new LinearLayout[mainapp.maxThrottles];
    llSetSpds = new LinearLayout[mainapp.maxThrottles];
    llLocoIds = new LinearLayout[mainapp.maxThrottles];
    llLocoDirs = new LinearLayout[mainapp.maxThrottles];

    fbs = new ViewGroup[mainapp.maxThrottles];

    tops = new int[mainapp.maxThrottles];
    bottoms = new int[mainapp.maxThrottles];

    functionMaps = (LinkedHashMap<Integer, Button>[]) new LinkedHashMap<?, ?>[mainapp.maxThrottles];

    displayUnitScales = new double[mainapp.maxThrottles];

    changeTimers = new ChangeDelay[mainapp.maxThrottles];

    // throttle layouts
    vThrotScr = findViewById(R.id.throttle_screen);
    vThrotScrWrap = findViewById(R.id.throttle_screen_wrapper);

    for (int i = 0; i < mainapp.maxThrottles; i++) {
        // set listener for select loco buttons
        Button bSel = findViewById(R.id.button_select_loco_0);
        TextView tvLeft = findViewById(R.id.loco_left_direction_indicaton_0);
        TextView tvRight = findViewById(R.id.loco_right_direction_indicaton_0);
        switch (i) {
        case 1:
            bSel = findViewById(R.id.button_select_loco_1);
            tvLeft = findViewById(R.id.loco_left_direction_indicaton_1);
            tvRight = findViewById(R.id.loco_right_direction_indicaton_1);
            break;
        case 2:
            bSel = findViewById(R.id.button_select_loco_2);
            tvLeft = findViewById(R.id.loco_left_direction_indicaton_2);
            tvRight = findViewById(R.id.loco_right_direction_indicaton_2);
            break;
        case 3:
            bSel = findViewById(R.id.button_select_loco_3);
            tvLeft = findViewById(R.id.loco_left_direction_indicaton_3);
            tvRight = findViewById(R.id.loco_right_direction_indicaton_3);
            break;
        case 4:
            bSel = findViewById(R.id.button_select_loco_4);
            tvLeft = findViewById(R.id.loco_left_direction_indicaton_4);
            tvRight = findViewById(R.id.loco_right_direction_indicaton_4);
            break;
        case 5:
            bSel = findViewById(R.id.button_select_loco_5);
            tvLeft = findViewById(R.id.loco_left_direction_indicaton_5);
            tvRight = findViewById(R.id.loco_right_direction_indicaton_5);
            break;
        }
        bSels[i] = bSel;
        bSels[i].setClickable(true);
        sfbt = new select_function_button_touch_listener(i);
        bSels[i].setOnClickListener(sfbt);
        bSels[i].setOnTouchListener(sfbt);
        bSels[i].setOnLongClickListener(sfbt); // Consist Light Edit
        tvLeftDirInds[i] = tvLeft;
        tvRightDirInds[i] = tvRight;

        // Arrow Keys
        try {

            Button bRight = findViewById(R.id.right_speed_button_0);
            Button bLeft = findViewById(R.id.left_speed_button_0);
            switch (i) {
            case 1:
                bRight = findViewById(R.id.right_speed_button_1);
                bLeft = findViewById(R.id.left_speed_button_1);
                break;
            case 2:
                bRight = findViewById(R.id.right_speed_button_2);
                bLeft = findViewById(R.id.left_speed_button_2);
                break;
            case 3:
                bRight = findViewById(R.id.right_speed_button_3);
                bLeft = findViewById(R.id.left_speed_button_3);
                break;
            case 4:
                bRight = findViewById(R.id.right_speed_button_4);
                bLeft = findViewById(R.id.left_speed_button_4);
                break;
            case 5:
                bRight = findViewById(R.id.right_speed_button_5);
                bLeft = findViewById(R.id.left_speed_button_5);
                break;
            }
            bRSpds[i] = bRight;
            bRSpds[i].setClickable(true);
            asbl = new arrow_speed_button_touch_listener(i, "right");
            bRSpds[i].setOnLongClickListener(asbl);
            bRSpds[i].setOnTouchListener(asbl);
            bRSpds[i].setOnClickListener(asbl);

            bLSpds[i] = bLeft;
            bLSpds[i].setClickable(true);
            asbl = new arrow_speed_button_touch_listener(i, "left");
            bLSpds[i].setOnLongClickListener(asbl);
            bLSpds[i].setOnTouchListener(asbl);
            bLSpds[i].setOnClickListener(asbl);

        } catch (Exception ex) {
            Log.d("debug", "onCreate: " + ex.getMessage());
        }

        // set listeners for 3 direction buttons for each throttle
        //----------------------------------------
        Button bFwd = findViewById(R.id.button_fwd_0);
        Button bStop = findViewById(R.id.button_stop_0);
        Button bRev = findViewById(R.id.button_rev_0);
        View v = findViewById(R.id.speed_cell_0);
        switch (i) {
        case 1:
            bFwd = findViewById(R.id.button_fwd_1);
            bStop = findViewById(R.id.button_stop_1);
            bRev = findViewById(R.id.button_rev_1);
            v = findViewById(R.id.speed_cell_1);
            break;
        case 2:
            bFwd = findViewById(R.id.button_fwd_2);
            bStop = findViewById(R.id.button_stop_2);
            bRev = findViewById(R.id.button_rev_2);
            v = findViewById(R.id.speed_cell_2);
            break;
        case 3:
            bFwd = findViewById(R.id.button_fwd_3);
            bStop = findViewById(R.id.button_stop_3);
            bRev = findViewById(R.id.button_rev_3);
            v = findViewById(R.id.speed_cell_3);
            break;
        case 4:
            bFwd = findViewById(R.id.button_fwd_4);
            bStop = findViewById(R.id.button_stop_4);
            bRev = findViewById(R.id.button_rev_4);
            v = findViewById(R.id.speed_cell_4);
            break;
        case 5:
            bFwd = findViewById(R.id.button_fwd_5);
            bStop = findViewById(R.id.button_stop_5);
            bRev = findViewById(R.id.button_rev_5);
            v = findViewById(R.id.speed_cell_5);
            break;
        }

        bFwds[i] = bFwd;
        dbtl = new direction_button_touch_listener(direction_button.LEFT, i);
        bFwds[i].setOnTouchListener(dbtl);

        bStops[i] = bStop;
        fbtl = new function_button_touch_listener(function_button.STOP, i);
        bStops[i].setOnTouchListener(fbtl);

        bRevs[i] = bRev;
        dbtl = new direction_button_touch_listener(direction_button.RIGHT, i);
        bRevs[i].setOnTouchListener(dbtl);

        fbtl = new function_button_touch_listener(function_button.SPEED_LABEL, i);
        v.setOnTouchListener(fbtl);

        // set up listeners for all throttles
        SeekBar s = findViewById(R.id.speed_0);
        switch (i) {
        case 1:
            s = findViewById(R.id.speed_1);
            break;
        case 2:
            s = findViewById(R.id.speed_2);
            break;
        case 3:
            s = findViewById(R.id.speed_3);
            break;
        case 4:
            s = findViewById(R.id.speed_4);
            break;
        case 5:
            s = findViewById(R.id.speed_5);
            break;
        }
        throttle_listener thl;
        sbs[i] = s;
        thl = new throttle_listener(i);
        sbs[i].setOnSeekBarChangeListener(thl);
        sbs[i].setOnTouchListener(thl);

        max_throttle_change = 1;
        //          displaySpeedSteps = false;

        switch (i) {
        case 0:
            lls[i] = findViewById(R.id.throttle_0);
            //                    llSetSpds[i] = (LinearLayout) findViewById(R.id.throttle_0_setspeed);
            llLocoIds[i] = findViewById(R.id.loco_buttons_group_0);
            llLocoDirs[i] = findViewById(R.id.dir_buttons_table_0);
            tvVols[i] = findViewById(R.id.volume_indicator_0); // volume indicators
            tvGamePads[i] = findViewById(R.id.gamepad_indicator_0); // gamepad indicators
            tvSpdLabs[i] = findViewById(R.id.speed_label_0); // set_default_function_labels();
            tvSpdVals[i] = findViewById(R.id.speed_value_label_0);
            //**//                    fbs[i] = (ViewGroup) findViewById(R.id.function_buttons_table_0);
            break;
        case 1:
            lls[i] = findViewById(R.id.throttle_1);
            //                    llSetSpds[i] = (LinearLayout) findViewById(R.id.throttle_1_setspeed);
            llLocoIds[i] = findViewById(R.id.loco_buttons_group_1);
            llLocoDirs[i] = findViewById(R.id.dir_buttons_table_1);
            tvVols[i] = findViewById(R.id.volume_indicator_1); // volume indicators
            tvGamePads[i] = findViewById(R.id.gamepad_indicator_1); // gamepad indicators
            tvSpdLabs[i] = findViewById(R.id.speed_label_1); // set_default_function_labels();
            tvSpdVals[i] = findViewById(R.id.speed_value_label_1);
            //**//                    fbs[i] = (ViewGroup) findViewById(R.id.function_buttons_table_1);
            break;
        case 2:
            lls[i] = findViewById(R.id.throttle_2);
            //                    llSetSpds[i] = (LinearLayout) findViewById(R.id.throttle_2_setspeed);
            llLocoIds[i] = findViewById(R.id.loco_buttons_group_2);
            llLocoDirs[i] = findViewById(R.id.dir_buttons_table_2);
            tvVols[i] = findViewById(R.id.volume_indicator_2); // volume indicators
            tvGamePads[i] = findViewById(R.id.gamepad_indicator_2); // gamepad indicators
            tvSpdLabs[i] = findViewById(R.id.speed_label_2); // set_default_function_labels();
            tvSpdVals[i] = findViewById(R.id.speed_value_label_2);
            //**//                    fbs[i] = (ViewGroup) findViewById(R.id.function_buttons_table_2);
            break;
        case 3:
            lls[i] = findViewById(R.id.throttle_3);
            //                    llSetSpds[i] = (LinearLayout) findViewById(R.id.throttle_3_setspeed);
            llLocoIds[i] = findViewById(R.id.loco_buttons_group_3);
            llLocoDirs[i] = findViewById(R.id.dir_buttons_table_3);
            tvVols[i] = findViewById(R.id.volume_indicator_3); // volume indicators
            tvGamePads[i] = findViewById(R.id.gamepad_indicator_3); // gamepad indicators
            tvSpdLabs[i] = findViewById(R.id.speed_label_3); // set_default_function_labels();
            tvSpdVals[i] = findViewById(R.id.speed_value_label_3);
            //**//                    fbs[i] = (ViewGroup) findViewById(R.id.function_buttons_table_3);
            break;
        case 4:
            lls[i] = findViewById(R.id.throttle_4);
            //                    llSetSpds[i] = (LinearLayout) findViewById(R.id.throttle_4_setspeed);
            llLocoIds[i] = findViewById(R.id.loco_buttons_group_4);
            llLocoDirs[i] = findViewById(R.id.dir_buttons_table_4);
            tvVols[i] = findViewById(R.id.volume_indicator_4); // volume indicators
            tvGamePads[i] = findViewById(R.id.gamepad_indicator_4); // gamepad indicators
            tvSpdLabs[i] = findViewById(R.id.speed_label_4); // set_default_function_labels();
            tvSpdVals[i] = findViewById(R.id.speed_value_label_4);
            //**//                    fbs[i] = (ViewGroup) findViewById(R.id.function_buttons_table_4);
            break;
        case 5:
            lls[i] = findViewById(R.id.throttle_5);
            //                    llSetSpds[i] = (LinearLayout) findViewById(R.id.throttle_5_setspeed);
            llLocoIds[i] = findViewById(R.id.loco_buttons_group_5);
            llLocoDirs[i] = findViewById(R.id.dir_buttons_table_5);
            tvVols[i] = findViewById(R.id.volume_indicator_5); // volume indicators
            tvGamePads[i] = findViewById(R.id.gamepad_indicator_5); // gamepad indicators
            tvSpdLabs[i] = findViewById(R.id.speed_label_5); // set_default_function_labels();
            tvSpdVals[i] = findViewById(R.id.speed_value_label_5);
            //**//                    fbs[i] = (ViewGroup) findViewById(R.id.function_buttons_table_5);
            break;
        }

        // set throttle change delay timers
        changeTimers[i] = new ChangeDelay(i);

    }

    clearVolumeAndGamepadAdditionalIndicators();

    setDirectionButtonLabels(); // set all the direction button labels

    // set label and dcc functions (based on settings) or hide if no label
    setAllFunctionLabelsAndListeners();

    if (mVelocityTracker == null) {
        mVelocityTracker = VelocityTracker.obtain();
    }

    setActiveThrottle(0); // set the throttle the volume keys control depending on the preference to the default 0

    webView = findViewById(R.id.throttle_webview);
    String databasePath = webView.getContext().getDir("databases", Context.MODE_PRIVATE).getPath();
    webView.getSettings().setDatabasePath(databasePath);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setBuiltInZoomControls(true); // Enable Multitouch
    // if supported
    webView.getSettings().setUseWideViewPort(true); // Enable greater
    // zoom-out
    webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
    webView.setInitialScale((int) (100 * scale));
    // webView.getSettings().setLoadWithOverviewMode(true); // size image to
    // fill width

    // open all links inside the current view (don't start external web
    // browser)
    noUrl = getApplicationContext().getResources().getString(R.string.blank_page_url);

    WebViewClient EDWebClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!noUrl.equals(url)) { // if url is legit
                currentUrl = url;
                if (firstUrl == null) { // if this is the first legit url 
                    firstUrl = url;
                    clearHistory = true;
                }
                if (clearHistory) { // keep clearing history until off this page
                    if (url.equals(firstUrl)) { // (works around Android bug)
                        webView.clearHistory();
                    } else {
                        clearHistory = false;
                    }
                }
            }
        }
    };

    webView.setWebViewClient(EDWebClient);
    if (currentUrl == null || savedInstanceState == null || webView.restoreState(savedInstanceState) == null) {
        load_webview(); // reload if no saved state or no page had loaded when state was saved
    }
    // put pointer to this activity's handler in main app's shared variable
    mainapp.throttle_msg_handler = new throttle_handler();

    // set throttle change delay timers
    for (int throttleIndex = 0; throttleIndex < mainapp.maxThrottles; throttleIndex++) {
        changeTimers[throttleIndex] = new ChangeDelay(throttleIndex);
    }
    // tone generator for feedback sounds
    try {
        tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION,
                preferences.getIntPrefValue(prefs, "prefGamePadFeedbackVolume", getApplicationContext()
                        .getResources().getString(R.string.prefGamePadFeedbackVolumeDefaultValue)));
    } catch (RuntimeException e) {
        Log.e("Engine_Driver", "new ToneGenerator failed. Runtime Exception, OS "
                + android.os.Build.VERSION.SDK_INT + " Message: " + e);
    }
    // set GamePad Support
    setGamepadKeys();

    // initialise ESU MCII
    if (IS_ESU_MCII) {
        Log.d("Engine_Driver", "ESU_MCII: Initialise fragments...");
        int zeroTrim = preferences.getIntPrefValue(prefs, "prefEsuMc2ZeroTrim",
                getApplicationContext().getResources().getString(R.string.prefEsuMc2ZeroTrimDefaultValue));
        esuThrottleFragment = ThrottleFragment.newInstance(zeroTrim);
        esuThrottleFragment.setOnThrottleListener(esuOnThrottleListener);
        esuStopButtonFragment = StopButtonFragment.newInstance();
        esuStopButtonFragment.setOnStopButtonListener(esuOnStopButtonListener);
        Log.d("Engine_Driver", "ESU_MCII: ...fragments initialised");

        getSupportFragmentManager().beginTransaction().add(esuThrottleFragment, "mc2:throttle")
                .add(esuStopButtonFragment, "mc2:stopKey").commit();
        esuMc2Led.setState(EsuMc2Led.RED, EsuMc2LedState.OFF, true);
        esuMc2Led.setState(EsuMc2Led.GREEN, EsuMc2LedState.STEADY_FLASH, true);

        // Now apply knob zero trim
        updateEsuMc2ZeroTrim();
        Log.d("Engine_Driver", "ESU_MCII: Initialisation complete");
    }

    setupSensor(); // setup the support for shake actions.

    setupTts();

    if (prefs.getBoolean("prefImportServerAuto",
            getApplicationContext().getResources().getBoolean(R.bool.prefImportServerAutoDefaultValue))) {
        autoImportFromURL();
    }

}

From source file:com.tct.mail.compose.ComposeActivity.java

protected void sendOrSave(final boolean save, final boolean showToast) {
    // Check if user is a monkey. Monkeys can compose and hit send
    // button but are not allowed to send anything off the device.
    // TS: xiaolin.li 2015-01-08 EMAIL BUGFIX-893877 DEL_S
    /*if (ActivityManager.isUserAMonkey()) {
    return;//from w  w w.  j a  v a  2 s  .  com
    }*/
    // TS: xiaolin.li 2015-01-08 EMAIL BUGFIX-893877 DEL_E
    final SendOrSaveCallback callback = new SendOrSaveCallback() {
        // FIXME: unused
        private int mRestoredRequestId;

        @Override
        public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask) {
            synchronized (mActiveTasks) {
                int numTasks = mActiveTasks.size();
                if (numTasks == 0) {
                    // Start service so we won't be killed if this app is
                    // put in the background.
                    startService(new Intent(ComposeActivity.this, EmptyService.class));
                }

                mActiveTasks.add(sendOrSaveTask);
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.initializeSendOrSave(sendOrSaveTask);
            }
        }

        @Override
        public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage, Message message) {
            synchronized (mDraftLock) {
                mDraftAccount = sendOrSaveMessage.mAccount;
                mDraftId = message.id;
                mDraft = message;
                if (sRequestMessageIdMap != null) {
                    sRequestMessageIdMap.put(sendOrSaveMessage.requestId(), mDraftId);
                }
                // Cache request message map, in case the process is killed
                saveRequestMap();
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage, message);
            }
        }

        @Override
        public Message getMessage() {
            synchronized (mDraftLock) {
                return mDraft;
            }
        }

        @Override
        public void sendOrSaveFinished(SendOrSaveTask task, boolean success) {
            // Update the last sent from account.
            if (mAccount != null) {
                MailAppProvider.getInstance().setLastSentFromAccount(mAccount.uri.toString());
            }
            // TS: zhaotianyong 2015-03-25 EMAIL BUGFIX-954496 ADD_S
            // TS: zhaotianyong 2015-03-31 EMAIL BUGFIX-963249 ADD_S
            if (doSend) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) ComposeActivity.this
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
                if (info == null) {
                    Utility.showToast(ComposeActivity.this, R.string.send_failed);
                }
            }
            // TS: zhaotianyong 2015-03-31 EMAIL BUGFIX-963249 ADD_E
            // TS: zhaotianyong 2015-03-25 EMAIL BUGFIX-954496 ADD_E
            if (success) {
                // Successfully sent or saved so reset change markers
                discardChanges();
                //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 ADD_S
                if (!doSend && showToast) {
                    Intent intent = new Intent(DRAFT_SAVED_ACTION);
                    intent.setPackage(getString(R.string.email_package_name));
                    intent.putExtra(BaseColumns._ID, mDraftId);
                    //send ordered broadcast to execute the event in sequence in different receivers,
                    //ordered by priority
                    sendOrderedBroadcast(intent, null);
                }
                //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 ADD_E
            } else {
                // A failure happened with saving/sending the draft
                // TODO(pwestbro): add a better string that should be used
                // when failing to send or save
                //[BUGFIX]-MOD by SCDTABLET.shujing.jin@tcl.com,08/05/2016,2635083
                Utility.showShortToast(ComposeActivity.this, R.string.send_failed);
                //Toast.makeText(ComposeActivity.this, R.string.send_failed, Toast.LENGTH_SHORT)
                //        .show();
            }

            int numTasks;
            synchronized (mActiveTasks) {
                // Remove the task from the list of active tasks
                mActiveTasks.remove(task);
                numTasks = mActiveTasks.size();
            }

            if (numTasks == 0) {
                // Stop service so we can be killed.
                stopService(new Intent(ComposeActivity.this, EmptyService.class));
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.sendOrSaveFinished(task, success);
            }
        }

        @Override
        public void incrementRecipientsTimesContacted(final List<String> recipients) {
            ComposeActivity.this.incrementRecipientsTimesContacted(recipients);
        }
    };
    //TS: zheng.zou 2015-3-16 EMAIL BUGFIX_948927 Mod_S
    if (mReplyFromAccount == null && mAccount != null) {
        mReplyFromAccount = getDefaultReplyFromAccount(mAccount);
    }
    if (mReplyFromAccount != null) {
        setAccount(mReplyFromAccount.account);
    }
    //TS: zheng.zou 2015-3-16 EMAIL BUGFIX_948927 Mod_E
    // TS: yanhua.chen 2015-9-19 EMAIL BUGFIX_569665 ADD_S
    mIsSaveDraft = save;
    // TS: yanhua.chen 2015-9-19 EMAIL BUGFIX_569665 ADD_E

    final Spanned body = removeComposingSpans(mBodyView.getText());
    SEND_SAVE_TASK_HANDLER.post(new Runnable() {
        @Override
        public void run() {
            final Message msg = createMessage(mReplyFromAccount, mRefMessage, getMode(), body);
            // TS: kaifeng.lu 2016-4-6 EMAIL BUGFIX_1909143 ADD_S
            if (/*!mIsClickIcon &&*/ !mEditDraft && (mIsSaveDraft || doSend)) {//[BUGFIX]-MOD by SCDTABLET.shujing.jin@tcl.com,05/06/2016,2013535
                String body1 = mBodyView.getText().toString().replace("\n", "\n\r");
                SpannableString spannableString = new SpannableString(body1);
                StringBuffer bodySignature = new StringBuffer(body1);
                //[BUGFIX]-DEL begin by SCDTABLET.shujing.jin@tcl.com,05/17/2016,2013535,2148647
                //if(mCachedSettings != null){
                //    bodySignature.append(convertToPrintableSignature(mCachedSettings.signature));
                //}
                //[BUGFIX]-DEL end by SCDTABLET.shujing.jin
                spannableString = new SpannableString(bodySignature.toString());
                msg.bodyHtml = spannedBodyToHtml(spannableString, true);
                msg.bodyText = bodySignature.toString();
            }
            // TS: kaifeng.lu 2016-4-6 EMAIL BUGFIX_1909143 ADD_E
            mRequestId = sendOrSaveInternal(ComposeActivity.this, mReplyFromAccount, msg, mRefMessage,
                    mQuotedTextView.getQuotedTextIfIncluded(), callback, SEND_SAVE_TASK_HANDLER, save,
                    mComposeMode, mDraftAccount, mExtraValues);
        }
    });

    // Don't display the toast if the user is just changing the orientation,
    // but we still need to save the draft to the cursor because this is how we restore
    // the attachments when the configuration change completes.
    if (showToast && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
        //TS: xinlei.sheng 2015-01-26 EMAIL FIXBUG_886976 MOD_S
        if (mLaunchContact) {
            mLaunchContact = false;
        } else {
            //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 MDD_S
            if (!save) {
                //[BUGFIX]-MOD by SCDTABLET.shujing.jin@tcl.com,08/05/2016,2635083
                Utility.showToast(this, R.string.sending_message);
                //Toast.makeText(this, R.string.sending_message,
                //        Toast.LENGTH_LONG).show();
            }
            //                Toast.makeText(this, save ? R.string.message_saved : R.string.sending_message,
            //                        Toast.LENGTH_LONG).show();
            //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 MOD_E
        }
        //TS: xinlei.sheng 2015-01-26 EMAIL FIXBUG_886976 MOD_E
    }

    // Need to update variables here because the send or save completes
    // asynchronously even though the toast shows right away.
    discardChanges();
    updateSaveUi();

    // If we are sending, finish the activity
    if (!save) {
        finish();
        //TS: yanhua.chen 2015-6-15 EMAIL BUGFIX_1024081 ADD_S
        //TS: lin-zhou 2015-10-15 EMAIL BUGFIX_718388 MOD_S
        Uri soundUri = Uri.parse(
                "android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.email_sent);
        MediaPlayer player = new MediaPlayer();
        try {
            if (soundUri != null) {
                player.setDataSource(getApplicationContext(), soundUri);
            }
            player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
            player.prepare();
            player.start();
        } catch (IllegalArgumentException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur IllegalArgumentException");
        } catch (SecurityException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur SecurityException");
        } catch (IllegalStateException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur IllegalStateException");
        } catch (IOException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur IOException");
        } catch (NullPointerException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur NullPointerException");
        }
        //TS: lin-zhou 2015-10-15 EMAIL BUGFIX_718388 MOD_E
        //TS: yanhua.chen 2015-6-15 EMAIL BUGFIX_1024081 ADD_E
    }
}