Example usage for android.app Notification FLAG_SHOW_LIGHTS

List of usage examples for android.app Notification FLAG_SHOW_LIGHTS

Introduction

In this page you can find the example usage for android.app Notification FLAG_SHOW_LIGHTS.

Prototype

int FLAG_SHOW_LIGHTS

To view the source code for android.app Notification FLAG_SHOW_LIGHTS.

Click Source Link

Document

Bit to be bitwise-ored into the #flags field that should be set if you want the LED on for this notification.

Usage

From source file:nl.vanvianen.android.gcm.GCMIntentService.java

@Override
@SuppressWarnings("unchecked")
protected void onMessage(Context context, Intent intent) {
    Log.d(LCAT, "Push notification received");

    boolean isTopic = false;

    HashMap<String, Object> data = new HashMap<String, Object>();
    for (String key : intent.getExtras().keySet()) {
        Object value = intent.getExtras().get(key);
        Log.d(LCAT, "Message key: \"" + key + "\" value: \"" + value + "\"");

        if (key.equals("from") && value instanceof String && ((String) value).startsWith("/topics/")) {
            isTopic = true;//from  w w w.j a v a  2s  .  c  o  m
        }

        String eventKey = key.startsWith("data.") ? key.substring(5) : key;
        data.put(eventKey, intent.getExtras().get(key));

        if (value instanceof String && ((String) value).startsWith("{")) {
            Log.d(LCAT, "Parsing JSON string...");
            try {
                JSONObject json = new JSONObject((String) value);

                Iterator<String> keys = json.keys();
                while (keys.hasNext()) {
                    String jKey = keys.next();
                    String jValue = json.getString(jKey);
                    Log.d(LCAT, "JSON key: \"" + jKey + "\" value: \"" + jValue + "\"");

                    data.put(jKey, jValue);
                }
            } catch (JSONException ex) {
                Log.d(LCAT, "JSON error: " + ex.getMessage());
            }
        }
    }

    /* Store data to be retrieved when resuming app as a JSON object, serialized as a String, otherwise
     * Ti.App.Properties.getString(GCMModule.LAST_DATA) doesn't work. */
    JSONObject json = new JSONObject(data);
    TiApplication.getInstance().getAppProperties().setString(GCMModule.LAST_DATA, json.toString());

    /* Get settings from notification object */
    int smallIcon = 0;
    int largeIcon = 0;
    String sound = null;
    boolean vibrate = false;
    boolean insistent = false;
    String group = null;
    boolean localOnly = true;
    int priority = 0;
    boolean bigText = false;
    int notificationId = 1;

    Integer ledOn = null;
    Integer ledOff = null;

    String titleKey = DEFAULT_TITLE_KEY;
    String messageKey = DEFAULT_MESSAGE_KEY;
    String tickerKey = DEFAULT_TICKER_KEY;
    String title = null;
    String message = null;
    String ticker = null;

    boolean backgroundOnly = false;

    Map<String, Object> notificationSettings = new Gson().fromJson(
            TiApplication.getInstance().getAppProperties().getString(GCMModule.NOTIFICATION_SETTINGS, null),
            Map.class);
    if (notificationSettings != null) {
        if (notificationSettings.get("smallIcon") instanceof String) {
            smallIcon = getResource("drawable", (String) notificationSettings.get("smallIcon"));
        } else {
            Log.e(LCAT, "Invalid setting smallIcon, should be String");
        }

        if (notificationSettings.get("largeIcon") instanceof String) {
            largeIcon = getResource("drawable", (String) notificationSettings.get("largeIcon"));
        } else {
            Log.e(LCAT, "Invalid setting largeIcon, should be String");
        }

        if (notificationSettings.get("sound") != null) {
            if (notificationSettings.get("sound") instanceof String) {
                sound = (String) notificationSettings.get("sound");
            } else {
                Log.e(LCAT, "Invalid setting sound, should be String");
            }
        }

        if (notificationSettings.get("vibrate") != null) {
            if (notificationSettings.get("vibrate") instanceof Boolean) {
                vibrate = (Boolean) notificationSettings.get("vibrate");
            } else {
                Log.e(LCAT, "Invalid setting vibrate, should be Boolean");
            }
        }

        if (notificationSettings.get("insistent") != null) {
            if (notificationSettings.get("insistent") instanceof Boolean) {
                insistent = (Boolean) notificationSettings.get("insistent");
            } else {
                Log.e(LCAT, "Invalid setting insistent, should be Boolean");
            }
        }

        if (notificationSettings.get("group") != null) {
            if (notificationSettings.get("group") instanceof String) {
                group = (String) notificationSettings.get("group");
            } else {
                Log.e(LCAT, "Invalid setting group, should be String");
            }
        }

        if (notificationSettings.get("localOnly") != null) {
            if (notificationSettings.get("localOnly") instanceof Boolean) {
                localOnly = (Boolean) notificationSettings.get("localOnly");
            } else {
                Log.e(LCAT, "Invalid setting localOnly, should be Boolean");
            }
        }

        if (notificationSettings.get("priority") != null) {
            if (notificationSettings.get("priority") instanceof Integer) {
                priority = (Integer) notificationSettings.get("priority");
            } else if (notificationSettings.get("priority") instanceof Double) {
                priority = ((Double) notificationSettings.get("priority")).intValue();
            } else {
                Log.e(LCAT,
                        "Invalid setting priority, should be an integer, between PRIORITY_MIN ("
                                + NotificationCompat.PRIORITY_MIN + ") and PRIORITY_MAX ("
                                + NotificationCompat.PRIORITY_MAX + ")");
            }
        }

        if (notificationSettings.get("bigText") != null) {
            if (notificationSettings.get("bigText") instanceof Boolean) {
                bigText = (Boolean) notificationSettings.get("bigText");
            } else {
                Log.e(LCAT, "Invalid setting bigText, should be Boolean");
            }
        }

        if (notificationSettings.get("titleKey") != null) {
            if (notificationSettings.get("titleKey") instanceof String) {
                titleKey = (String) notificationSettings.get("titleKey");
            } else {
                Log.e(LCAT, "Invalid setting titleKey, should be String");
            }
        }

        if (notificationSettings.get("messageKey") != null) {
            if (notificationSettings.get("messageKey") instanceof String) {
                messageKey = (String) notificationSettings.get("messageKey");
            } else {
                Log.e(LCAT, "Invalid setting messageKey, should be String");
            }
        }

        if (notificationSettings.get("tickerKey") != null) {
            if (notificationSettings.get("tickerKey") instanceof String) {
                tickerKey = (String) notificationSettings.get("tickerKey");
            } else {
                Log.e(LCAT, "Invalid setting tickerKey, should be String");
            }
        }

        if (notificationSettings.get("title") != null) {
            if (notificationSettings.get("title") instanceof String) {
                title = (String) notificationSettings.get("title");
            } else {
                Log.e(LCAT, "Invalid setting title, should be String");
            }
        }

        if (notificationSettings.get("message") != null) {
            if (notificationSettings.get("message") instanceof String) {
                message = (String) notificationSettings.get("message");
            } else {
                Log.e(LCAT, "Invalid setting message, should be String");
            }
        }

        if (notificationSettings.get("ticker") != null) {
            if (notificationSettings.get("ticker") instanceof String) {
                ticker = (String) notificationSettings.get("ticker");
            } else {
                Log.e(LCAT, "Invalid setting ticker, should be String");
            }
        }

        if (notificationSettings.get("ledOn") != null) {
            if (notificationSettings.get("ledOn") instanceof Integer) {
                ledOn = (Integer) notificationSettings.get("ledOn");
                if (ledOn < 0) {
                    Log.e(LCAT, "Invalid setting ledOn, should be positive");
                    ledOn = null;
                }
            } else {
                Log.e(LCAT, "Invalid setting ledOn, should be Integer");
            }
        }

        if (notificationSettings.get("ledOff") != null) {
            if (notificationSettings.get("ledOff") instanceof Integer) {
                ledOff = (Integer) notificationSettings.get("ledOff");
                if (ledOff < 0) {
                    Log.e(LCAT, "Invalid setting ledOff, should be positive");
                    ledOff = null;
                }
            } else {
                Log.e(LCAT, "Invalid setting ledOff, should be Integer");
            }
        }

        if (notificationSettings.get("backgroundOnly") != null) {
            if (notificationSettings.get("backgroundOnly") instanceof Boolean) {
                backgroundOnly = (Boolean) notificationSettings.get("backgroundOnly");
            } else {
                Log.e(LCAT, "Invalid setting backgroundOnly, should be Boolean");
            }
        }

        if (notificationSettings.get("notificationId") != null) {
            if (notificationSettings.get("notificationId") instanceof Integer) {
                notificationId = (Integer) notificationSettings.get("notificationId");
            } else {
                Log.e(LCAT, "Invalid setting notificationId, should be Integer");
            }
        }

    } else {
        Log.d(LCAT, "No notification settings found");
    }

    /* If icon not found, default to appicon */
    if (smallIcon == 0) {
        smallIcon = getResource("drawable", "appicon");
    }

    /* If large icon not found, default to icon */
    if (largeIcon == 0) {
        largeIcon = smallIcon;
    }

    /* Create intent to (re)start the app's root activity */
    String pkg = TiApplication.getInstance().getApplicationContext().getPackageName();
    Intent launcherIntent = TiApplication.getInstance().getApplicationContext().getPackageManager()
            .getLaunchIntentForPackage(pkg);
    launcherIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER);

    /* Grab notification content from data according to provided keys if not already set */
    if (title == null && titleKey != null) {
        title = (String) data.get(titleKey);
    }
    if (message == null && messageKey != null) {
        message = (String) data.get(messageKey);
    }
    if (ticker == null && tickerKey != null) {
        ticker = (String) data.get(tickerKey);
    }

    Log.i(LCAT, "Title: " + title);
    Log.i(LCAT, "Message: " + message);
    Log.i(LCAT, "Ticker: " + ticker);

    /* Check for app state */
    if (GCMModule.getInstance() != null) {
        /* Send data to app */
        if (isTopic) {
            GCMModule.getInstance().sendTopicMessage(data);
        } else {
            GCMModule.getInstance().sendMessage(data);
        }
        /* Do not create notification if backgroundOnly and app is in foreground */
        if (backgroundOnly && GCMModule.getInstance().isInForeground()) {
            Log.d(LCAT, "Notification received in foreground, no need for notification.");
            return;
        }
    }

    if (message == null) {
        Log.d(LCAT,
                "Message received but no 'message' specified in push notification payload, so will make this silent");
    } else {
        Log.d(LCAT, "Creating notification...");

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), largeIcon);
        if (bitmap == null) {
            Log.d(LCAT, "No large icon found");
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setContentTitle(title)
                .setContentText(message).setTicker(ticker)
                .setContentIntent(
                        PendingIntent.getActivity(this, 0, launcherIntent, PendingIntent.FLAG_ONE_SHOT))
                .setSmallIcon(smallIcon).setLargeIcon(bitmap);

        /* Name of group to group similar notifications together, can also be set in the push notification payload */
        if (data.get("group") != null) {
            group = (String) data.get("group");
        }
        if (group != null) {
            builder.setGroup(group);
        }
        Log.i(LCAT, "Group: " + group);

        /* Whether notification should be for this device only or bridged to other devices, can also be set in the push notification payload */
        if (data.get("localOnly") != null) {
            localOnly = Boolean.valueOf((String) data.get("localOnly"));
        }
        builder.setLocalOnly(localOnly);
        Log.i(LCAT, "LocalOnly: " + localOnly);

        /* Specify notification priority, can also be set in the push notification payload */
        if (data.get("priority") != null) {
            priority = Integer.parseInt((String) data.get("priority"));
        }
        if (priority >= NotificationCompat.PRIORITY_MIN && priority <= NotificationCompat.PRIORITY_MAX) {
            builder.setPriority(priority);
            Log.i(LCAT, "Priority: " + priority);
        } else {
            Log.e(LCAT, "Ignored invalid priority " + priority);
        }

        /* Specify whether bigtext should be used, can also be set in the push notification payload */
        if (data.get("bigText") != null) {
            bigText = Boolean.valueOf((String) data.get("bigText"));
        }
        if (bigText) {
            builder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
        }
        Log.i(LCAT, "bigText: " + bigText);

        Notification notification = builder.build();

        /* Sound, can also be set in the push notification payload */
        if (data.get("sound") != null) {
            Log.d(LCAT, "Sound specified in notification");
            sound = (String) data.get("sound");
        }

        if ("default".equals(sound)) {
            Log.i(LCAT, "Sound: default sound");
            notification.defaults |= Notification.DEFAULT_SOUND;
        } else if (sound != null) {
            Log.i(LCAT, "Sound " + sound);
            notification.sound = Uri.parse("android.resource://" + pkg + "/" + getResource("raw", sound));
        }

        /* Vibrate, can also be set in the push notification payload */
        if (data.get("vibrate") != null) {
            vibrate = Boolean.valueOf((String) data.get("vibrate"));
        }
        if (vibrate) {
            notification.defaults |= Notification.DEFAULT_VIBRATE;
        }
        Log.i(LCAT, "Vibrate: " + vibrate);

        /* Insistent, can also be set in the push notification payload */
        if ("true".equals(data.get("insistent"))) {
            insistent = true;
        }
        if (insistent) {
            notification.flags |= Notification.FLAG_INSISTENT;
        }
        Log.i(LCAT, "Insistent: " + insistent);

        /* notificationId, set in push payload to specify multiple notifications should be shown. If not specified, subsequent notifications "override / overwrite" the older ones */
        if (data.get("notificationId") != null) {
            if (data.get("notificationId") instanceof Integer) {
                notificationId = (Integer) data.get("notificationId");
            } else if (data.get("notificationId") instanceof String) {
                try {
                    notificationId = Integer.parseInt((String) data.get("notificationId"));
                } catch (NumberFormatException ex) {
                    Log.e(LCAT, "Invalid setting notificationId, should be Integer");
                }
            } else {
                Log.e(LCAT, "Invalid setting notificationId, should be Integer");
            }
        }
        Log.i(LCAT, "Notification ID: " + notificationId);

        /* Specify LED flashing */
        if (ledOn != null || ledOff != null) {
            notification.flags |= Notification.FLAG_SHOW_LIGHTS;
            if (ledOn != null) {
                notification.ledOnMS = ledOn;
            }
            if (ledOff != null) {
                notification.ledOffMS = ledOff;
            }
        } else {
            notification.defaults |= Notification.DEFAULT_LIGHTS;
        }

        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(notificationId,
                notification);
    }
}

From source file:com.olearyp.gusto.Expsetup.java

protected void sendCommand(final String command, final String description, final String state) {
    final Intent runCmd = new Intent("com.olearyp.gusto.SUEXEC");
    runCmd.setData(/*  w w  w.  ja va 2 s .  c o  m*/
            Uri.fromParts("command", ". /system/bin/exp_script.sh.lib && read_in_ep_config && " + command, ""))
            .putExtra("com.olearyp.gusto.STATE", state);
    final Notification note = new Notification(R.drawable.icon,
            description.substring(0, 1).toUpperCase() + description.substring(1) + "...",
            System.currentTimeMillis());
    note.setLatestEventInfo(Expsetup.this, getString(R.string.app_name),
            getString(R.string.app_name) + " is " + description + "...",
            PendingIntent.getBroadcast(Expsetup.this, 0, null, 0));
    runCmd.putExtra("com.olearyp.gusto.RUN_NOTIFICATION", note);
    startService(runCmd);
    setServerState(state);
    if (getServerState().equals(getString(R.string.reboot_manual_flash_required))) {
        final Intent intent = new Intent("com.olearyp.gusto.SUEXEC")
                .setData(Uri.fromParts("commandid", Integer.toString(R.string.reboot_recovery), ""));
        final PendingIntent contentIntent = PendingIntent.getService(this, 0, intent, 0);
        final Notification rebootNote = new Notification(R.drawable.status_reboot,
                getString(R.string.reboot_recovery_required_msg), System.currentTimeMillis());
        rebootNote.setLatestEventInfo(this, "GUSTO reboot request",
                getString(R.string.reboot_recovery_doit_msg), contentIntent);
        rebootNote.deleteIntent = PendingIntent.getBroadcast(this, 0,
                new Intent("com.olearyp.gusto.RESET_SERVER_STATE"), 0);
        rebootNote.flags |= Notification.FLAG_SHOW_LIGHTS;
        rebootNote.ledOnMS = 200;
        rebootNote.ledOffMS = 400;
        rebootNote.ledARGB = Color.argb(255, 255, 0, 0);
        nm.notify(REBOOT_NOTIFICATION, rebootNote);
    } else if (getServerState().equals(getString(R.string.reboot_recovery_required))) {
        final Intent intent = new Intent("com.olearyp.gusto.SUEXEC")
                .setData(Uri.fromParts("commandid", Integer.toString(R.string.reboot), ""));
        final PendingIntent contentIntent = PendingIntent.getService(this, 0, intent, 0);
        final Notification rebootNote = new Notification(R.drawable.status_reboot,
                getString(R.string.reboot_autoflash_required_msg), System.currentTimeMillis());
        rebootNote.setLatestEventInfo(this, "GUSTO reboot request",
                getString(R.string.reboot_autoflash_doit_msg), contentIntent);
        rebootNote.deleteIntent = PendingIntent.getBroadcast(this, 0,
                new Intent("com.olearyp.gusto.RESET_SERVER_STATE"), 0);
        rebootNote.flags |= Notification.FLAG_SHOW_LIGHTS;
        rebootNote.ledOnMS = 200;
        rebootNote.ledOffMS = 600;
        rebootNote.ledARGB = Color.argb(255, 255, 255, 0);
        nm.notify(REBOOT_NOTIFICATION, rebootNote);
    } else if (getServerState().equals(getString(R.string.reboot_required))) {
        final Intent intent = new Intent("com.olearyp.gusto.SUEXEC")
                .setData(Uri.fromParts("commandid", Integer.toString(R.string.reboot), ""));
        final PendingIntent contentIntent = PendingIntent.getService(this, 0, intent, 0);
        final Notification rebootNote = new Notification(R.drawable.status_reboot,
                getString(R.string.reboot_required_msg), System.currentTimeMillis());
        rebootNote.setLatestEventInfo(this, "GUSTO reboot request", getString(R.string.reboot_doit_msg),
                contentIntent);
        rebootNote.deleteIntent = PendingIntent.getBroadcast(this, 0,
                new Intent("com.olearyp.gusto.RESET_SERVER_STATE"), 0);
        rebootNote.flags |= Notification.FLAG_SHOW_LIGHTS;
        rebootNote.ledOnMS = 200;
        rebootNote.ledOffMS = 600;
        rebootNote.ledARGB = Color.argb(255, 255, 255, 0);
        nm.notify(REBOOT_NOTIFICATION, rebootNote);
    }
}

From source file:com.waz.zclient.controllers.notifications.NotificationsController.java

private void attachNotificationLed(Notification notification) {
    int color = sharedPreferences.getInt(UserPreferencesController.USER_PREFS_LAST_ACCENT_COLOR, -1);
    if (color == -1) {
        color = context.getResources().getColor(R.color.accent_default);
    }/*from   w w w .  ja  v  a  2  s  .  com*/
    notification.ledARGB = color;
    notification.ledOnMS = context.getResources().getInteger(R.integer.notifications__system__led_on);
    notification.ledOffMS = context.getResources().getInteger(R.integer.notifications__system__led_off);
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
}

From source file:com.android.calendar.alerts.AlertService.java

private static void addNotificationOptions(NotificationWrapper nw, boolean quietUpdate, String tickerText,
        boolean defaultVibrate, String reminderRingtone, boolean showLights) {
    Notification notification = nw.mNotification;

    if (showLights) {
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;
        notification.defaults |= Notification.DEFAULT_LIGHTS;
    }/*ww  w .  ja  v a2s  .  c  om*/

    // Quietly update notification bar. Nothing new. Maybe something just got deleted.
    if (!quietUpdate) {
        // Flash ticker in status bar
        if (!TextUtils.isEmpty(tickerText)) {
            notification.tickerText = tickerText;
        }

        // Generate either a pop-up dialog, status bar notification, or
        // neither. Pop-up dialog and status bar notification may include a
        // sound, an alert, or both. A status bar notification also includes
        // a toast.
        if (defaultVibrate) {
            notification.defaults |= Notification.DEFAULT_VIBRATE;
        }

        // Possibly generate a sound. If 'Silent' is chosen, the ringtone
        // string will be empty.
        notification.sound = TextUtils.isEmpty(reminderRingtone) ? null : Uri.parse(reminderRingtone);
    }
}

From source file:co.beem.project.beem.FbTextService.java

/**
 * Show a notification using the preference of the user.
 * /*from   w  ww .  j  a  v a  2  s .  c o m*/
 * @param id
 *            the id of the notification.
 * @param notif
 *            the notification to show
 */
public void sendNotification(int id, Notification notif) {
    if (mSettings.getBoolean(FbTextApplication.NOTIFICATION_VIBRATE_KEY, true))
        notif.defaults |= Notification.DEFAULT_VIBRATE;
    notif.ledARGB = 0xff0000ff; // Blue color
    notif.ledOnMS = 1000;
    notif.ledOffMS = 1000;
    notif.flags |= Notification.FLAG_SHOW_LIGHTS;
    String ringtoneStr = mSettings.getString(FbTextApplication.CHANGE_RINGTONE_PREF_KEY,
            Settings.System.DEFAULT_NOTIFICATION_URI.toString());
    notif.sound = Uri.parse(ringtoneStr);
    if (mSettings.getBoolean("notifications_new_message", true))
        mNotificationManager.notify(id, notif);
}

From source file:com.zuzhili.bussiness.helper.CCPHelper.java

/**
 * ???/*from  w  w w  . j  a  v  a2s.com*/
 * content  ?
 */
private void showMsgNotification(Context context, String content, String ticker, String listId) {
    // NotificationManager
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(android.content.Context.NOTIFICATION_SERVICE);

    // ?
    Intent notificationIntent = new Intent(context, HomeTabActivity.class); // ??Activity
    notificationIntent.putExtra(Constants.TO_GROUPSLISTFRG, "ok");
    notificationIntent.putExtra(Constants.CHANGE_SOCIAL, listId);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//Intent.FLAG_ACTIVITY_SINGLE_TOP|
    notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    notificationIntent.setData(Uri.parse("custom://" + System.currentTimeMillis()));
    PendingIntent contentItent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Notification??
    Notification notification = new NotificationCompat.Builder(context)
            .setContentTitle(context.getString(R.string.new_msg_notification_title)).setContentText(content)
            .setSmallIcon(R.drawable.notify).setTicker(ticker).setContentIntent(contentItent)
            .setWhen(System.currentTimeMillis()).build();

    //FLAG_AUTO_CANCEL   ??
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    //DEFAULT_VIBRATE <uses-permission android:name="android.permission.VIBRATE" />??
    notification.defaults = Notification.DEFAULT_VIBRATE;
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.ledARGB = Color.BLUE;
    notification.ledOnMS = 5000; //

    // ? NotificationNotificationManager
    notificationManager.cancel(0);
    notificationManager.notify(0, notification);
}

From source file:com.wso2.mobile.mdm.services.Operation.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *//*ww  w.jav a  2 s  .  com*/
private static void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_stat_gcm;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, NotifyActivity.class);
    notificationIntent.putExtra("notification", message);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    notificationManager.notify(0, notification);
    Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}

From source file:org.telegram.messenger.MessagesController.java

private void showInAppNotification(MessageObject messageObject) {
    if (!UserConfig.clientActivated) {
        return;//from  ww w .  java  2 s  . c  o m
    }
    if (ApplicationLoader.lastPauseTime != 0) {
        ApplicationLoader.lastPauseTime = System.currentTimeMillis();
        FileLog.e("tmessages", "reset sleep timeout by recieved message");
    }
    if (messageObject == null) {
        return;
    }
    SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications",
            Context.MODE_PRIVATE);
    boolean globalEnabled = preferences.getBoolean("EnableAll", true);
    if (!globalEnabled) {
        return;
    }

    if (ApplicationLoader.lastPauseTime == 0) {
        boolean inAppSounds = preferences.getBoolean("EnableInAppSounds", true);
        boolean inAppVibrate = preferences.getBoolean("EnableInAppVibrate", true);
        boolean inAppPreview = preferences.getBoolean("EnableInAppPreview", true);

        if (inAppSounds || inAppVibrate || inAppPreview) {
            long dialog_id = messageObject.messageOwner.dialog_id;
            int user_id = messageObject.messageOwner.from_id;
            int chat_id = 0;
            if (dialog_id == 0) {
                if (messageObject.messageOwner.to_id.chat_id != 0) {
                    dialog_id = -messageObject.messageOwner.to_id.chat_id;
                    chat_id = messageObject.messageOwner.to_id.chat_id;
                } else if (messageObject.messageOwner.to_id.user_id != 0) {
                    if (messageObject.messageOwner.to_id.user_id == UserConfig.clientUserId) {
                        dialog_id = messageObject.messageOwner.from_id;
                    } else {
                        dialog_id = messageObject.messageOwner.to_id.user_id;
                    }
                }
            } else {
                TLRPC.EncryptedChat chat = encryptedChats.get((int) (dialog_id >> 32));
                if (chat == null) {
                    return;
                }
            }
            if (dialog_id == 0) {
                return;
            }
            TLRPC.User user = users.get(user_id);
            if (user == null) {
                return;
            }
            TLRPC.Chat chat;
            if (chat_id != 0) {
                chat = chats.get(chat_id);
                if (chat == null) {
                    return;
                }
            }
            String key = "notify_" + dialog_id;
            boolean value = preferences.getBoolean(key, true);
            if (!value) {
                return;
            }

            if (inAppPreview) {
                NotificationCenter.Instance.postNotificationName(701, messageObject);
            }
            if (inAppVibrate) {
                Vibrator v = (Vibrator) ApplicationLoader.applicationContext
                        .getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(100);
            }
            if (inAppSounds) {
                playNotificationSound();
            }
        }
    } else {
        long dialog_id = messageObject.messageOwner.dialog_id;
        int chat_id = messageObject.messageOwner.to_id.chat_id;
        int user_id = messageObject.messageOwner.to_id.user_id;
        if (user_id != 0 && user_id == UserConfig.clientUserId) {
            user_id = messageObject.messageOwner.from_id;
        }
        if (dialog_id == 0) {
            if (chat_id != 0) {
                dialog_id = -chat_id;
            } else if (user_id != 0) {
                dialog_id = user_id;
            }
        }

        if (dialog_id != 0) {
            String key = "notify_" + dialog_id;
            boolean value = preferences.getBoolean(key, true);
            if (!value) {
                return;
            }
        }

        boolean groupEnabled = preferences.getBoolean("EnableGroup", true);
        if (chat_id != 0 && !globalEnabled) {
            return;
        }
        TLRPC.FileLocation photoPath = null;

        boolean globalVibrate = preferences.getBoolean("EnableVibrateAll", true);
        boolean groupVibrate = preferences.getBoolean("EnableVibrateGroup", true);
        boolean groupPreview = preferences.getBoolean("EnablePreviewGroup", true);
        boolean userPreview = preferences.getBoolean("EnablePreviewAll", true);

        String defaultPath = null;
        Uri defaultUri = Settings.System.DEFAULT_NOTIFICATION_URI;
        if (defaultUri != null) {
            defaultPath = defaultUri.getPath();
        }

        String globalSound = preferences.getString("GlobalSoundPath", defaultPath);
        String chatSound = preferences.getString("GroupSoundPath", defaultPath);
        String userSoundPath = null;
        String chatSoundPath = null;

        NotificationManager mNotificationManager = (NotificationManager) ApplicationLoader.applicationContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        String msg = null;

        if ((int) dialog_id != 0) {
            if (chat_id != 0) {
                intent.putExtra("chatId", chat_id);
            }
            if (user_id != 0) {
                intent.putExtra("userId", user_id);
            }

            if (chat_id == 0 && user_id != 0) {

                TLRPC.User u = users.get(user_id);
                if (u == null) {
                    return;
                }

                if (u.photo != null && u.photo.photo_small != null && u.photo.photo_small.volume_id != 0
                        && u.photo.photo_small.local_id != 0) {
                    photoPath = u.photo.photo_small;
                }

                if (userPreview) {
                    if (messageObject.messageOwner instanceof TLRPC.TL_messageService) {
                        if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserJoined) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationContactJoined,
                                    Utilities.formatName(u.first_name, u.last_name));
                        } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationContactNewPhoto,
                                    Utilities.formatName(u.first_name, u.last_name));
                        } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) {
                            String date = String.format("%s %s %s",
                                    Utilities.formatterYear
                                            .format(((long) messageObject.messageOwner.date) * 1000),
                                    ApplicationLoader.applicationContext.getString(R.string.OtherAt),
                                    Utilities.formatterDay
                                            .format(((long) messageObject.messageOwner.date) * 1000));
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationUnrecognizedDevice, UserConfig.currentUser.first_name,
                                    date, messageObject.messageOwner.action.title,
                                    messageObject.messageOwner.action.address);
                        }
                    } else {
                        if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) {
                            if (messageObject.messageOwner.message != null
                                    && messageObject.messageOwner.message.length() != 0) {
                                msg = ApplicationLoader.applicationContext.getString(
                                        R.string.NotificationMessageText,
                                        Utilities.formatName(u.first_name, u.last_name),
                                        messageObject.messageOwner.message);
                            } else {
                                msg = ApplicationLoader.applicationContext.getString(
                                        R.string.NotificationMessageNoText,
                                        Utilities.formatName(u.first_name, u.last_name));
                            }
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationMessagePhoto,
                                    Utilities.formatName(u.first_name, u.last_name));
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationMessageVideo,
                                    Utilities.formatName(u.first_name, u.last_name));
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationMessageContact,
                                    Utilities.formatName(u.first_name, u.last_name));
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationMessageMap,
                                    Utilities.formatName(u.first_name, u.last_name));
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationMessageDocument,
                                    Utilities.formatName(u.first_name, u.last_name));
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaAudio) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationMessageAudio,
                                    Utilities.formatName(u.first_name, u.last_name));
                        }
                    }
                } else {
                    msg = ApplicationLoader.applicationContext.getString(R.string.NotificationMessageNoText,
                            Utilities.formatName(u.first_name, u.last_name));
                }
            } else if (chat_id != 0 && user_id == 0) {
                TLRPC.Chat chat = chats.get(chat_id);
                if (chat == null) {
                    return;
                }
                TLRPC.User u = users.get(messageObject.messageOwner.from_id);
                if (u == null) {
                    return;
                }

                if (u.photo != null && u.photo.photo_small != null && u.photo.photo_small.volume_id != 0
                        && u.photo.photo_small.local_id != 0) {
                    photoPath = u.photo.photo_small;
                }

                if (groupPreview) {
                    if (messageObject.messageOwner instanceof TLRPC.TL_messageService) {
                        if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser) {
                            if (messageObject.messageOwner.action.user_id == UserConfig.clientUserId) {
                                msg = ApplicationLoader.applicationContext.getString(
                                        R.string.NotificationInvitedToGroup,
                                        Utilities.formatName(u.first_name, u.last_name), chat.title);
                            } else {
                                TLRPC.User u2 = users.get(messageObject.messageOwner.action.user_id);
                                if (u2 == null) {
                                    return;
                                }
                                msg = ApplicationLoader.applicationContext.getString(
                                        R.string.NotificationGroupAddMember,
                                        Utilities.formatName(u.first_name, u.last_name), chat.title,
                                        Utilities.formatName(u2.first_name, u2.last_name));
                            }
                        } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatEditTitle) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationEditedGroupName,
                                    Utilities.formatName(u.first_name, u.last_name),
                                    messageObject.messageOwner.action.title);
                        } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatEditPhoto
                                || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeletePhoto) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationEditedGroupPhoto,
                                    Utilities.formatName(u.first_name, u.last_name), chat.title);
                        } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser) {
                            if (messageObject.messageOwner.action.user_id == UserConfig.clientUserId) {
                                msg = ApplicationLoader.applicationContext.getString(
                                        R.string.NotificationGroupKickYou,
                                        Utilities.formatName(u.first_name, u.last_name), chat.title);
                            } else if (messageObject.messageOwner.action.user_id == u.id) {
                                msg = ApplicationLoader.applicationContext.getString(
                                        R.string.NotificationGroupLeftMember,
                                        Utilities.formatName(u.first_name, u.last_name), chat.title);
                            } else {
                                TLRPC.User u2 = users.get(messageObject.messageOwner.action.user_id);
                                if (u2 == null) {
                                    return;
                                }
                                msg = ApplicationLoader.applicationContext.getString(
                                        R.string.NotificationGroupKickMember,
                                        Utilities.formatName(u.first_name, u.last_name), chat.title,
                                        Utilities.formatName(u2.first_name, u2.last_name));
                            }
                        }
                    } else {
                        if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) {
                            if (messageObject.messageOwner.message != null
                                    && messageObject.messageOwner.message.length() != 0) {
                                msg = ApplicationLoader.applicationContext.getString(
                                        R.string.NotificationMessageGroupText,
                                        Utilities.formatName(u.first_name, u.last_name), chat.title,
                                        messageObject.messageOwner.message);
                            } else {
                                msg = ApplicationLoader.applicationContext.getString(
                                        R.string.NotificationMessageGroupNoText,
                                        Utilities.formatName(u.first_name, u.last_name), chat.title);
                            }
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationMessageGroupPhoto,
                                    Utilities.formatName(u.first_name, u.last_name), chat.title);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationMessageGroupVideo,
                                    Utilities.formatName(u.first_name, u.last_name), chat.title);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationMessageGroupContact,
                                    Utilities.formatName(u.first_name, u.last_name), chat.title);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationMessageGroupMap,
                                    Utilities.formatName(u.first_name, u.last_name), chat.title);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationMessageGroupDocument,
                                    Utilities.formatName(u.first_name, u.last_name), chat.title);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaAudio) {
                            msg = ApplicationLoader.applicationContext.getString(
                                    R.string.NotificationMessageGroupAudio,
                                    Utilities.formatName(u.first_name, u.last_name), chat.title);
                        }
                    }
                } else {
                    msg = ApplicationLoader.applicationContext.getString(
                            R.string.NotificationMessageGroupNoText,
                            Utilities.formatName(u.first_name, u.last_name), chat.title);
                }
            }
        } else {
            msg = ApplicationLoader.applicationContext.getString(R.string.YouHaveNewMessage);
            int enc_id = (int) (dialog_id >> 32);
            intent.putExtra("encId", enc_id);
        }
        if (msg == null) {
            return;
        }

        boolean needVibrate = false;

        if (user_id != 0) {
            userSoundPath = preferences.getString("sound_path_" + user_id, null);
            needVibrate = globalVibrate;
        }
        if (chat_id != 0) {
            chatSoundPath = preferences.getString("sound_chat_path_" + chat_id, null);
            needVibrate = groupVibrate;
        }

        String choosenSoundPath = null;

        if (user_id != 0) {
            if (userSoundPath != null) {
                choosenSoundPath = userSoundPath;
            } else if (globalSound != null) {
                choosenSoundPath = globalSound;
            }
        } else if (chat_id != 0) {
            if (chatSoundPath != null) {
                choosenSoundPath = chatSoundPath;
            } else if (chatSound != null) {
                choosenSoundPath = chatSound;
            }
        } else {
            choosenSoundPath = globalSound;
        }

        intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
        intent.setFlags(32768);
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                ApplicationLoader.applicationContext)
                        .setContentTitle(ApplicationLoader.applicationContext.getString(R.string.AppName))
                        .setSmallIcon(R.drawable.notification)
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg)
                        .setAutoCancel(true).setTicker(msg);

        if (photoPath != null) {
            Bitmap img = FileLoader.Instance.getImageFromMemory(photoPath, null, null, "50_50", false);
            //                String fileNameFinal = u.photo.photo_small.volume_id + "_" + u.photo.photo_small.local_id + ".jpg";
            //                File cacheFileFinal = new File(Utilities.getCacheDir(), fileNameFinal);
            //                if (cacheFileFinal.exists()) {
            //                    photoPath
            //                }
            if (img != null) {
                mBuilder.setLargeIcon(img);
            }
        }

        if (needVibrate) {
            mBuilder.setVibrate(new long[] { 0, 100, 0, 100 });
        }
        if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) {
            if (choosenSoundPath.equals(defaultPath)) {
                mBuilder.setSound(defaultUri);
            } else {
                mBuilder.setSound(Uri.parse(choosenSoundPath));
            }
        }

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.cancel(1);
        Notification notification = mBuilder.build();
        notification.ledARGB = 0xff00ff00;
        notification.ledOnMS = 1000;
        notification.ledOffMS = 1000;
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;
        try {
            mNotificationManager.notify(1, notification);
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    }
}