Example usage for android.graphics.drawable BitmapDrawable getBitmap

List of usage examples for android.graphics.drawable BitmapDrawable getBitmap

Introduction

In this page you can find the example usage for android.graphics.drawable BitmapDrawable getBitmap.

Prototype

public final Bitmap getBitmap() 

Source Link

Document

Returns the bitmap used by this drawable to render.

Usage

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

@SuppressLint("InlinedApi")
private void showExtraNotifications(NotificationCompat.Builder notificationBuilder, boolean notifyAboutLast) {
    if (Build.VERSION.SDK_INT < 18) {
        return;//from w  ww.  java 2 s  .  c o  m
    }

    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();

    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 = LocaleController.getString("AppName", 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 notificationId = oldIdsWear.get(dialog_id);
        if (notificationId == null) {
            notificationId = (int) dialog_id;
        } else {
            oldIdsWear.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("kr.toptalk.messenger.ACTION_MESSAGE_HEARD");
        msgHeardIntent.putExtra("dialog_id", dialog_id);
        msgHeardIntent.putExtra("max_id", max_id);
        PendingIntent msgHeardPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext,
                notificationId, 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("kr.toptalk.messenger.ACTION_MESSAGE_REPLY");
            msgReplyIntent.putExtra("dialog_id", dialog_id);
            msgReplyIntent.putExtra("max_id", max_id);
            PendingIntent msgReplyPendingIntent = PendingIntent.getBroadcast(
                    ApplicationLoader.applicationContext, notificationId, msgReplyIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            RemoteInput remoteInputAuto = new RemoteInput.Builder(NotificationsController.EXTRA_VOICE_REPLY)
                    .setLabel(LocaleController.getString("Reply", 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,
                    notificationId, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            RemoteInput remoteInputWear = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
                    .setLabel(LocaleController.getString("Reply", R.string.Reply)).build();
            String replyToString;
            if (chat != null) {
                replyToString = LocaleController.formatString("ReplyToGroup", R.string.ReplyToGroup, name);
            } else {
                replyToString = LocaleController.formatString("ReplyToUser", R.string.ReplyToUser, name);
            }
            wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon, replyToString,
                    replyPendingIntent).addRemoteInput(remoteInputWear).build();
        }

        Integer count = pushDialogs.get(dialog_id);
        if (count == null) {
            count = 0;
        }
        NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(null)
                .setConversationTitle(String.format("%1$s (%2$s)", name, LocaleController
                        .formatPluralString("NewMessages", Math.max(count, messageObjects.size()))));

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

            unreadConvBuilder.addMessage(message);
            messagingStyle.addMessage(message, ((long) messageObject.messageOwner.date) * 1000, null);
        }

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

        NotificationCompat.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).setNumber(messageObjects.size()).setColor(0xff2ca5e0)
                        .setGroupSummary(false).setWhen(((long) messageObjects.get(0).messageOwner.date) * 1000)
                        .setStyle(messagingStyle).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());
            } 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) {
                        builder.setLargeIcon(bitmap);
                    }
                } catch (Throwable e) {
                    //ignore
                }
            }
        }

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

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

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

From source file:net.bluehack.messenger.NotificationsController.java

@SuppressLint("InlinedApi")
private void showExtraNotifications(NotificationCompat.Builder notificationBuilder, boolean notifyAboutLast) {
    if (Build.VERSION.SDK_INT < 18) {
        return;/*  ww w  .  j a  va2s  .  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();

    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 = LocaleController.getString("AppName", 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 notificationId = oldIdsWear.get(dialog_id);
        if (notificationId == null) {
            notificationId = (int) dialog_id;
        } else {
            oldIdsWear.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("net.bluehack.messenger.ACTION_MESSAGE_HEARD");
        msgHeardIntent.putExtra("dialog_id", dialog_id);
        msgHeardIntent.putExtra("max_id", max_id);
        PendingIntent msgHeardPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext,
                notificationId, 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("net.bluehack.messenger.ACTION_MESSAGE_REPLY");
            msgReplyIntent.putExtra("dialog_id", dialog_id);
            msgReplyIntent.putExtra("max_id", max_id);
            PendingIntent msgReplyPendingIntent = PendingIntent.getBroadcast(
                    ApplicationLoader.applicationContext, notificationId, msgReplyIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            RemoteInput remoteInputAuto = new RemoteInput.Builder(NotificationsController.EXTRA_VOICE_REPLY)
                    .setLabel(LocaleController.getString("Reply", 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,
                    notificationId, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            RemoteInput remoteInputWear = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
                    .setLabel(LocaleController.getString("Reply", R.string.Reply)).build();
            String replyToString;
            if (chat != null) {
                replyToString = LocaleController.formatString("ReplyToGroup", R.string.ReplyToGroup, name);
            } else {
                replyToString = LocaleController.formatString("ReplyToUser", R.string.ReplyToUser, name);
            }
            wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon, replyToString,
                    replyPendingIntent).addRemoteInput(remoteInputWear).build();
        }

        Integer count = pushDialogs.get(dialog_id);
        if (count == null) {
            count = 0;
        }
        NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(null)
                .setConversationTitle(String.format("%1$s (%2$s)", name, LocaleController
                        .formatPluralString("NewMessages", Math.max(count, messageObjects.size()))));

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

            unreadConvBuilder.addMessage(message);
            messagingStyle.addMessage(message, ((long) messageObject.messageOwner.date) * 1000, null);
        }

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

        NotificationCompat.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).setNumber(messageObjects.size()).setColor(0xff2ca5e0)
                        .setGroupSummary(false).setWhen(((long) messageObjects.get(0).messageOwner.date) * 1000)
                        .setStyle(messagingStyle).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());
            } 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) {
                        builder.setLargeIcon(bitmap);
                    }
                } catch (Throwable e) {
                    //ignore
                }
            }
        }

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

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

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

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

@SuppressLint("InlinedApi")
private void showExtraNotifications(NotificationCompat.Builder notificationBuilder, boolean notifyAboutLast) {
    if (Build.VERSION.SDK_INT < 18) {
        return;/*from   w  w w.  jav  a  2 s . com*/
    }

    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();

    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 = LocaleController.getString("AppName", 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 notificationId = oldIdsWear.get(dialog_id);
        if (notificationId == null) {
            notificationId = (int) dialog_id;
        } else {
            oldIdsWear.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.ferdi2005.secondgram.ACTION_MESSAGE_HEARD");
        msgHeardIntent.putExtra("dialog_id", dialog_id);
        msgHeardIntent.putExtra("max_id", max_id);
        PendingIntent msgHeardPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext,
                notificationId, msgHeardIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        unreadConvBuilder.setReadPendingIntent(msgHeardPendingIntent);

        NotificationCompat.Action wearReplyAction = null;

        if ((!ChatObject.isChannel(chat) || chat != null && chat.megagroup)
                && !AndroidUtilities.needShowPasscode(false) && !UserConfig.isWaitingForPasscodeEnter) {
            Intent msgReplyIntent = new Intent();
            msgReplyIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
            msgReplyIntent.setAction("com.ferdi2005.secondgram.ACTION_MESSAGE_REPLY");
            msgReplyIntent.putExtra("dialog_id", dialog_id);
            msgReplyIntent.putExtra("max_id", max_id);
            PendingIntent msgReplyPendingIntent = PendingIntent.getBroadcast(
                    ApplicationLoader.applicationContext, notificationId, msgReplyIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            RemoteInput remoteInputAuto = new RemoteInput.Builder(NotificationsController.EXTRA_VOICE_REPLY)
                    .setLabel(LocaleController.getString("Reply", 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,
                    notificationId, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            RemoteInput remoteInputWear = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
                    .setLabel(LocaleController.getString("Reply", R.string.Reply)).build();
            String replyToString;
            if (chat != null) {
                replyToString = LocaleController.formatString("ReplyToGroup", R.string.ReplyToGroup, name);
            } else {
                replyToString = LocaleController.formatString("ReplyToUser", R.string.ReplyToUser, name);
            }
            wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon, replyToString,
                    replyPendingIntent).setAllowGeneratedReplies(true).addRemoteInput(remoteInputWear).build();
        }

        Integer count = pushDialogs.get(dialog_id);
        if (count == null) {
            count = 0;
        }
        NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(null)
                .setConversationTitle(String.format("%1$s (%2$s)", name, LocaleController
                        .formatPluralString("NewMessages", Math.max(count, messageObjects.size()))));

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

            unreadConvBuilder.addMessage(message);
            messagingStyle.addMessage(message, ((long) messageObject.messageOwner.date) * 1000, null);
        }

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

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

        String dismissalID = null;
        if (chat != null)
            dismissalID = "tgchat" + chat.id + "_" + max_id;
        else if (user != null)
            dismissalID = "tguser" + user.id + "_" + max_id;

        wearableExtender.setDismissalId(dismissalID);

        NotificationCompat.WearableExtender summaryExtender = new NotificationCompat.WearableExtender();
        summaryExtender.setDismissalId("summary_" + dismissalID);
        notificationBuilder.extend(summaryExtender);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                ApplicationLoader.applicationContext).setContentTitle(name)
                        .setSmallIcon(R.drawable.notification).setGroup("messages").setContentText(text)
                        .setAutoCancel(true).setNumber(messageObjects.size()).setColor(0xff2ca5e0)
                        .setGroupSummary(false).setWhen(((long) messageObjects.get(0).messageOwner.date) * 1000)
                        .setStyle(messagingStyle).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());
            } 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) {
                        builder.setLargeIcon(bitmap);
                    }
                } catch (Throwable e) {
                    //ignore
                }
            }
        }

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

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

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

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

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

        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();/* w w w. j  av a 2 s  .com*/
        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:edu.usf.cutr.opentripplanner.android.fragments.MainFragment.java

/**
 * Draws the route on the map./*from   www .jav  a 2s. c om*/
 * <p>
 * To indicate the full route a polyline will be drawn using all points in
 * itinerary.
 * <p>
 * On each method of transportation change a mode marker will be added.
 * <p>
 * Mode marker for transit step will display stop name, departure time and
 * headsign.
 * Mode marker for walk/bike connection, guidance to next point and distance and time
 * to get there.
 * <p>
 * Previous routes are removed from the map.
 *
 * @param itinerary     the information to be drawn
 * @param animateCamera if true map will be zoomed to exactly fit the route
 *                      after the drawing
 */
public void showRouteOnMap(List<Leg> itinerary, boolean animateCamera) {
    Log.v(OTPApp.TAG, "(TripRequest) legs size = " + Integer.toString(itinerary.size()));
    if (mRoute != null) {
        for (Polyline legLine : mRoute) {
            legLine.remove();
        }
        mRoute.clear();
    }
    if (mModeMarkers != null) {
        for (Marker modeMarker : mModeMarkers) {
            modeMarker.remove();
        }
    }
    mRoute = new ArrayList<Polyline>();
    mModeMarkers = new ArrayList<Marker>();
    Marker firstTransitMarker = null;

    if (!itinerary.isEmpty()) {
        LatLngBounds.Builder boundsCreator = LatLngBounds.builder();

        int stepIndex = 0;

        for (Leg leg : itinerary) {
            stepIndex++;

            List<LatLng> points = LocationUtil.decodePoly(leg.legGeometry.getPoints());

            MarkerOptions modeMarkerOption = new MarkerOptions().position(points.get(0));

            float scaleFactor = getResources().getFraction(R.fraction.scaleFactor, 1, 1);

            Drawable drawable = getResources().getDrawable(getPathIcon(leg.mode));
            if (drawable != null) {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable.getCurrent();
                Bitmap bitmap = bitmapDrawable.getBitmap();
                Bitmap bitmapHalfSize = Bitmap.createScaledBitmap(bitmap,
                        (int) (bitmap.getWidth() / scaleFactor), (int) (bitmap.getHeight() / scaleFactor),
                        false);
                modeMarkerOption.icon(BitmapDescriptorFactory.fromBitmap(bitmapHalfSize));
            } else {
                Log.e(OTPApp.TAG, "Error obtaining drawable to add mode icons to the map");
            }

            TraverseMode traverseMode = TraverseMode.valueOf(leg.mode);

            if (traverseMode.isTransit()) {
                modeMarkerOption.title(stepIndex + ". "
                        + ConversionUtils.getRouteShortNameSafe(leg.getRouteShortName(), leg.getRouteLongName(),
                                mApplicationContext)
                        + " " + getResources().getString(R.string.map_markers_connector_before_stop) + " "
                        + DirectionsGenerator.getLocalizedStreetName(leg.getFrom().name,
                                mApplicationContext.getResources()));
                String modeMarkerSnippet = ConversionUtils.getTimeWithContext(mApplicationContext,
                        leg.getAgencyTimeZoneOffset(), Long.parseLong(leg.getStartTime()), false);
                if (leg.getHeadsign() != null) {
                    modeMarkerSnippet += " " + getResources().getString(R.string.step_by_step_non_transit_to)
                            + " " + leg.getHeadsign();
                }
                modeMarkerOption.snippet(modeMarkerSnippet);
            } else {
                if (traverseMode.equals(TraverseMode.WALK)) {
                    modeMarkerOption.title(stepIndex + ". "
                            + getResources().getString(R.string.map_markers_mode_walk_action) + " "
                            + getResources().getString(R.string.map_markers_connector_before_destination) + " "
                            + DirectionsGenerator.getLocalizedStreetName(leg.getTo().name,
                                    mApplicationContext.getResources()));
                } else if (traverseMode.equals(TraverseMode.BICYCLE)) {
                    modeMarkerOption.title(stepIndex + ". "
                            + getResources().getString(R.string.map_markers_mode_bicycle_action) + " "
                            + getResources().getString(R.string.map_markers_connector_before_destination) + " "
                            + DirectionsGenerator.getLocalizedStreetName(leg.getTo().name,
                                    mApplicationContext.getResources()));
                }
                modeMarkerOption.snippet(ConversionUtils.getFormattedDurationTextNoSeconds(leg.duration / 1000,
                        mApplicationContext) + " " + "-" + " "
                        + ConversionUtils.getFormattedDistance(leg.getDistance(), mApplicationContext));
            }

            Marker modeMarker = mMap.addMarker(modeMarkerOption);
            mModeMarkers.add(modeMarker);

            if (traverseMode.isTransit()) {
                //because on transit two step-by-step indications are generated (get on / get off)
                stepIndex++;

                if (firstTransitMarker == null) {
                    firstTransitMarker = modeMarker;
                    firstTransitMarker.showInfoWindow();
                }
            }
            PolylineOptions options = new PolylineOptions().addAll(points).width(5 * scaleFactor)
                    .color(OTPApp.COLOR_ROUTE_LINE);
            Polyline routeLine = mMap.addPolyline(options);
            mRoute.add(routeLine);
            for (LatLng point : points) {
                boundsCreator.include(point);
            }
        }
        if (animateCamera) {
            mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(boundsCreator.build(),
                    getResources().getInteger(R.integer.default_padding)));
        }
    }
}

From source file:com.connectsdk.service.WebOSTVService.java

private void sendToast(JSONObject payload, ResponseListener<Object> listener) {
    if (!payload.has("iconData")) {
        Context context = DiscoveryManager.getInstance().getContext();

        try {//from   w w  w  .j av a  2  s.co  m
            Drawable drawable = context.getPackageManager().getApplicationIcon(context.getPackageName());

            if (drawable != null) {
                BitmapDrawable bitDw = ((BitmapDrawable) drawable);
                Bitmap bitmap = bitDw.getBitmap();

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

                byte[] bitmapByte = stream.toByteArray();
                bitmapByte = Base64.encode(bitmapByte, Base64.NO_WRAP);
                String bitmapData = new String(bitmapByte);

                payload.put("iconData", bitmapData);
                payload.put("iconExtension", "png");
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    String uri = "palm://system.notifications/createToast";
    ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(this, uri,
            payload, true, listener);
    request.send();
}

From source file:com.kll.collect.android.activities.FormEntryActivity.java

/**
 * Creates a view given the View type and an event
 *
 * @param event/*from ww w.j  a v  a 2  s. c  om*/
 * @param advancingPage
 *            -- true if this results from advancing through the form
 * @return newly created View
 */
private View createView(int event, boolean advancingPage, int swipeCase) {
    FormController formController = Collect.getInstance().getFormController();
    /*   setTitle(getString(R.string.app_name) + " > "
    + formController.getFormTitle());*/
    int questioncount = formController.getFormDef().getDeepChildCount();

    switch (event) {
    case FormEntryController.EVENT_BEGINNING_OF_FORM:
        progressValue = 0.0;
        progressUpdate(progressValue, questioncount);
        View startView = View.inflate(this, R.layout.form_entry_start, null);
        /*setTitle(getString(R.string.app_name) + " > "
              + formController.getFormTitle());*/

        Drawable image = null;
        File mediaFolder = formController.getMediaFolder();
        String mediaDir = mediaFolder.getAbsolutePath();
        BitmapDrawable bitImage = null;
        // attempt to load the form-specific logo...
        // this is arbitrarily silly
        bitImage = new BitmapDrawable(getResources(), mediaDir + File.separator + "form_logo.png");

        if (bitImage != null && bitImage.getBitmap() != null && bitImage.getIntrinsicHeight() > 0
                && bitImage.getIntrinsicWidth() > 0) {
            image = bitImage;
        }

        if (image == null) {
            // show the opendatakit zig...
            // image =
            // getResources().getDrawable(R.drawable.opendatakit_zig);
            ((ImageView) startView.findViewById(R.id.form_start_bling)).setVisibility(View.GONE);
        } else {
            ImageView v = ((ImageView) startView.findViewById(R.id.form_start_bling));
            v.setImageDrawable(image);
            v.setContentDescription(formController.getFormTitle());
        }

        // change start screen based on navigation prefs
        String navigationChoice = PreferenceManager.getDefaultSharedPreferences(this)
                .getString(PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.KEY_NAVIGATION);
        Boolean useSwipe = false;
        Boolean useButtons = false;
        ImageView ia = ((ImageView) startView.findViewById(R.id.image_advance));
        ImageView ib = ((ImageView) startView.findViewById(R.id.image_backup));
        TextView ta = ((TextView) startView.findViewById(R.id.text_advance));
        TextView tb = ((TextView) startView.findViewById(R.id.text_backup));
        TextView d = ((TextView) startView.findViewById(R.id.description));

        if (navigationChoice != null) {
            if (navigationChoice.contains(PreferencesActivity.NAVIGATION_SWIPE)) {
                useSwipe = true;
            }
            if (navigationChoice.contains(PreferencesActivity.NAVIGATION_BUTTONS)) {
                useButtons = true;
            }
        }
        if (useSwipe && !useButtons) {
            d.setText(getString(R.string.swipe_instructions, formController.getFormTitle()));
        } else if (useButtons && !useSwipe) {
            ia.setVisibility(View.GONE);
            ib.setVisibility(View.GONE);
            ta.setVisibility(View.GONE);
            tb.setVisibility(View.GONE);
            d.setText(getString(R.string.buttons_instructions, formController.getFormTitle()));
        } else {
            d.setText(getString(R.string.swipe_buttons_instructions, formController.getFormTitle()));
        }

        if (mBackButton.isShown()) {
            mBackButton.setEnabled(false);
        }
        if (mNextButton.isShown()) {
            mNextButton.setEnabled(true);
        }

        return startView;
    case FormEntryController.EVENT_END_OF_FORM:
        progressValue = questioncount;
        progressUpdate(progressValue, questioncount);
        View endView = View.inflate(this, R.layout.form_entry_end, null);

        ((ImageView) endView.findViewById(R.id.completed))
                .setImageDrawable(getResources().getDrawable(R.drawable.complete_tick));
        ((TextView) endView.findViewById(R.id.description))
                .setText(getString(R.string.save_enter_data_description, formController.getFormTitle()));

        // checkbox for if finished or ready to send
        final CheckBox instanceComplete = ((CheckBox) endView.findViewById(R.id.mark_finished));
        instanceComplete.setChecked(isInstanceComplete(true));

        if (!mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_MARK_AS_FINALIZED, true)) {
            instanceComplete.setVisibility(View.GONE);
        }

        // edittext to change the displayed name of the instance
        final EditText saveAs = (EditText) endView.findViewById(R.id.save_name);

        // disallow carriage returns in the name
        InputFilter returnFilter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                    int dend) {
                for (int i = start; i < end; i++) {
                    if (Character.getType((source.charAt(i))) == Character.CONTROL) {
                        return "";
                    }
                }
                return null;
            }
        };
        saveAs.setFilters(new InputFilter[] { returnFilter });
        String saveName = getSaveName();

        if (saveName == null) {
            // no meta/instanceName field in the form -- see if we have a
            // name for this instance from a previous save attempt...
            if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) {
                Uri instanceUri = getIntent().getData();
                Cursor instance = null;
                try {
                    instance = getContentResolver().query(instanceUri, null, null, null, null);
                    if (instance.getCount() == 1) {
                        instance.moveToFirst();
                        saveName = instance.getString(instance.getColumnIndex(InstanceColumns.DISPLAY_NAME));
                    }
                } finally {
                    if (instance != null) {
                        instance.close();
                    }
                }
            }
            if (saveName == null) {
                // last resort, default to the form title
                saveName = formController.getFormTitle();
            }
            // present the prompt to allow user to name the form
            TextView sa = (TextView) endView.findViewById(R.id.save_form_as);
            sa.setVisibility(View.VISIBLE);
            saveAs.setText(saveName);
            saveAs.setEnabled(true);
            saveAs.setVisibility(View.VISIBLE);
        } else {
            // if instanceName is defined in form, this is the name -- no
            // revisions
            // display only the name, not the prompt, and disable edits
            TextView sa = (TextView) endView.findViewById(R.id.save_form_as);
            sa.setVisibility(View.GONE);
            saveAs.setText(saveName);
            saveAs.setEnabled(false);
            saveAs.setBackgroundColor(Color.WHITE);
            saveAs.setVisibility(View.VISIBLE);
        }

        // override the visibility settings based upon admin preferences
        if (!mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_SAVE_AS, true)) {
            saveAs.setVisibility(View.GONE);
            TextView sa = (TextView) endView.findViewById(R.id.save_form_as);
            sa.setVisibility(View.GONE);
        }

        // Create 'save' button
        ((Button) endView.findViewById(R.id.save_exit_button)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Collect.getInstance().getActivityLogger().logInstanceAction(this, "createView.saveAndExit",
                        instanceComplete.isChecked() ? "saveAsComplete" : "saveIncomplete");
                // Form is marked as 'saved' here.
                if (saveAs.getText().length() < 1) {
                    Toast.makeText(FormEntryActivity.this, R.string.save_as_error, Toast.LENGTH_SHORT).show();
                } else {
                    saveDataToDisk(EXIT, instanceComplete.isChecked(), saveAs.getText().toString());
                }
            }
        });

        if (mBackButton.isShown()) {
            mBackButton.setEnabled(true);
        }
        if (mNextButton.isShown()) {
            mNextButton.setEnabled(false);
        }

        return endView;
    case FormEntryController.EVENT_QUESTION:
    case FormEntryController.EVENT_GROUP:
    case FormEntryController.EVENT_REPEAT:
        ODKView odkv = null;
        // should only be a group here if the event_group is a field-list
        try {
            double depth = (double) formController.getFormIndex().getDepth();
            double local_index = (double) formController.getFormIndex().getLocalIndex();
            double instance_index = (double) formController.getFormIndex().getInstanceIndex();
            Log.i("Question coint", Integer.toString(questioncount));

            Log.i("Depth", Integer.toString(formController.getFormIndex().getDepth()));
            Log.i("Local Index", Integer.toString(formController.getFormIndex().getLocalIndex()));
            Log.i("Instance Index", Integer.toString(formController.getFormIndex().getInstanceIndex()));

            if (swipeCase == NEXT) {

                Log.i("progressValue", Double.toString(progressValue));

            }
            if (swipeCase == PREVIOUS) {
                progressValue = progressValue - (1 - (instance_index * local_index / questioncount * depth));

                Log.i("progressValue", Double.toString(progressValue));
            }
            Log.i("progressValue", Double.toString(progressValue));
            progressUpdate(progressValue, questioncount);
            FormEntryPrompt[] prompts = formController.getQuestionPrompts();
            FormEntryCaption[] groups = formController.getGroupsForCurrentIndex();
            odkv = new ODKView(this, formController.getQuestionPrompts(), groups, advancingPage);
            Log.i(t, "created view for group "
                    + (groups.length > 0 ? groups[groups.length - 1].getLongText() : "[top]") + " "
                    + (prompts.length > 0 ? prompts[0].getQuestionText() : "[no question]"));
        } catch (RuntimeException e) {
            Log.e(t, e.getMessage(), e);
            // this is badness to avoid a crash.
            try {
                event = formController.stepToNextScreenEvent();
                createErrorDialog(e.getMessage(), DO_NOT_EXIT);
            } catch (JavaRosaException e1) {
                Log.e(t, e1.getMessage(), e1);
                createErrorDialog(e.getMessage() + "\n\n" + e1.getCause().getMessage(), DO_NOT_EXIT);
            }
            return createView(event, advancingPage, swipeCase);
        }

        // Makes a "clear answer" menu pop up on long-click
        for (QuestionWidget qw : odkv.getWidgets()) {
            if (!qw.getPrompt().isReadOnly()) {
                registerForContextMenu(qw);
            }
        }

        if (mBackButton.isShown() && mNextButton.isShown()) {
            mBackButton.setEnabled(true);
            mNextButton.setEnabled(true);
        }
        return odkv;
    default:
        Log.e(t, "Attempted to create a view that does not exist.");
        // this is badness to avoid a crash.
        try {
            event = formController.stepToNextScreenEvent();
            createErrorDialog(getString(R.string.survey_internal_error), EXIT);
        } catch (JavaRosaException e) {
            Log.e(t, e.getMessage(), e);
            createErrorDialog(e.getCause().getMessage(), EXIT);
        }
        return createView(event, advancingPage, swipeCase);
    }

}

From source file:org.mozilla.gecko.BrowserApp.java

@Override
public boolean onPrepareOptionsMenu(Menu aMenu) {
    if (aMenu == null)
        return false;

    // Hide the tab history panel when hardware menu button is pressed.
    TabHistoryFragment frag = (TabHistoryFragment) getSupportFragmentManager()
            .findFragmentByTag(TAB_HISTORY_FRAGMENT_TAG);
    if (frag != null) {
        frag.dismiss();//w  w  w  .ja  v  a 2  s.  c  o  m
    }

    if (!GeckoThread.checkLaunchState(GeckoThread.LaunchState.GeckoRunning)) {
        aMenu.findItem(R.id.settings).setEnabled(false);
        aMenu.findItem(R.id.help).setEnabled(false);
    }

    Tab tab = Tabs.getInstance().getSelectedTab();
    final MenuItem bookmark = aMenu.findItem(R.id.bookmark);
    final MenuItem reader = aMenu.findItem(R.id.reading_list);
    final MenuItem back = aMenu.findItem(R.id.back);
    final MenuItem forward = aMenu.findItem(R.id.forward);
    final MenuItem share = aMenu.findItem(R.id.share);
    final MenuItem quickShare = aMenu.findItem(R.id.quickshare);
    final MenuItem saveAsPDF = aMenu.findItem(R.id.save_as_pdf);
    final MenuItem charEncoding = aMenu.findItem(R.id.char_encoding);
    final MenuItem findInPage = aMenu.findItem(R.id.find_in_page);
    final MenuItem desktopMode = aMenu.findItem(R.id.desktop_mode);
    final MenuItem enterGuestMode = aMenu.findItem(R.id.new_guest_session);
    final MenuItem exitGuestMode = aMenu.findItem(R.id.exit_guest_session);

    // Only show the "Quit" menu item on pre-ICS, television devices,
    // or if the user has explicitly enabled the clear on shutdown pref.
    // (We check the pref last to save the pref read.)
    // In ICS+, it's easy to kill an app through the task switcher.
    final boolean visible = Versions.preICS || HardwareUtils.isTelevision() || !PrefUtils
            .getStringSet(GeckoSharedPrefs.forProfile(this), ClearOnShutdownPref.PREF, new HashSet<String>())
            .isEmpty();
    aMenu.findItem(R.id.quit).setVisible(visible);
    aMenu.findItem(R.id.logins).setVisible(AppConstants.NIGHTLY_BUILD);

    if (tab == null || tab.getURL() == null) {
        bookmark.setEnabled(false);
        reader.setEnabled(false);
        back.setEnabled(false);
        forward.setEnabled(false);
        share.setEnabled(false);
        quickShare.setEnabled(false);
        saveAsPDF.setEnabled(false);
        findInPage.setEnabled(false);

        // NOTE: Use MenuUtils.safeSetEnabled because some actions might
        // be on the BrowserToolbar context menu.
        if (Versions.feature11Plus) {
            // There is no page menu prior to v11 resources.
            MenuUtils.safeSetEnabled(aMenu, R.id.page, false);
        }
        MenuUtils.safeSetEnabled(aMenu, R.id.subscribe, false);
        MenuUtils.safeSetEnabled(aMenu, R.id.add_search_engine, false);
        MenuUtils.safeSetEnabled(aMenu, R.id.site_settings, false);
        MenuUtils.safeSetEnabled(aMenu, R.id.add_to_launcher, false);

        return true;
    }

    final boolean inGuestMode = GeckoProfile.get(this).inGuestMode();

    final boolean isAboutReader = AboutPages.isAboutReader(tab.getURL());
    bookmark.setEnabled(!isAboutReader);
    bookmark.setVisible(!inGuestMode);
    bookmark.setCheckable(true);
    bookmark.setChecked(tab.isBookmark());
    bookmark.setIcon(resolveBookmarkIconID(tab.isBookmark()));
    bookmark.setTitle(resolveBookmarkTitleID(tab.isBookmark()));

    reader.setEnabled(isAboutReader || !AboutPages.isAboutPage(tab.getURL()));
    reader.setVisible(!inGuestMode);
    reader.setCheckable(true);
    final boolean isPageInReadingList = tab.isInReadingList();
    reader.setChecked(isPageInReadingList);
    reader.setIcon(resolveReadingListIconID(isPageInReadingList));
    reader.setTitle(resolveReadingListTitleID(isPageInReadingList));

    back.setEnabled(tab.canDoBack());
    forward.setEnabled(tab.canDoForward());
    desktopMode.setChecked(tab.getDesktopMode());
    desktopMode.setIcon(
            tab.getDesktopMode() ? R.drawable.ic_menu_desktop_mode_on : R.drawable.ic_menu_desktop_mode_off);

    View backButtonView = MenuItemCompat.getActionView(back);

    if (backButtonView != null) {
        backButtonView.setOnLongClickListener(new Button.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Tab tab = Tabs.getInstance().getSelectedTab();
                if (tab != null) {
                    closeOptionsMenu();
                    return tabHistoryController.showTabHistory(tab, TabHistoryController.HistoryAction.BACK);
                }
                return false;
            }
        });
    }

    View forwardButtonView = MenuItemCompat.getActionView(forward);

    if (forwardButtonView != null) {
        forwardButtonView.setOnLongClickListener(new Button.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Tab tab = Tabs.getInstance().getSelectedTab();
                if (tab != null) {
                    closeOptionsMenu();
                    return tabHistoryController.showTabHistory(tab, TabHistoryController.HistoryAction.FORWARD);
                }
                return false;
            }
        });
    }

    String url = tab.getURL();
    if (AboutPages.isAboutReader(url)) {
        String urlFromReader = ReaderModeUtils.getUrlFromAboutReader(url);
        if (urlFromReader != null) {
            url = urlFromReader;
        }
    }

    // Disable share menuitem for about:, chrome:, file:, and resource: URIs
    final boolean shareVisible = RestrictedProfiles.isAllowed(this, Restriction.DISALLOW_SHARE);
    share.setVisible(shareVisible);
    final boolean shareEnabled = StringUtils.isShareableUrl(url) && shareVisible;
    share.setEnabled(shareEnabled);
    MenuUtils.safeSetEnabled(aMenu, R.id.downloads,
            RestrictedProfiles.isAllowed(this, Restriction.DISALLOW_DOWNLOADS));

    // NOTE: Use MenuUtils.safeSetEnabled because some actions might
    // be on the BrowserToolbar context menu.
    if (Versions.feature11Plus) {
        MenuUtils.safeSetEnabled(aMenu, R.id.page, !isAboutHome(tab));
    }
    MenuUtils.safeSetEnabled(aMenu, R.id.subscribe, tab.hasFeeds());
    MenuUtils.safeSetEnabled(aMenu, R.id.add_search_engine, tab.hasOpenSearch());
    MenuUtils.safeSetEnabled(aMenu, R.id.site_settings, !isAboutHome(tab));
    MenuUtils.safeSetEnabled(aMenu, R.id.add_to_launcher, !isAboutHome(tab));

    // Action providers are available only ICS+.
    if (Versions.feature14Plus) {
        quickShare.setVisible(shareVisible);
        quickShare.setEnabled(shareEnabled);

        // This provider also applies to the quick share menu item.
        final GeckoActionProvider provider = ((GeckoMenuItem) share).getGeckoActionProvider();
        if (provider != null) {
            Intent shareIntent = provider.getIntent();

            // For efficiency, the provider's intent is only set once
            if (shareIntent == null) {
                shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.setType("text/plain");
                provider.setIntent(shareIntent);
            }

            // Replace the existing intent's extras
            shareIntent.putExtra(Intent.EXTRA_TEXT, url);
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, tab.getDisplayTitle());
            shareIntent.putExtra(Intent.EXTRA_TITLE, tab.getDisplayTitle());
            shareIntent.putExtra(ShareDialog.INTENT_EXTRA_DEVICES_ONLY, true);

            // Clear the existing thumbnail extras so we don't share an old thumbnail.
            shareIntent.removeExtra("share_screenshot_uri");

            // Include the thumbnail of the page being shared.
            BitmapDrawable drawable = tab.getThumbnail();
            if (drawable != null) {
                Bitmap thumbnail = drawable.getBitmap();

                // Kobo uses a custom intent extra for sharing thumbnails.
                if (Build.MANUFACTURER.equals("Kobo") && thumbnail != null) {
                    File cacheDir = getExternalCacheDir();

                    if (cacheDir != null) {
                        File outFile = new File(cacheDir, "thumbnail.png");

                        try {
                            java.io.FileOutputStream out = new java.io.FileOutputStream(outFile);
                            thumbnail.compress(Bitmap.CompressFormat.PNG, 90, out);
                        } catch (FileNotFoundException e) {
                            Log.e(LOGTAG, "File not found", e);
                        }

                        shareIntent.putExtra("share_screenshot_uri", Uri.parse(outFile.getPath()));
                    }
                }
            }
        }
    }

    final boolean privateTabVisible = RestrictedProfiles.isAllowed(this, Restriction.DISALLOW_PRIVATE_BROWSING);
    MenuUtils.safeSetVisible(aMenu, R.id.new_private_tab, privateTabVisible);

    // Disable save as PDF for about:home and xul pages.
    saveAsPDF.setEnabled(!(isAboutHome(tab) || tab.getContentType().equals("application/vnd.mozilla.xul+xml")
            || tab.getContentType().startsWith("video/")));

    // Disable find in page for about:home, since it won't work on Java content.
    findInPage.setEnabled(!isAboutHome(tab));

    charEncoding.setVisible(GeckoPreferences.getCharEncodingState());

    if (mProfile.inGuestMode()) {
        exitGuestMode.setVisible(true);
    } else {
        enterGuestMode.setVisible(true);
    }

    if (!RestrictedProfiles.isAllowed(this, Restriction.DISALLOW_GUEST_BROWSING)) {
        MenuUtils.safeSetVisible(aMenu, R.id.new_guest_session, false);
    }

    if (!RestrictedProfiles.isAllowed(this, Restriction.DISALLOW_INSTALL_EXTENSION)) {
        MenuUtils.safeSetVisible(aMenu, R.id.addons, false);
    }

    return true;
}