Example usage for android.app PendingIntent FLAG_UPDATE_CURRENT

List of usage examples for android.app PendingIntent FLAG_UPDATE_CURRENT

Introduction

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

Prototype

int FLAG_UPDATE_CURRENT

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

Click Source Link

Document

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

Usage

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        notificationManager.notify(REQUEST_UNIQUE_ID, notification);

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

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

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

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

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

From source file:android_network.hetnet.vpn_service.ServiceSinkhole.java

private Builder getBuilder(List<Rule> listAllowed, List<Rule> listRule) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean subnet = prefs.getBoolean("subnet", false);
    boolean tethering = prefs.getBoolean("tethering", false);
    boolean lan = prefs.getBoolean("lan", false);
    boolean ip6 = prefs.getBoolean("ip6", true);
    boolean filter = prefs.getBoolean("filter", false);
    boolean system = prefs.getBoolean("manage_system", false);

    // Build VPN service
    Builder builder = new Builder();
    builder.setSession(getString(R.string.app_name));

    // VPN address
    String vpn4 = prefs.getString("vpn4", "10.1.10.1");
    Log.i(TAG, "vpn4=" + vpn4);
    builder.addAddress(vpn4, 32);/*from   ww  w .j a  v a2  s  .  com*/
    if (ip6) {
        String vpn6 = prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1");
        Log.i(TAG, "vpn6=" + vpn6);
        builder.addAddress(vpn6, 128);
    }

    // DNS address
    if (filter)
        for (InetAddress dns : getDns(ServiceSinkhole.this)) {
            if (ip6 || dns instanceof Inet4Address) {
                Log.i(TAG, "dns=" + dns);
                builder.addDnsServer(dns);
            }
        }

    // Subnet routing
    if (subnet) {
        // Exclude IP ranges
        List<IPUtil.CIDR> listExclude = new ArrayList<>();
        listExclude.add(new IPUtil.CIDR("127.0.0.0", 8)); // localhost

        if (tethering) {
            // USB Tethering 192.168.42.x
            // Wi-Fi Tethering 192.168.43.x
            listExclude.add(new IPUtil.CIDR("192.168.42.0", 23));
        }

        if (lan) {
            try {
                Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
                while (nis.hasMoreElements()) {
                    NetworkInterface ni = nis.nextElement();
                    if (ni != null && ni.isUp() && !ni.isLoopback() && ni.getName() != null
                            && !ni.getName().startsWith("tun"))
                        for (InterfaceAddress ia : ni.getInterfaceAddresses())
                            if (ia.getAddress() instanceof Inet4Address) {
                                IPUtil.CIDR local = new IPUtil.CIDR(ia.getAddress(),
                                        ia.getNetworkPrefixLength());
                                Log.i(TAG, "Excluding " + ni.getName() + " " + local);
                                listExclude.add(local);
                            }
                }
            } catch (SocketException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        }

        Configuration config = getResources().getConfiguration();
        if (config.mcc == 310 && config.mnc == 260) {
            // T-Mobile Wi-Fi calling
            listExclude.add(new IPUtil.CIDR("66.94.2.0", 24));
            listExclude.add(new IPUtil.CIDR("66.94.6.0", 23));
            listExclude.add(new IPUtil.CIDR("66.94.8.0", 22));
            listExclude.add(new IPUtil.CIDR("208.54.0.0", 16));
        }
        listExclude.add(new IPUtil.CIDR("224.0.0.0", 3)); // broadcast

        Collections.sort(listExclude);

        try {
            InetAddress start = InetAddress.getByName("0.0.0.0");
            for (IPUtil.CIDR exclude : listExclude) {
                Log.i(TAG, "Exclude " + exclude.getStart().getHostAddress() + "..."
                        + exclude.getEnd().getHostAddress());
                for (IPUtil.CIDR include : IPUtil.toCIDR(start, IPUtil.minus1(exclude.getStart())))
                    try {
                        builder.addRoute(include.address, include.prefix);
                    } catch (Throwable ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }
                start = IPUtil.plus1(exclude.getEnd());
            }
            for (IPUtil.CIDR include : IPUtil.toCIDR("224.0.0.0", "255.255.255.255"))
                try {
                    builder.addRoute(include.address, include.prefix);
                } catch (Throwable ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
        } catch (UnknownHostException ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
    } else
        builder.addRoute("0.0.0.0", 0);

    Log.i(TAG, "IPv6=" + ip6);
    if (ip6)
        builder.addRoute("0:0:0:0:0:0:0:0", 0);

    // MTU
    int mtu = jni_get_mtu();
    Log.i(TAG, "MTU=" + mtu);
    builder.setMtu(mtu);

    //         Add list of allowed applications
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        if (last_connected && !filter)
            for (Rule rule : listAllowed)
                try {
                    builder.addDisallowedApplication(rule.info.packageName);
                } catch (PackageManager.NameNotFoundException ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
        else if (filter)
            for (Rule rule : listRule)
                if (!rule.apply || (!system && rule.system))
                    try {
                        Log.i(TAG, "Not routing " + rule.info.packageName);
                        builder.addDisallowedApplication(rule.info.packageName);
                    } catch (PackageManager.NameNotFoundException ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }

    // Build configure intent
    Intent configure = new Intent(this, MainActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, configure, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setConfigureIntent(pi);

    return builder;
}

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

private void showOrUpdateNotification(boolean notifyAboutLast) {
    if (pushMessages.isEmpty()) {
        dismissNotification();//from   w  w  w  . java  2 s . 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;
        }

        final long dialog_id = lastMessageObject.getDialogId();

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

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

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

        //TLRPC.FileLocation photoPath = null;

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

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

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

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

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

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

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

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

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

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

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

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

        mBuilder.setCategory(NotificationCompat.CATEGORY_MESSAGE);

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

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

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

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

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

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

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

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

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

        scheduleNotificationRepeat();

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

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

}

From source file:com.andrew.apolloMod.service.ApolloService.java

/** Return notification remote views
 * /*w  w  w .j av a 2 s  .c  om*/
 * @return [views, bigViews]
 */
public RemoteViews[] getNotificationViews() {
    Bitmap b = getAlbumBitmap();

    RemoteViews bigViews = new RemoteViews(getPackageName(), R.layout.status_bar_expanded);
    RemoteViews views = new RemoteViews(getPackageName(), R.layout.status_bar);

    if (b != null) {
        bigViews.setImageViewBitmap(R.id.status_bar_album_art, b);
        views.setViewVisibility(R.id.status_bar_icon, View.GONE);
        views.setViewVisibility(R.id.status_bar_album_art, View.VISIBLE);
        views.setImageViewBitmap(R.id.status_bar_album_art, b);
    } else {
        views.setViewVisibility(R.id.status_bar_icon, View.VISIBLE);
        views.setViewVisibility(R.id.status_bar_album_art, View.GONE);
    }

    ComponentName rec = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName());
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.putExtra(CMDNOTIF, 1);
    mediaButtonIntent.setComponent(rec);
    KeyEvent mediaKey = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
    mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, mediaKey);
    PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, mediaButtonIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    views.setOnClickPendingIntent(R.id.status_bar_play, mediaPendingIntent);
    bigViews.setOnClickPendingIntent(R.id.status_bar_play, mediaPendingIntent);

    mediaButtonIntent.putExtra(CMDNOTIF, 2);
    mediaKey = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_NEXT);
    mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, mediaKey);
    mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 2, mediaButtonIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    views.setOnClickPendingIntent(R.id.status_bar_next, mediaPendingIntent);
    bigViews.setOnClickPendingIntent(R.id.status_bar_next, mediaPendingIntent);

    mediaButtonIntent.putExtra(CMDNOTIF, 4);
    mediaKey = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PREVIOUS);
    mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, mediaKey);
    mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 4, mediaButtonIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    bigViews.setOnClickPendingIntent(R.id.status_bar_prev, mediaPendingIntent);

    mediaButtonIntent.putExtra(CMDNOTIF, 3);
    mediaKey = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_STOP);
    mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, mediaKey);
    mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 3, mediaButtonIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    views.setOnClickPendingIntent(R.id.status_bar_collapse, mediaPendingIntent);
    bigViews.setOnClickPendingIntent(R.id.status_bar_collapse, mediaPendingIntent);

    views.setImageViewResource(R.id.status_bar_play, R.drawable.apollo_holo_dark_pause);
    bigViews.setImageViewResource(R.id.status_bar_play, R.drawable.apollo_holo_dark_pause);

    views.setTextViewText(R.id.status_bar_track_name, getTrackName());
    bigViews.setTextViewText(R.id.status_bar_track_name, getTrackName());

    views.setTextViewText(R.id.status_bar_artist_name, getArtistName());
    bigViews.setTextViewText(R.id.status_bar_artist_name, getArtistName());

    bigViews.setTextViewText(R.id.status_bar_album_name, getAlbumName());

    return new RemoteViews[] { views, bigViews };

}

From source file:eu.faircode.netguard.ServiceSinkhole.java

private Builder getBuilder(List<Rule> listAllowed, List<Rule> listRule) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean subnet = prefs.getBoolean("subnet", false);
    boolean tethering = prefs.getBoolean("tethering", false);
    boolean lan = prefs.getBoolean("lan", false);
    boolean ip6 = prefs.getBoolean("ip6", true);
    boolean filter = prefs.getBoolean("filter", false);
    boolean system = prefs.getBoolean("manage_system", false);

    // Build VPN service
    Builder builder = new Builder();
    builder.setSession(getString(R.string.app_name));

    // VPN address
    String vpn4 = prefs.getString("vpn4", "10.1.10.1");
    Log.i(TAG, "vpn4=" + vpn4);
    builder.addAddress(vpn4, 32);//from   ww w .  ja  v a 2 s  . c  o  m
    if (ip6) {
        String vpn6 = prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1");
        Log.i(TAG, "vpn6=" + vpn6);
        builder.addAddress(vpn6, 128);
    }

    // DNS address
    if (filter)
        for (InetAddress dns : getDns(ServiceSinkhole.this)) {
            if (ip6 || dns instanceof Inet4Address) {
                Log.i(TAG, "dns=" + dns);
                builder.addDnsServer(dns);
            }
        }

    // Subnet routing
    if (subnet) {
        // Exclude IP ranges
        List<IPUtil.CIDR> listExclude = new ArrayList<>();
        listExclude.add(new IPUtil.CIDR("127.0.0.0", 8)); // localhost

        if (tethering) {
            // USB tethering 192.168.42.x
            // Wi-Fi tethering 192.168.43.x
            listExclude.add(new IPUtil.CIDR("192.168.42.0", 23));
            // Wi-Fi direct 192.168.49.x
            listExclude.add(new IPUtil.CIDR("192.168.49.0", 24));
        }

        if (lan) {
            try {
                Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
                while (nis.hasMoreElements()) {
                    NetworkInterface ni = nis.nextElement();
                    if (ni != null && ni.isUp() && !ni.isLoopback() && ni.getName() != null
                            && !ni.getName().startsWith("tun"))
                        for (InterfaceAddress ia : ni.getInterfaceAddresses())
                            if (ia.getAddress() instanceof Inet4Address) {
                                IPUtil.CIDR local = new IPUtil.CIDR(ia.getAddress(),
                                        ia.getNetworkPrefixLength());
                                Log.i(TAG, "Excluding " + ni.getName() + " " + local);
                                listExclude.add(local);
                            }
                }
            } catch (SocketException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        }

        // https://en.wikipedia.org/wiki/Mobile_country_code
        Configuration config = getResources().getConfiguration();

        // T-Mobile Wi-Fi calling
        if (config.mcc == 310 && (config.mnc == 160 || config.mnc == 200 || config.mnc == 210
                || config.mnc == 220 || config.mnc == 230 || config.mnc == 240 || config.mnc == 250
                || config.mnc == 260 || config.mnc == 270 || config.mnc == 310 || config.mnc == 490
                || config.mnc == 660 || config.mnc == 800)) {
            listExclude.add(new IPUtil.CIDR("66.94.2.0", 24));
            listExclude.add(new IPUtil.CIDR("66.94.6.0", 23));
            listExclude.add(new IPUtil.CIDR("66.94.8.0", 22));
            listExclude.add(new IPUtil.CIDR("208.54.0.0", 16));
        }

        // Verizon wireless calling
        if ((config.mcc == 310 && (config.mnc == 4 || config.mnc == 5 || config.mnc == 6 || config.mnc == 10
                || config.mnc == 12 || config.mnc == 13 || config.mnc == 350 || config.mnc == 590
                || config.mnc == 820 || config.mnc == 890 || config.mnc == 910))
                || (config.mcc == 311 && (config.mnc == 12 || config.mnc == 110
                        || (config.mnc >= 270 && config.mnc <= 289) || config.mnc == 390
                        || (config.mnc >= 480 && config.mnc <= 489) || config.mnc == 590))
                || (config.mcc == 312 && (config.mnc == 770))) {
            listExclude.add(new IPUtil.CIDR("66.174.0.0", 16)); // 66.174.0.0 - 66.174.255.255
            listExclude.add(new IPUtil.CIDR("66.82.0.0", 15)); // 69.82.0.0 - 69.83.255.255
            listExclude.add(new IPUtil.CIDR("69.96.0.0", 13)); // 69.96.0.0 - 69.103.255.255
            listExclude.add(new IPUtil.CIDR("70.192.0.0", 11)); // 70.192.0.0 - 70.223.255.255
            listExclude.add(new IPUtil.CIDR("97.128.0.0", 9)); // 97.128.0.0 - 97.255.255.255
            listExclude.add(new IPUtil.CIDR("174.192.0.0", 9)); // 174.192.0.0 - 174.255.255.255
            listExclude.add(new IPUtil.CIDR("72.96.0.0", 9)); // 72.96.0.0 - 72.127.255.255
            listExclude.add(new IPUtil.CIDR("75.192.0.0", 9)); // 75.192.0.0 - 75.255.255.255
            listExclude.add(new IPUtil.CIDR("97.0.0.0", 10)); // 97.0.0.0 - 97.63.255.255
        }

        // Broadcast
        listExclude.add(new IPUtil.CIDR("224.0.0.0", 3));

        Collections.sort(listExclude);

        try {
            InetAddress start = InetAddress.getByName("0.0.0.0");
            for (IPUtil.CIDR exclude : listExclude) {
                Log.i(TAG, "Exclude " + exclude.getStart().getHostAddress() + "..."
                        + exclude.getEnd().getHostAddress());
                for (IPUtil.CIDR include : IPUtil.toCIDR(start, IPUtil.minus1(exclude.getStart())))
                    try {
                        builder.addRoute(include.address, include.prefix);
                    } catch (Throwable ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }
                start = IPUtil.plus1(exclude.getEnd());
            }
            for (IPUtil.CIDR include : IPUtil.toCIDR("224.0.0.0", "255.255.255.255"))
                try {
                    builder.addRoute(include.address, include.prefix);
                } catch (Throwable ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
        } catch (UnknownHostException ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
    } else
        builder.addRoute("0.0.0.0", 0);

    Log.i(TAG, "IPv6=" + ip6);
    if (ip6)
        builder.addRoute("0:0:0:0:0:0:0:0", 0);

    // MTU
    int mtu = jni_get_mtu();
    Log.i(TAG, "MTU=" + mtu);
    builder.setMtu(mtu);

    // Add list of allowed applications
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        if (last_connected && !filter)
            for (Rule rule : listAllowed)
                try {
                    builder.addDisallowedApplication(rule.info.packageName);
                } catch (PackageManager.NameNotFoundException ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
        else if (filter)
            for (Rule rule : listRule)
                if (!rule.apply || (!system && rule.system))
                    try {
                        Log.i(TAG, "Not routing " + rule.info.packageName);
                        builder.addDisallowedApplication(rule.info.packageName);
                    } catch (PackageManager.NameNotFoundException ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }

    // Build configure intent
    Intent configure = new Intent(this, ActivityMain.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, configure, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setConfigureIntent(pi);

    return builder;
}

From source file:com.av.remusic.service.MediaService.java

private Notification getNotification() {
    RemoteViews remoteViews;/*from  www .ja v  a 2 s . c  om*/
    final int PAUSE_FLAG = 0x1;
    final int NEXT_FLAG = 0x2;
    final int STOP_FLAG = 0x3;
    final String albumName = getAlbumName();
    final String artistName = getArtistName();
    final boolean isPlaying = isPlaying();

    remoteViews = new RemoteViews(this.getPackageName(), R.layout.notification);
    String text = TextUtils.isEmpty(albumName) ? artistName : artistName + " - " + albumName;
    remoteViews.setTextViewText(R.id.title, getTrackName());
    remoteViews.setTextViewText(R.id.text, text);

    //action?  ?flag??
    Intent pauseIntent = new Intent(TOGGLEPAUSE_ACTION);
    pauseIntent.putExtra("FLAG", PAUSE_FLAG);
    PendingIntent pausePIntent = PendingIntent.getBroadcast(this, 0, pauseIntent, 0);
    remoteViews.setImageViewResource(R.id.iv_pause,
            isPlaying ? R.drawable.note_btn_pause : R.drawable.note_btn_play);
    remoteViews.setOnClickPendingIntent(R.id.iv_pause, pausePIntent);

    Intent nextIntent = new Intent(NEXT_ACTION);
    nextIntent.putExtra("FLAG", NEXT_FLAG);
    PendingIntent nextPIntent = PendingIntent.getBroadcast(this, 0, nextIntent, 0);
    remoteViews.setOnClickPendingIntent(R.id.iv_next, nextPIntent);

    Intent preIntent = new Intent(STOP_ACTION);
    preIntent.putExtra("FLAG", STOP_FLAG);
    PendingIntent prePIntent = PendingIntent.getBroadcast(this, 0, preIntent, 0);
    remoteViews.setOnClickPendingIntent(R.id.iv_stop, prePIntent);

    //        PendingIntent pendingIntent = PendingIntent.getActivity(this.getApplicationContext(), 0,
    //                new Intent(this.getApplicationContext(), PlayingActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
    final Intent nowPlayingIntent = new Intent();
    //nowPlayingIntent.setAction("com.av.remusic.LAUNCH_NOW_PLAYING_ACTION");
    nowPlayingIntent
            .setComponent(new ComponentName("com.av.remusic", "com.av.remusic.activity.PlayingActivity"));
    nowPlayingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent clickIntent = PendingIntent.getBroadcast(this, 0, nowPlayingIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent click = PendingIntent.getActivity(this, 0, nowPlayingIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    final Bitmap bitmap = ImageUtils.getArtworkQuick(this, getAlbumId(), 160, 160);
    if (bitmap != null) {
        remoteViews.setImageViewBitmap(R.id.image, bitmap);
        // remoteViews.setImageViewUri(R.id.image, MusicUtils.getAlbumUri(this, getAudioId()));
        mNoBit = null;

    } else if (!isTrackLocal()) {
        if (mNoBit != null) {
            remoteViews.setImageViewBitmap(R.id.image, mNoBit);
            mNoBit = null;

        } else {
            Uri uri = null;
            if (getAlbumPath() != null) {
                try {
                    uri = Uri.parse(getAlbumPath());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (getAlbumPath() == null || uri == null) {
                mNoBit = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder_disk_210);
                updateNotification();
            } else {
                ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(uri)
                        .setProgressiveRenderingEnabled(true).build();
                ImagePipeline imagePipeline = Fresco.getImagePipeline();
                DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline
                        .fetchDecodedImage(imageRequest, MediaService.this);

                dataSource.subscribe(new BaseBitmapDataSubscriber() {

                    @Override
                    public void onNewResultImpl(@Nullable Bitmap bitmap) {
                        // You can use the bitmap in only limited ways
                        // No need to do any cleanup.
                        if (bitmap != null) {
                            mNoBit = bitmap;
                        }
                        updateNotification();
                    }

                    @Override
                    public void onFailureImpl(DataSource dataSource) {
                        // No cleanup required here.
                        mNoBit = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder_disk_210);
                        updateNotification();
                    }
                }, CallerThreadExecutor.getInstance());
            }
        }

    } else {
        remoteViews.setImageViewResource(R.id.image, R.drawable.placeholder_disk_210);
    }

    if (mNotificationPostTime == 0) {
        mNotificationPostTime = System.currentTimeMillis();
    }
    if (mNotification == null) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContent(remoteViews)
                .setSmallIcon(R.drawable.ic_notification).setContentIntent(click)
                .setWhen(mNotificationPostTime);
        if (CommonUtils.isJellyBeanMR1()) {
            builder.setShowWhen(false);
        }
        mNotification = builder.build();
    } else {
        mNotification.contentView = remoteViews;
    }

    return mNotification;
}

From source file:com.cloud9.netmusic.service.MediaService.java

private Notification getNotification() {
    RemoteViews remoteViews;// w w  w.ja va 2 s  .  c  om
    final int PAUSE_FLAG = 0x1;
    final int NEXT_FLAG = 0x2;
    final int STOP_FLAG = 0x3;
    final String albumName = getAlbumName();
    final String artistName = getArtistName();
    final boolean isPlaying = isPlaying();

    remoteViews = new RemoteViews(this.getPackageName(), R.layout.notification);
    String text = TextUtils.isEmpty(albumName) ? artistName : artistName + " - " + albumName;
    remoteViews.setTextViewText(R.id.title, getTrackName());
    remoteViews.setTextViewText(R.id.text, text);

    //action?  ?flag??
    Intent pauseIntent = new Intent(TOGGLEPAUSE_ACTION);
    pauseIntent.putExtra("FLAG", PAUSE_FLAG);
    PendingIntent pausePIntent = PendingIntent.getBroadcast(this, 0, pauseIntent, 0);
    remoteViews.setImageViewResource(R.id.iv_pause,
            isPlaying ? R.drawable.note_btn_pause : R.drawable.note_btn_play);
    remoteViews.setOnClickPendingIntent(R.id.iv_pause, pausePIntent);

    Intent nextIntent = new Intent(NEXT_ACTION);
    nextIntent.putExtra("FLAG", NEXT_FLAG);
    PendingIntent nextPIntent = PendingIntent.getBroadcast(this, 0, nextIntent, 0);
    remoteViews.setOnClickPendingIntent(R.id.iv_next, nextPIntent);

    Intent preIntent = new Intent(STOP_ACTION);
    preIntent.putExtra("FLAG", STOP_FLAG);
    PendingIntent prePIntent = PendingIntent.getBroadcast(this, 0, preIntent, 0);
    remoteViews.setOnClickPendingIntent(R.id.iv_stop, prePIntent);

    //        PendingIntent pendingIntent = PendingIntent.getActivity(this.getApplicationContext(), 0,
    //                new Intent(this.getApplicationContext(), PlayingActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
    final Intent nowPlayingIntent = new Intent();
    //nowPlayingIntent.setAction("com.cloud9.netmusic.LAUNCH_NOW_PLAYING_ACTION");
    nowPlayingIntent.setComponent(new ComponentName("com.wm.remusic", "PlayingActivity"));
    nowPlayingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent clickIntent = PendingIntent.getBroadcast(this, 0, nowPlayingIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent click = PendingIntent.getActivity(this, 0, nowPlayingIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    final Bitmap bitmap = ImageUtils.getArtworkQuick(this, getAlbumId(), 160, 160);
    if (bitmap != null) {
        remoteViews.setImageViewBitmap(R.id.image, bitmap);
        // remoteViews.setImageViewUri(R.id.image, MusicUtils.getAlbumUri(this, getAudioId()));
        mNoBit = null;

    } else if (!isTrackLocal()) {
        if (mNoBit != null) {
            remoteViews.setImageViewBitmap(R.id.image, mNoBit);
            mNoBit = null;

        } else {
            Uri uri = null;
            if (getAlbumPath() != null) {
                try {
                    uri = Uri.parse(getAlbumPath());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (getAlbumPath() == null || uri == null) {
                mNoBit = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder_disk_210);
                updateNotification();
            } else {
                ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(uri)
                        .setProgressiveRenderingEnabled(true).build();
                ImagePipeline imagePipeline = Fresco.getImagePipeline();
                DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline
                        .fetchDecodedImage(imageRequest, MediaService.this);

                dataSource.subscribe(new BaseBitmapDataSubscriber() {

                    @Override
                    public void onNewResultImpl(@Nullable Bitmap bitmap) {
                        // You can use the bitmap in only limited ways
                        // No need to do any cleanup.
                        if (bitmap != null) {
                            mNoBit = bitmap;
                        }
                        updateNotification();
                    }

                    @Override
                    public void onFailureImpl(DataSource dataSource) {
                        // No cleanup required here.
                        mNoBit = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder_disk_210);
                        updateNotification();
                    }
                }, CallerThreadExecutor.getInstance());
            }
        }

    } else {
        remoteViews.setImageViewResource(R.id.image, R.drawable.placeholder_disk_210);
    }

    if (mNotificationPostTime == 0) {
        mNotificationPostTime = System.currentTimeMillis();
    }
    if (mNotification == null) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContent(remoteViews)
                .setSmallIcon(R.drawable.ic_notification).setContentIntent(click)
                .setWhen(mNotificationPostTime);
        if (CommonUtils.isJellyBeanMR1()) {
            builder.setShowWhen(false);
        }
        mNotification = builder.build();
    } else {
        mNotification.contentView = remoteViews;
    }

    return mNotification;
}

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

@SuppressLint("InlinedApi")
private void showExtraNotifications(NotificationCompat.Builder notificationBuilder, boolean notifyAboutLast) {
    // TODO: support Android wear by calling this function above from showOrUpdateNotification
    if (Build.VERSION.SDK_INT < 18) {
        return;/*  www . ja  va  2 s  .  c  om*/
    }

    ArrayList<Long> sortedDialogs = new ArrayList<>();
    HashMap<Long, ArrayList<MessageObject>> messagesByDialogs = new HashMap<>();
    for (int a = 0; a < pushMessages.size(); a++) {
        MessageObject messageObject = pushMessages.get(a);
        long dialog_id = messageObject.getDialogId();
        if ((int) dialog_id == 0) {
            continue;
        }

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

    HashMap<Long, Integer> oldIdsWear = new HashMap<>();
    oldIdsWear.putAll(wearNotificationsIds);
    wearNotificationsIds.clear();

    HashMap<Long, Integer> oldIdsAuto = new HashMap<>();
    oldIdsAuto.putAll(autoNotificationsIds);
    autoNotificationsIds.clear();

    for (int b = 0; b < sortedDialogs.size(); b++) {
        long dialog_id = sortedDialogs.get(b);
        ArrayList<MessageObject> messageObjects = messagesByDialogs.get(dialog_id);
        int max_id = messageObjects.get(0).getId();
        int max_date = messageObjects.get(0).messageOwner.date;
        TLRPC.Chat chat = null;
        TLRPC.User user = null;
        String name;
        if (dialog_id > 0) {
            user = MessagesController.getInstance().getUser((int) dialog_id);
            if (user == null) {
                continue;
            }
        } else {
            /*chat = MessagesController.getInstance().getChat(-(int)dialog_id);
            if (chat == null) {*/
            continue;
            //}
        }
        TLRPC.FileLocation photoPath = null;
        if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
            name = mContext.getString(R.string.AppName);
        } else {
            if (chat != null) {
                name = chat.title;
            } else {
                name = UserObject.getUserName(user);
            }
            /*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.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;
            }
            }*/
        }

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

        Integer notificationIdAuto = oldIdsAuto.get(dialog_id);
        if (notificationIdAuto == null) {
            notificationIdAuto = autoNotificationId++;
        } else {
            oldIdsAuto.remove(dialog_id);
        }

        NotificationCompat.CarExtender.UnreadConversation.Builder unreadConvBuilder = new NotificationCompat.CarExtender.UnreadConversation.Builder(
                name).setLatestTimestamp((long) max_date * 1000);

        Intent msgHeardIntent = new Intent();
        msgHeardIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        msgHeardIntent.setAction("com.b44t.messenger.ACTION_MESSAGE_HEARD");
        msgHeardIntent.putExtra("dialog_id", dialog_id);
        msgHeardIntent.putExtra("max_id", max_id);
        PendingIntent msgHeardPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext,
                notificationIdAuto, msgHeardIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        unreadConvBuilder.setReadPendingIntent(msgHeardPendingIntent);

        NotificationCompat.Action wearReplyAction = null;

        if (/*!ChatObject.isChannel(chat) &&*/ !AndroidUtilities.needShowPasscode(false)
                && !UserConfig.isWaitingForPasscodeEnter) {
            Intent msgReplyIntent = new Intent();
            msgReplyIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
            msgReplyIntent.setAction("com.b44t.messenger.ACTION_MESSAGE_REPLY");
            msgReplyIntent.putExtra("dialog_id", dialog_id);
            msgReplyIntent.putExtra("max_id", max_id);
            PendingIntent msgReplyPendingIntent = PendingIntent.getBroadcast(
                    ApplicationLoader.applicationContext, notificationIdAuto, msgReplyIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            RemoteInput remoteInputAuto = new RemoteInput.Builder(NotificationsController.EXTRA_VOICE_REPLY)
                    .setLabel(mContext.getString(R.string.Reply)).build();
            unreadConvBuilder.setReplyAction(msgReplyPendingIntent, remoteInputAuto);

            Intent replyIntent = new Intent(ApplicationLoader.applicationContext, WearReplyReceiver.class);
            replyIntent.putExtra("dialog_id", dialog_id);
            replyIntent.putExtra("max_id", max_id);
            PendingIntent replyPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext,
                    notificationIdWear, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            RemoteInput remoteInputWear = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
                    .setLabel(mContext.getString(R.string.Reply)).build();
            String replyToString;
            if (chat != null) {
                replyToString = String.format(mContext.getString(R.string.ReplyToGroup), name);
            } else {
                replyToString = String.format(mContext.getString(R.string.ReplyToContact), name);
            }
            wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon, replyToString,
                    replyPendingIntent).addRemoteInput(remoteInputWear).build();
        }

        String text = "";
        for (int a = messageObjects.size() - 1; a >= 0; a--) {
            MessageObject messageObject = messageObjects.get(a);
            String message = getStringForMessage(messageObject, ADD_GROUP | ADD_USER);
            if (message == null) {
                continue;
            }
            /*if (chat != null) {
            message = message.replace(" @ " + name, "");
            } else {
            message = message.replace(name + ": ", "").replace(name + " ", "");
            }*/
            if (text.length() > 0) {
                text += "\n\n";
            }
            text += message;

            unreadConvBuilder.addMessage(message);
        }

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

        NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();
        if (wearReplyAction != null) {
            wearableExtender.addAction(wearReplyAction);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                ApplicationLoader.applicationContext).setContentTitle(name)
                        .setSmallIcon(R.drawable.notification).setGroup("messages").setContentText(text)
                        .setAutoCancel(true).setColor(Theme.ACTION_BAR_COLOR).setGroupSummary(false)
                        .setContentIntent(contentIntent).extend(wearableExtender)
                        .extend(new NotificationCompat.CarExtender()
                                .setUnreadConversation(unreadConvBuilder.build()))
                        .setCategory(NotificationCompat.CATEGORY_MESSAGE);
        /*if (photoPath != null) {
        BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(photoPath, null, "50_50");
        if (img != null) {
            builder.setLargeIcon(img.getBitmap());
        }
        }*/

        notificationManager.notify(notificationIdWear, builder.build());
        wearNotificationsIds.put(dialog_id, notificationIdWear);
    }

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

From source file:no.nordicsemi.android.nrftoolbox.dfu.DfuService.java

/**
 * Creates or updates the notification in the Notification Manager. Sends broadcast with given progress or error state to the activity.
 * /*from   w ww .j  a va  2  s.c om*/
 * @param progress
 *            the current progress state or an error number, can be one of {@link #PROGRESS_CONNECTING}, {@link #PROGRESS_STARTING}, {@link #PROGRESS_VALIDATING}, {@link #PROGRESS_DISCONNECTING},
 *            {@link #PROGRESS_COMPLETED} or {@link #ERROR_FILE_CLOSED}, {@link #ERROR_FILE_INVALID} , etc
 */
private void updateProgressNotification(final int progress) {
    final String deviceAddress = mDeviceAddress;
    final String deviceName = mDeviceName != null ? mDeviceName : getString(R.string.dfu_unknown_name);

    final Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.stat_dfu);

    final Notification.Builder builder = new Notification.Builder(this)
            .setSmallIcon(android.R.drawable.stat_sys_upload).setOnlyAlertOnce(true).setLargeIcon(largeIcon);
    switch (progress) {
    case PROGRESS_CONNECTING:
        builder.setOngoing(true).setContentTitle(getString(R.string.dfu_status_connecting))
                .setContentText(getString(R.string.dfu_status_connecting_msg, deviceName))
                .setProgress(100, 0, true);
        break;
    case PROGRESS_STARTING:
        builder.setOngoing(true).setContentTitle(getString(R.string.dfu_status_starting))
                .setContentText(getString(R.string.dfu_status_starting_msg, deviceName))
                .setProgress(100, 0, true);
        break;
    case PROGRESS_VALIDATING:
        builder.setOngoing(true).setContentTitle(getString(R.string.dfu_status_validating))
                .setContentText(getString(R.string.dfu_status_validating_msg, deviceName))
                .setProgress(100, 0, true);
        break;
    case PROGRESS_DISCONNECTING:
        builder.setOngoing(true).setContentTitle(getString(R.string.dfu_status_disconnecting))
                .setContentText(getString(R.string.dfu_status_disconnecting_msg, deviceName))
                .setProgress(100, 0, true);
        break;
    case PROGRESS_COMPLETED:
        builder.setOngoing(false).setContentTitle(getString(R.string.dfu_status_completed))
                .setContentText(getString(R.string.dfu_status_completed_msg)).setAutoCancel(true);
        break;
    case PROGRESS_ABORTED:
        builder.setOngoing(false).setContentTitle(getString(R.string.dfu_status_abored))
                .setContentText(getString(R.string.dfu_status_aborted_msg)).setAutoCancel(true);
        break;
    default:
        if (progress >= ERROR_MASK) {
            // progress is an error number
            builder.setOngoing(false).setContentTitle(getString(R.string.dfu_status_error))
                    .setContentText(getString(R.string.dfu_status_error_msg)).setAutoCancel(true);
        } else {
            // progress is in percents
            builder.setOngoing(true).setContentTitle(getString(R.string.dfu_status_uploading))
                    .setContentText(getString(R.string.dfu_status_uploading_msg, deviceName))
                    .setProgress(100, progress, false);
        }
    }
    // send progress or error broadcast
    if (progress < ERROR_MASK)
        sendProgressBroadcast(progress);
    else
        sendErrorBroadcast(progress);

    // We cannot set two activities at once (using PendingIntent.getActivities(...)) because we have to start the BluetoothLeService first. Service is created in DeviceListActivity.
    // When creating activities the parent Activity is not created, it's just inserted to the history stack.
    final Intent intent = new Intent(this, NotificationActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(DfuActivity.EXTRA_DEVICE_ADDRESS, deviceAddress);
    intent.putExtra(DfuActivity.EXTRA_DEVICE_NAME, deviceName);
    intent.putExtra(DfuActivity.EXTRA_PROGRESS, progress); // this may contains ERROR_CONNECTION_MASK bit!
    if (mLogSession != null)
        intent.putExtra(DfuActivity.EXTRA_LOG_URI, mLogSession.getSessionUri());
    final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);

    final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(NOTIFICATION_ID, builder.build());
}