Example usage for android.app NotificationManager notify

List of usage examples for android.app NotificationManager notify

Introduction

In this page you can find the example usage for android.app NotificationManager notify.

Prototype

public void notify(int id, Notification notification) 

Source Link

Document

Post a notification to be shown in the status bar.

Usage

From source file:com.adityarathi.muo.services.AudioPlaybackService.java

/**
 * Updates the current notification with info from the specified 
 * SongHelper object./*from www. j a v  a 2s .c  o  m*/
 */
public void updateNotification(SongHelper songHelper) {
    Notification notification = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
        notification = buildJBNotification(songHelper);
    else
        notification = buildICSNotification(songHelper);

    //Update the current notification.
    NotificationManager notifManager = (NotificationManager) mApp
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notifManager.notify(mNotificationId, notification);

}

From source file:com.akop.bach.service.XboxLiveServiceClient.java

private void notifyMessages(XboxLiveAccount account, long[] unreadMessages, List<Long> lastUnreadList) {
    NotificationManager mgr = getNotificationManager();
    Context context = getContext();

    int notificationId = 0x1000000 | ((int) account.getId() & 0xffffff);

    if (App.getConfig().logToConsole()) {
        String s = "";
        for (Object unr : lastUnreadList)
            s += unr.toString() + ",";

        App.logv("Currently unread (%d): %s", lastUnreadList.size(), s);

        s = "";/*from  w  w w .j  ava  2 s . c om*/
        for (Object unr : unreadMessages)
            s += unr.toString() + ",";

        App.logv("New unread (%d): %s", unreadMessages.length, s);
    }

    if (unreadMessages.length > 0) {
        int unreadCount = 0;
        for (Object unread : unreadMessages) {
            if (!lastUnreadList.contains(unread))
                unreadCount++;
        }

        if (App.getConfig().logToConsole())
            App.logv("%d computed new", unreadCount);

        if (unreadCount > 0) {
            String tickerTitle;
            String tickerText;

            if (unreadMessages.length == 1) {
                tickerTitle = context.getString(R.string.new_message);
                tickerText = context.getString(R.string.notify_message_pending_f, account.getScreenName(),
                        Messages.getSender(context, unreadMessages[0]));
            } else {
                tickerTitle = context.getString(R.string.new_messages);
                tickerText = context.getString(R.string.notify_messages_pending_f, account.getScreenName(),
                        unreadMessages.length, account.getDescription());
            }

            Notification notification = new Notification(R.drawable.xbox_stat_notify_message, tickerText,
                    System.currentTimeMillis());

            Intent intent = new Intent(context, MessageList.class);
            intent.putExtra("account", account);

            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);

            notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;

            if (unreadMessages.length > 1)
                notification.number = unreadMessages.length;

            notification.ledOnMS = DEFAULT_LIGHTS_ON_MS;
            notification.ledOffMS = DEFAULT_LIGHTS_OFF_MS;
            notification.ledARGB = DEFAULT_LIGHTS_COLOR;
            notification.sound = account.getRingtoneUri();

            if (account.isVibrationEnabled())
                notification.defaults |= Notification.DEFAULT_VIBRATE;

            notification.setLatestEventInfo(context, tickerTitle, tickerText, contentIntent);

            mgr.notify(notificationId, notification);
        }
    } else // No unread messages
    {
        mgr.cancel(notificationId);
    }
}

From source file:com.freshplanet.nativeExtensions.C2DMBroadcastReceiver.java

/**
 * Get the parameters from the message and create a notification from it.
 * @param context/*  w  w w . jav  a2 s. co m*/
 * @param intent
 */
public void handleMessage(Context context, Intent intent) {
    try {
        registerResources(context);
        extractColors(context);

        FREContext ctxt = C2DMExtension.context;

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

        // icon is required for notification.
        // @see http://developer.android.com/guide/practices/ui_guidelines/icon_design_status_bar.html

        int icon = notificationIcon;
        long when = System.currentTimeMillis();

        // json string

        String parameters = intent.getStringExtra("parameters");
        String facebookId = null;
        JSONObject object = null;
        if (parameters != null) {
            try {
                object = (JSONObject) new JSONTokener(parameters).nextValue();
            } catch (Exception e) {
                Log.d(TAG, "cannot parse the object");
            }
        }
        if (object != null && object.has("facebookId")) {
            facebookId = object.getString("facebookId");
        }

        CharSequence tickerText = intent.getStringExtra("tickerText");
        CharSequence contentTitle = intent.getStringExtra("contentTitle");
        CharSequence contentText = intent.getStringExtra("contentText");

        Intent notificationIntent = new Intent(context, Class.forName(context.getPackageName() + ".AppEntry"));

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        Notification notification = new Notification(icon, tickerText, when);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

        RemoteViews contentView = new RemoteViews(context.getPackageName(), customLayout);

        contentView.setTextViewText(customLayoutTitle, contentTitle);
        contentView.setTextViewText(customLayoutDescription, contentText);

        contentView.setTextColor(customLayoutTitle, notification_text_color);
        contentView.setFloat(customLayoutTitle, "setTextSize",
                notification_title_size_factor * notification_text_size);
        contentView.setTextColor(customLayoutDescription, notification_text_color);
        contentView.setFloat(customLayoutDescription, "setTextSize",
                notification_description_size_factor * notification_text_size);

        if (facebookId != null) {
            Log.d(TAG, "bitmap not null");
            CreateNotificationTask cNT = new CreateNotificationTask();
            cNT.setParams(customLayoutImageContainer, NotifId, nm, notification, contentView);
            String src = "http://graph.facebook.com/" + facebookId + "/picture?type=normal";
            URL url = new URL(src);
            cNT.execute(url);
        } else {
            Log.d(TAG, "bitmap null");
            contentView.setImageViewResource(customLayoutImageContainer, customLayoutImage);
            notification.contentView = contentView;
            nm.notify(NotifId, notification);
        }
        NotifId++;

        if (ctxt != null) {
            parameters = parameters == null ? "" : parameters;
            ctxt.dispatchStatusEventAsync("COMING_FROM_NOTIFICATION", parameters);
        }

    } catch (Exception e) {
        Log.e(TAG, "Error activating application:", e);
    }
}

From source file:com.akop.bach.service.XboxLiveServiceClient.java

private void notifyFriends(XboxLiveAccount account, long[] friendsOnline, List<Long> lastFriendsOnline) {
    NotificationManager mgr = getNotificationManager();
    Context context = getContext();

    int notificationId = 0x2000000 | ((int) account.getId() & 0xffffff);

    if (App.getConfig().logToConsole()) {
        String s = "";
        for (Object unr : lastFriendsOnline)
            s += unr.toString() + ",";

        App.logv("Currently online (%d): %s", lastFriendsOnline.size(), s);

        s = "";/*  w w w. j a  va 2 s. co m*/
        for (Object unr : friendsOnline)
            s += unr.toString() + ",";

        App.logv("New online (%d): %s", friendsOnline.length, s);
    }

    if (friendsOnline.length > 0) {
        int newOnlineCount = 0;
        for (Object online : friendsOnline)
            if (!lastFriendsOnline.contains(online))
                newOnlineCount++;

        if (App.getConfig().logToConsole())
            App.logv("%d computed new; %d online now; %d online before", newOnlineCount, friendsOnline.length,
                    lastFriendsOnline.size());

        if (newOnlineCount > 0) {
            // Prepare notification objects
            String tickerTitle;
            String tickerText;

            if (friendsOnline.length == 1) {
                tickerTitle = context.getString(R.string.friend_online);
                tickerText = context.getString(R.string.notify_friend_online_f,
                        Friends.getGamertag(context, friendsOnline[0]), account.getDescription());
            } else {
                tickerTitle = context.getString(R.string.friends_online);
                tickerText = context.getString(R.string.notify_friends_online_f, account.getScreenName(),
                        friendsOnline.length, account.getDescription());
            }

            Notification notification = new Notification(R.drawable.xbox_stat_notify_friend, tickerText,
                    System.currentTimeMillis());
            notification.flags |= Notification.FLAG_AUTO_CANCEL;

            Intent intent = new Intent(context, FriendList.class);
            intent.putExtra("account", account);

            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);

            notification.setLatestEventInfo(context, tickerTitle, tickerText, contentIntent);

            // New users online

            if (friendsOnline.length > 1)
                notification.number = friendsOnline.length;

            notification.flags |= Notification.FLAG_SHOW_LIGHTS;
            notification.ledOnMS = DEFAULT_LIGHTS_ON_MS;
            notification.ledOffMS = DEFAULT_LIGHTS_OFF_MS;
            notification.ledARGB = DEFAULT_LIGHTS_COLOR;
            notification.sound = account.getRingtoneUri();

            if (account.isVibrationEnabled())
                notification.defaults |= Notification.DEFAULT_VIBRATE;

            mgr.notify(notificationId, notification);
        }
    } else // No unread messages
    {
        mgr.cancel(notificationId);
    }
}

From source file:com.android.systemui.ReminderReceiver.java

@Override
public void onReceive(final Context context, Intent intent) {
    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    SharedPreferences shared = context.getSharedPreferences(KEY_REMINDER_ACTION, Context.MODE_PRIVATE);

    if (intent.getBooleanExtra("clear", false)) {
        manager.cancel(NOTI_ID);/*from  w w w.  j  a  v a  2 s  .  c o m*/
        // User has set a new reminder but didn't clear
        // This notification until now
        if (!shared.getBoolean("updated", false)) {
            shared.edit().putBoolean("scheduled", false).commit();
            shared.edit().putInt("hours", -1).commit();
            shared.edit().putInt("minutes", -1).commit();
            shared.edit().putInt("day", -1).commit();
            shared.edit().putString("title", null).commit();
            shared.edit().putString("message", null).commit();
        }
    } else {
        String title = shared.getString("title", null);
        String message = shared.getString("message", null);
        if (title != null && message != null) {
            Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_qs_alarm_on);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setTicker(title)
                    .setContentTitle(title).setContentText(message).setAutoCancel(false).setOngoing(true)
                    .setPriority(NotificationCompat.PRIORITY_HIGH).setSmallIcon(R.drawable.ic_qs_alarm_on)
                    .setLargeIcon(bm).setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(message));

            int alertMode = Settings.System.getIntForUser(context.getContentResolver(),
                    Settings.System.REMINDER_ALERT_NOTIFY, 0, UserHandle.USER_CURRENT);
            PendingIntent result = null;
            Intent serviceIntent = new Intent(context, ReminderService.class);
            if (alertMode != 0 && !QuietHoursHelper.inQuietHours(context, Settings.System.QUIET_HOURS_MUTE)) {
                context.startService(serviceIntent);
            }

            // Stop sound on click
            serviceIntent.putExtra("stopSelf", true);
            result = PendingIntent.getService(context, 1, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            builder.setContentIntent(result);

            // Add button for dismissal
            serviceIntent.putExtra("dismissNoti", true);
            result = PendingIntent.getService(context, 0, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            builder.addAction(R.drawable.ic_sysbar_null,
                    context.getResources().getString(R.string.quick_settings_reminder_noti_dismiss), result);

            // Add button for reminding later
            serviceIntent.putExtra("time", true);
            result = PendingIntent.getService(context, 2, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            builder.addAction(R.drawable.ic_qs_alarm_on,
                    context.getResources().getString(R.string.quick_settings_reminder_noti_later), result);

            shared.edit().putBoolean("scheduled", false).commit();
            shared.edit().putInt("hours", -1).commit();
            shared.edit().putInt("minutes", -1).commit();
            shared.edit().putInt("day", -1).commit();

            manager.notify(NOTI_ID, builder.build());
        }
    }
    shared.edit().putBoolean("updated", false).commit();
}

From source file:com.xorcode.andtweet.AndTweetService.java

/**
 * Notify user of the commands Queue size
 * //from  w w  w . java2 s . c  om
 * @return total size of Queues
 */
private int notifyOfQueue(boolean clearNotification) {
    int count = mRetryQueue.size() + mCommands.size();
    NotificationManager nM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (count == 0 || clearNotification) {
        // Clear notification
        nM.cancel(CommandEnum.NOTIFY_QUEUE.ordinal());
    } else if (mNotificationsEnabled) {
        if (mRetryQueue.size() > 0) {
            MyLog.d(TAG, mRetryQueue.size() + " commands in Retry Queue.");
        }
        if (mCommands.size() > 0) {
            MyLog.d(TAG, mCommands.size() + " commands in Main Queue.");
        }

        // Set up the notification to display to the user
        Notification notification = new Notification(R.drawable.notification_icon,
                (String) getText(R.string.notification_title), System.currentTimeMillis());

        int messageTitle;
        String aMessage = "";

        aMessage = I18n.formatQuantityMessage(getApplicationContext(), R.string.notification_queue_format,
                count, R.array.notification_queue_patterns, R.array.notification_queue_formats);
        messageTitle = R.string.notification_title_queue;

        // Set up the scrolling message of the notification
        notification.tickerText = aMessage;

        /**
         * Set the latest event information and send the notification
         * Actually don't start any intent
         * 
         * @see http
         *      ://stackoverflow.com/questions/4232006/android-notification
         *      -pendingintent-problem
         */
        // PendingIntent pi = PendingIntent.getActivity(this, 0, null, 0);

        /**
         * Kick the commands queue by sending empty command
         */
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, new CommandData(CommandEnum.EMPTY).toIntent(),
                0);

        notification.setLatestEventInfo(this, getText(messageTitle), aMessage, pi);
        nM.notify(CommandEnum.NOTIFY_QUEUE.ordinal(), notification);
    }
    return count;
}

From source file:com.raspi.chatapp.util.Notification.java

public void createNotification(String buddyId, String name, String message, String type) {
    SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

    if (defaultSharedPreferences
            .getBoolean(context.getResources().getString(R.string.pref_key_new_message_notifications), true)) {
        int index = buddyId.indexOf("@");
        if (index != -1)
            buddyId = buddyId.substring(0, index);
        if (name == null)
            name = buddyId;//ww w  . ja  v a  2 s  . c  o  m
        Log.d("DEBUG", "creating notification: " + buddyId + "|" + name + "|" + message);
        Intent resultIntent = new Intent(context, ChatActivity.class);
        resultIntent.setAction(NOTIFICATION_CLICK);
        String oldBuddyId = getOldBuddyId();
        Log.d("DEBUG",
                (oldBuddyId == null) ? ("oldBuddy is null (later " + buddyId) : ("oldBuddy: " + oldBuddyId));
        if (oldBuddyId == null || oldBuddyId.equals("")) {
            oldBuddyId = buddyId;
            setOldBuddyId(buddyId);
        }
        if (oldBuddyId.equals(buddyId)) {
            resultIntent.putExtra(Constants.BUDDY_ID, buddyId);
            resultIntent.putExtra(Constants.CHAT_NAME, name);
        }

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(ChatActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationManager nm = ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE));
        NotificationCompat.Style style;

        String[] previousNotifications = readJSONArray(CURRENT_NOTIFICATIONS);
        String title;
        String[] currentNotifications = Arrays.copyOf(previousNotifications, previousNotifications.length + 1);
        currentNotifications[currentNotifications.length - 1] = name + ": " + message;
        if (previousNotifications.length == 0) {
            style = new NotificationCompat.BigTextStyle();
            NotificationCompat.BigTextStyle bigTextStyle = ((NotificationCompat.BigTextStyle) style);
            title = context.getResources().getString(R.string.new_message) + " "
                    + context.getResources().getString(R.string.from) + " " + name;
            bigTextStyle.bigText(currentNotifications[0]);
            bigTextStyle.setBigContentTitle(title);
        } else {
            style = new NotificationCompat.InboxStyle();
            NotificationCompat.InboxStyle inboxStyle = (NotificationCompat.InboxStyle) style;
            title = (previousNotifications.length + 1) + " "
                    + context.getResources().getString(R.string.new_messages);
            for (String s : currentNotifications)
                if (s != null && !"".equals(s))
                    inboxStyle.addLine(s);
            inboxStyle.setSummaryText(
                    (currentNotifications.length > 2) ? ("+" + (currentNotifications.length - 2) + " more")
                            : null);
            inboxStyle.setBigContentTitle(title);
        }
        writeJSONArray(currentNotifications, CURRENT_NOTIFICATIONS);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
                .setContentText(currentNotifications[currentNotifications.length - 1])
                .setSmallIcon(MessageHistory.TYPE_TEXT.equals(type) ? R.drawable.ic_forum_white_48dp
                        : R.drawable.ic_photo_camera_white_48dp)
                .setLargeIcon(getLargeIcon(Character.toUpperCase(name.toCharArray()[0]))).setStyle(style)
                .setAutoCancel(true).setPriority(5).setContentIntent(resultPendingIntent);

        String str = context.getResources().getString(R.string.pref_key_privacy);
        mBuilder.setVisibility(context.getResources().getString(R.string.pref_value1_privacy).equals(str)
                ? NotificationCompat.VISIBILITY_SECRET
                : context.getResources().getString(R.string.pref_value2_privacy).equals(str)
                        ? NotificationCompat.VISIBILITY_PRIVATE
                        : NotificationCompat.VISIBILITY_PUBLIC);

        str = context.getResources().getString(R.string.pref_key_vibrate);
        if (defaultSharedPreferences.getBoolean(str, true))
            mBuilder.setVibrate(new long[] { 800, 500, 800, 500 });

        str = context.getResources().getString(R.string.pref_key_led);
        if (defaultSharedPreferences.getBoolean(str, true))
            mBuilder.setLights(Color.BLUE, 500, 500);

        str = defaultSharedPreferences.getString(context.getResources().getString(R.string.pref_key_ringtone),
                "");
        mBuilder.setSound("".equals(str) ? RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                : Uri.parse(str));

        nm.notify(NOTIFICATION_ID, mBuilder.build());
        str = context.getResources().getString(R.string.pref_key_banner);
        if (!defaultSharedPreferences.getBoolean(str, true)) {
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
            }
            reset();
        }
    }
}

From source file:cn.devit.app.ip_messenger.MainActivity.java

void setupListener() {
    handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case ADD_USER:
                userList.add((UserData) msg.obj);
                // view?
                if (sendView != null && sendView.userList != null) {
                    sendView.userList.setUserList(userList);
                } else {
                    // TODO a deferred event must notice.
                }/*from  w w  w.ja va  2s.c  o m*/

                break;
            case RECEIVE_MSG:
                final PigeonMessage m = (PigeonMessage) msg.obj;

                String tip = m.getContent();
                if (m.hasAttachements()) {
                    String attachementsDesc = "";
                    for (AttachementLink item : m.getAttachements()) {
                        attachementsDesc += item.getFilename();
                    }
                    tip += "" + attachementsDesc;

                    final NotificationManager notificationManager = (NotificationManager) getSystemService(
                            Context.NOTIFICATION_SERVICE);
                    new AlertDialog.Builder(MainActivity.this).setIcon(android.R.drawable.ic_dialog_info)
                            .setTitle("").setMessage(attachementsDesc)
                            .setPositiveButton("", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // TODO reject file
                                    notificationManager.cancel(m.hashCode());
                                    startDownloadAttachment(m);
                                }
                            }).setNegativeButton("?", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Log.d("main", "cancel notify NO.=" + m.hashCode());
                                    notificationManager.cancel(m.hashCode());
                                    // notificationManager.cancelAll();

                                    new Thread(new Runnable() {

                                        @Override
                                        public void run() {
                                            network.rejectAttachement(m);

                                        }
                                    }).start();

                                }
                            }).show();

                    Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class); // ??Activity
                    PendingIntent contentItent = PendingIntent.getActivity(MainActivity.this, 0,
                            notificationIntent, 0);
                    // TODO move to method.
                    Notification notification = new NotificationCompat.Builder(getApplicationContext())
                            .setSmallIcon(R.drawable.ic_launcher).setContentTitle("?")
                            .setContentText(attachementsDesc).setStyle(new NotificationCompat.InboxStyle())
                            .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                            .addAction(0, "agree", contentItent).addAction(0, "dismiss", contentItent).build();

                    // new Notification.Builder(
                    // getApplicationContext()).setTicker("?")
                    // // .setLargeIcon(R.drawable.ic_launcher)
                    // .setSmallIcon(R.drawable.ic_launcher).build();
                    // notification.flags |=
                    // (Notification.FLAG_AUTO_CANCEL);
                    // notification.defaults = Notification.DEFAULT_ALL;
                    // String title = "?";

                    // NotificationNotificationManager
                    Log.d("main", "show notify NO.=" + m.hashCode());
                    notificationManager.notify(m.hashCode(), notification);

                }
                Toast.makeText(getApplication(), tip, Toast.LENGTH_SHORT).show();

                DummyContent1.addItem(String.valueOf(i++), m.getSender().getUsername(), tip);
                break;
            default:
                Toast.makeText(getApplication(), String.valueOf(msg.obj), Toast.LENGTH_SHORT).show();
            }
            ;
        }
    };
    listener.handler = handler;
}