Example usage for android.app Notification DEFAULT_SOUND

List of usage examples for android.app Notification DEFAULT_SOUND

Introduction

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

Prototype

int DEFAULT_SOUND

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

Click Source Link

Document

Use the default notification sound.

Usage

From source file:com.nanostuffs.yurdriver.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *///  www . j a  va2s.c om
private void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_launcher;
    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, MapActivity.class);
    notificationIntent.putExtra("fromNotification", "notification");
    // 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,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    System.out.println("notification====>" + message);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    // notification.defaults |= Notification.DEFAULT_LIGHTS;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    notification.ledARGB = 0x00000000;
    notification.ledOnMS = 0;
    notification.ledOffMS = 0;
    notificationManager.notify(AndyConstants.NOTIFICATION_ID, notification);
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(
            PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,
            "WakeLock");
    wakeLock.acquire();
    wakeLock.release();

}

From source file:com.nobledesignlabs.lookupaddress.GcmIntentService.java

private void displayNotification(Context context, Bundle extras) {
    // ---PendingIntent to launch activity if the user selects
    // this notification---
    // NotificationView context = new NotificationView();
    try {//from   ww w . j  a  v  a  2s.co m

        Intent i = null;
        Random rand = new Random();
        int timenow = rand.nextInt();
        String title = extras.getString("title");
        String message = extras.getString("message");
        String picture = extras.getString("imgurl");
        String sinfotype = extras.getString("infotype");
        boolean cancelonclick = true;
        int infotype = Integer.parseInt(sinfotype);
        if (infotype == CommonStuff.ADDRESS_NOTIFICATION) {
            i = new Intent(context, NotificationView.class);
            i.putExtra("notificationID", timenow);
            i.putExtra("message", message);
            i.putExtra("title", title);
            i.putExtra("picture", picture);
            cancelonclick = true;
            // i.putExtra("infotype", picture);
        } else if (infotype == CommonStuff.ADDRESS_AUTHORIZATION_REQUEST) {
            i = new Intent(context, AuthorizationRequestActivity.class);
            String token = extras.getString("token");
            i.putExtra("notificationID", timenow);
            i.putExtra("message", message);
            i.putExtra("title", title);
            i.putExtra("picture", picture);
            i.putExtra("token", token);
            String address = extras.getString("address");
            i.putExtra("address", address);
            cancelonclick = true;
            // i.putExtra("infotype", picture);
        } else if (infotype == CommonStuff.ADDRESS_SHARING_REQUEST) {
            i = new Intent(context, AuthorizedActivity.class);
            i.putExtra("notificationID", timenow);
            i.putExtra("message", message);
            i.putExtra("title", title);
            String token = extras.getString("token");
            String address = extras.getString("address");
            i.putExtra("address", address);
            i.putExtra("token", token);
            cancelonclick = false;
            // i.putExtra("infotype", picture);
        }
        if (i != null) {
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, timenow, i, 0);
            /*
             * NotificationManager nm = (NotificationManager) context
             * .getSystemService(Context.NOTIFICATION_SERVICE); Notification
             * notif = new Notification( R.drawable.direction_uturn,
             * message, timenow); // String title =
             * context.getString(R.string.app_name);
             * 
             * i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
             * Intent.FLAG_ACTIVITY_SINGLE_TOP);
             * 
             * notif.setLatestEventInfo(context, title, message,
             * pendingIntent); // notif.flags |=
             * Notification.FLAG_AUTO_CANCEL; notif.flags =
             * Notification.FLAG_AUTO_CANCEL; notif.defaults |=
             * Notification.DEFAULT_SOUND; notif.defaults |=
             * Notification.DEFAULT_VIBRATE; notif.vibrate = new long[] {
             * 100, 250, 100, 500 }; nm.notify(timenow, notif);
             */

            NotificationCompat.Builder b = new NotificationCompat.Builder(context);

            if (cancelonclick) {
                b.setAutoCancel(true).setOngoing(false).setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.drawable.direction_uturn).setTicker(title).setContentTitle(title)
                        .setContentText(message).setVibrate(new long[] { 100, 250, 100, 500 })
                        .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE
                                | Notification.DEFAULT_SOUND)
                        .setContentIntent(pendingIntent).setLights(0xFFF7BF05, 250, 500)
                        .setContentInfo("me@address");

            } else {
                b.setAutoCancel(false).setOngoing(true).setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.drawable.direction_uturn).setTicker(title).setContentTitle(title)
                        .setContentText(message).setLights(0xFF308036, 250, 500)
                        .setVibrate(new long[] { 100, 250, 100, 500 })
                        .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE
                                | Notification.DEFAULT_SOUND)
                        .setContentIntent(pendingIntent).setContentInfo("me@address");
            }

            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(timenow, b.build());
        }
    } catch (Exception d) {
    }
}

From source file:com.ubikod.capptain.android.sdk.reach.CapptainDefaultNotifier.java

@Override
public Boolean handleNotification(CapptainReachInteractiveContent content) throws RuntimeException {
    /* System notification case */
    if (content.isSystemNotification()) {
        /* Big picture handling */
        Bitmap bigPicture = null;/*from  w  w w.ja  va 2s  .co m*/
        String bigPictureURL = content.getNotificationBigPicture();
        if (bigPictureURL != null && Build.VERSION.SDK_INT >= 16) {
            /* Schedule picture download if needed, or load picture if download completed. */
            Long downloadId = content.getDownloadId();
            if (downloadId == null) {
                NotificationUtilsV11.downloadBigPicture(mContext, content);
                return null;
            } else
                bigPicture = NotificationUtilsV11.getBigPicture(mContext, downloadId);
        }

        /* Generate notification identifier */
        int notificationId = getNotificationId(content);

        /* Build notification using support lib to manage compatibility with old Android versions */
        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);

        /* Icon for ticker and content icon */
        builder.setSmallIcon(mNotificationIcon);

        /*
         * Large icon, handled only since API Level 11 (needs down scaling if too large because it's
         * cropped otherwise by the system).
         */
        Bitmap notificationImage = content.getNotificationImage();
        if (notificationImage != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            builder.setLargeIcon(scaleBitmapForLargeIcon(mContext, notificationImage));

        /* Texts */
        String notificationTitle = content.getNotificationTitle();
        String notificationMessage = content.getNotificationMessage();
        String notificationBigText = content.getNotificationBigText();
        builder.setContentTitle(notificationTitle);
        builder.setContentText(notificationMessage);

        /*
         * Replay: display original date and don't replay all the tickers (be as quiet as possible
         * when replaying).
         */
        Long notificationFirstDisplayedDate = content.getNotificationFirstDisplayedDate();
        if (notificationFirstDisplayedDate != null)
            builder.setWhen(notificationFirstDisplayedDate);
        else
            builder.setTicker(notificationTitle);

        /* Big picture */
        if (bigPicture != null)
            builder.setStyle(new BigPictureStyle().bigPicture(bigPicture).setBigContentTitle(notificationTitle)
                    .setSummaryText(notificationMessage));

        /* Big text */
        else if (notificationBigText != null)
            builder.setStyle(new BigTextStyle().bigText(notificationBigText));

        /* Vibration/sound if not a replay */
        if (notificationFirstDisplayedDate == null) {
            int defaults = 0;
            if (content.isNotificationSound())
                defaults |= Notification.DEFAULT_SOUND;
            if (content.isNotificationVibrate())
                defaults |= Notification.DEFAULT_VIBRATE;
            builder.setDefaults(defaults);
        }

        /* Launch the receiver on action */
        Intent actionIntent = new Intent(INTENT_ACTION_ACTION_NOTIFICATION);
        CapptainReachAgent.setContentIdExtra(actionIntent, content);
        actionIntent.putExtra(INTENT_EXTRA_NOTIFICATION_ID, notificationId);
        Intent intent = content.getIntent();
        if (intent != null)
            actionIntent.putExtra(INTENT_EXTRA_COMPONENT, intent.getComponent());
        actionIntent.setPackage(mContext.getPackageName());
        PendingIntent contentIntent = PendingIntent.getBroadcast(mContext, (int) content.getLocalId(),
                actionIntent, FLAG_CANCEL_CURRENT);
        builder.setContentIntent(contentIntent);

        /* Also launch receiver if the notification is exited (clear button) */
        Intent exitIntent = new Intent(INTENT_ACTION_EXIT_NOTIFICATION);
        exitIntent.putExtra(INTENT_EXTRA_NOTIFICATION_ID, notificationId);
        CapptainReachAgent.setContentIdExtra(exitIntent, content);
        exitIntent.setPackage(mContext.getPackageName());
        PendingIntent deleteIntent = PendingIntent.getBroadcast(mContext, (int) content.getLocalId(),
                exitIntent, FLAG_CANCEL_CURRENT);
        builder.setDeleteIntent(deleteIntent);

        /* Can be dismissed ? */
        Notification notification = builder.build();
        if (!content.isNotificationCloseable())
            notification.flags |= Notification.FLAG_NO_CLEAR;

        /* Allow overriding */
        if (onNotificationPrepared(notification, content))

            /*
             * Submit notification, replacing the previous one if any (this should happen only if the
             * application process is restarted).
             */
            mNotificationManager.notify(notificationId, notification);
    }

    /* Activity embedded notification case */
    else {
        /* Get activity */
        Activity activity = CapptainActivityManager.getInstance().getCurrentActivity().get();

        /* Cannot notify in app if no activity provided */
        if (activity == null)
            return false;

        /* Get notification area */
        String category = content.getCategory();
        int areaId = getInAppAreaId(category);
        View notificationAreaView = activity.findViewById(areaId);

        /* No notification area, check if we can install overlay */
        if (notificationAreaView == null) {
            /* Check overlay is not disabled in this activity */
            Bundle activityConfig = CapptainUtils.getActivityMetaData(activity);
            if (!activityConfig.getBoolean(METADATA_NOTIFICATION_OVERLAY, true))
                return false;

            /* Inflate overlay layout and get reference to notification area */
            View overlay = LayoutInflater.from(mContext).inflate(getOverlayLayoutId(category), null);
            activity.addContentView(overlay, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
            notificationAreaView = activity.findViewById(areaId);
        }

        /* Otherwise check if there is an overlay containing the area to restore visibility */
        else {
            View overlay = activity.findViewById(getOverlayViewId(category));
            if (overlay != null)
                overlay.setVisibility(View.VISIBLE);
        }

        /* Make the notification area visible */
        notificationAreaView.setVisibility(View.VISIBLE);

        /* Prepare area */
        prepareInAppArea(content, notificationAreaView);
    }

    /* Success */
    return true;
}

From source file:nl.dobots.fridgefile.FridgeFile.java

private void createAlertNotification(String notificationSmall, String notificationBig) {

    Intent contentIntent = new Intent(this, MainActivity.class);
    contentIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent piContent = PendingIntent.getActivity(this, 0, contentIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    _notificationBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Temperature Alert").setContentText(notificationSmall)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationBig))
            .setContentIntent(piContent).setDefaults(Notification.DEFAULT_SOUND)
            .setLights(Color.BLUE, 500, 1000);
    _notificationManager.notify(Config.ALERT_NOTIFICATION_ID, _notificationBuilder.build());

}

From source file:com.teinproductions.tein.papyrosprogress.UpdateCheckReceiver.java

private static void issueNotification(Context context, Set<String> addedMilestones,
        Set<String> removedMilestones, Map<String, int[]> changedProgresses) {
    String title = context.getString(R.string.notification_title);
    StringBuilder message = new StringBuilder();

    // Changed progresses
    for (String milestoneTitle : changedProgresses.keySet()) {
        int oldProgress = changedProgresses.get(milestoneTitle)[0];
        int newProgress = changedProgresses.get(milestoneTitle)[1];
        message.append("\n").append(String.format(context.getString(R.string.notific_msg_text_format),
                milestoneTitle, oldProgress, newProgress));
    }//from   w  w w .  j  a va 2  s  .co  m

    // Added milestones
    for (String milestoneTitle : addedMilestones) {
        message.append("\n").append(context.getString(R.string.milestone_added_notification, milestoneTitle));
    }

    // Removed milestones
    for (String milestoneTitle : removedMilestones) {
        message.append("\n").append(context.getString(R.string.milestone_removed_notification, milestoneTitle));
    }

    // Remove first newline
    message.delete(0, 1);

    // Create PendingIntent
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class),
            PendingIntent.FLAG_UPDATE_CURRENT);

    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
    boolean sound = pref.getBoolean(Constants.NOTIFICATION_SOUND_PREF, true);
    boolean vibrate = pref.getBoolean(Constants.NOTIFICATION_VIBRATE_PREF, true);
    boolean light = pref.getBoolean(Constants.NOTIFICATION_LIGHT_PREF, true);
    int defaults = 0;
    if (sound)
        defaults = defaults | Notification.DEFAULT_SOUND;
    if (vibrate)
        defaults = defaults | Notification.DEFAULT_VIBRATE;
    if (light)
        defaults = defaults | Notification.DEFAULT_LIGHTS;

    // Build the notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(message).setContentIntent(pendingIntent)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
            .setSmallIcon(R.mipmap.notification_small_icon)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
            .setDefaults(defaults).setAutoCancel(true);

    // Issue the notification
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(PROGRESS_NOTIFICATION_ID, builder.build());
}

From source file:com.juick.android.XMPPMessageReceiver.java

public static void updateInfo(final Context context, int nMessages, boolean silent) {
    final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    String tickerText = "juick: new message";
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

    // public Notification(int icon, java.lang.CharSequence tickerText, long when) { /* compiled code */ }
    // Notification notif = new Notification(R.drawable.juick_message_icon, null,System.currentTimeMillis());

    int iconIndex;
    if (nMessages < 1) {
        iconIndex = 0; // to prevent out of bounds
    } else if (nMessages > NOTIFICATION_ICONS.length - 1) {
        iconIndex = NOTIFICATION_ICONS.length - 1; // to prevent out of bounds
    } else {//from   w  w w.j  a v  a 2  s .  c  o  m
        iconIndex = nMessages;
    }
    boolean showNumberUnread = sp.getBoolean("show_number_unread", true);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(
                    showNumberUnread ? NOTIFICATION_ICONS[iconIndex] : R.drawable.juick_message_icon_plain)
            .setWhen(System.currentTimeMillis());

    //context.getResources().getDrawable(smallIcon)
    // public Notification(int icon, java.lang.CharSequence tickerText, long when) { /* compiled code */ }

    int notification = 0;
    if (!silent) {
        if (sp.getBoolean("led_enabled", true))
            notification |= Notification.DEFAULT_LIGHTS;
        if (System.currentTimeMillis() - lastVibrate > 5000) {
            // add some sound
            if (sp.getBoolean("vibration_enabled", true))
                notification |= Notification.DEFAULT_VIBRATE;
            if (sp.getBoolean("ringtone_enabled", true)) {
                String ringtone_uri = sp.getString("ringtone_uri", "");
                if (ringtone_uri.length() > 0) {
                    notificationBuilder.setSound(Uri.parse(ringtone_uri));
                } else
                    notification |= Notification.DEFAULT_SOUND;
            }
            lastVibrate = System.currentTimeMillis();
        }
    }
    notificationBuilder.setDefaults(silent ? 0 : notification);
    Intent intent = new Intent(context, XMPPService.class);
    intent.setAction(XMPPService.ACTION_LAUNCH_MESSAGELIST);
    PendingIntent pendingIntent = PendingIntent.getService(context, 1000, intent, 0);
    //PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, nintent, 0);
    notificationBuilder.setContentTitle("Juick: " + nMessages + " new message" + (nMessages > 1 ? "s" : ""))
            .setContentText(tickerText).setContentIntent(pendingIntent).setNumber(nMessages);
    nm.notify("", 2, notificationBuilder.getNotification());
}

From source file:com.futureplatforms.kirin.extensions.localnotifications.LocalNotificationsBackend.java

@SuppressWarnings("deprecation")
public Notification createNotification(Bundle settings, JSONObject obj) {

    // notifications[i] = api.normalizeAPI({
    // 'string': {
    // mandatory: ['title', 'body'],
    // defaults: {'icon':'icon'}
    // },/* ww w  . j a  va  2 s .  com*/
    //
    // 'number': {
    // mandatory: ['id', 'timeMillisSince1970'],
    // // the number of ms after which we start prioritising more recent
    // things above you.
    // defaults: {'epsilon': 1000 * 60 * 24 * 365}
    // },
    //
    // 'boolean': {
    // defaults: {
    // 'vibrate': false,
    // 'sound': false
    // }
    // }

    int icon = settings.getInt("notification_icon", -1);
    if (icon == -1) {
        Log.e(C.TAG, "Need a notification_icon resource in the meta-data of LocalNotificationsAlarmReceiver");
        return null;
    }

    Notification n = new Notification();
    n.icon = icon;
    n.flags = Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
    long alarmTime = obj.optLong("timeMillisSince1970");
    long displayTime = obj.optLong("displayTimestamp", alarmTime);
    n.when = displayTime;
    n.tickerText = obj.optString("body");
    n.setLatestEventInfo(mContext, obj.optString("title"), obj.optString("body"), null);

    if (obj.optBoolean("vibrate")) {
        n.defaults |= Notification.DEFAULT_VIBRATE;
    }
    if (obj.optBoolean("sound")) {
        n.defaults |= Notification.DEFAULT_SOUND;
    }

    String uriString = settings.getString("content_uri_prefix");
    if (uriString == null) {
        Log.e(C.TAG, "Need a content_uri_prefix in the meta-data of LocalNotificationsAlarmReceiver");
        return null;
    }

    if (uriString.contains("%d")) {
        uriString = String.format(uriString, obj.optInt("id"));
    }
    Uri uri = Uri.parse(uriString);

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.setData(uri);
    n.contentIntent = PendingIntent.getActivity(mContext, 23, intent, PendingIntent.FLAG_ONE_SHOT);
    return n;
}

From source file:ru.appsm.inapphelp.IAHHelpDesk.java

/**
 *
 * Handle push notification. Cordova./*from   ww  w.j  a v a  2 s .co  m*/
 *
 * @param data
 * @param context
 */
public static void BuildNotificationForDataWithContext(JSONObject data, Context context) {
    Log.i(TAG, "Create notifications");
    if (data != null && data.has("secretkey") && data.has("userid") && data.has("appkey") && data.has("appid")
            && data.has("email") && data.has("message") && data.has("title") && data.has("notId")
            && data.has("msgId")) {
        try {
            int notId = 1;
            try {
                notId = data.getInt("notId");
            } catch (JSONException e) {
                notId = 1;
            }

            mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            Intent notificationIntent = new Intent(context, IssueDetailActivity.class);
            notificationIntent.putExtra("fromPush", true);
            notificationIntent.putExtra("userid", data.getString("userid"));
            notificationIntent.putExtra("appid", data.getString("appid"));
            notificationIntent.putExtra("appkey", data.getString("appkey"));
            notificationIntent.putExtra("secretkey", data.getString("secretkey"));
            notificationIntent.putExtra("email", data.getString("email"));

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

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                    .setSmallIcon(getApplicationIcon(context)).setContentTitle(data.getString("title"))
                    .setContentText(data.getString("message")).setAutoCancel(true)
                    .setContentIntent(contentIntent);

            if (data.getString("sound").equals("default")) {
                mBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE
                        | Notification.DEFAULT_LIGHTS);
            }

            mNotificationManager.notify(notId, mBuilder.build());
        } catch (JSONException e) {
            Log.i(TAG, "Fail to parse push data");
        }
    } else {
        Log.i(TAG, "Empty or wrong push data");
    }
}

From source file:com.mobileman.moments.android.frontend.activity.IncomingCallActivity.java

public static void sendGeneralNotificationOfMissedCall(Context context, String userName, String title) {
    Intent intent = new Intent(context, MainActivity.class);

    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder b = new NotificationCompat.Builder(context);
    String notificationTitle = userName + " " + context.getResources().getString(R.string.isLiveSuffix);
    String notificationText = title;
    NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
    b.setAutoCancel(true).setSmallIcon(R.drawable.ic_launcher).setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis()).setTicker("X").setContentTitle(notificationTitle)
            .setContentText(notificationText)
            .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
            .setContentIntent(contentIntent);

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(++NOTIFICATION_COUNTER, b.build());
}

From source file:uk.org.rivernile.edinburghbustracker.android.alerts.TimeAlertService.java

/**
 * {@inheritDoc}// w w  w.  j  av  a2s. co  m
 */
@Override
protected void onHandleIntent(final Intent intent) {
    final String stopCode = intent.getStringExtra(ARG_STOPCODE);
    final String[] services = intent.getStringArrayExtra(ARG_SERVICES);
    final int timeTrigger = intent.getIntExtra(ARG_TIME_TRIGGER, 5);
    final BusParser parser = new EdinburghParser();

    HashMap<String, BusStop> result;
    try {
        // Get the bus times. Only get 1 bus per service.
        result = parser.getBusStopData(new String[] { stopCode }, 1);
    } catch (BusParserException e) {
        // There was an error. No point continuing. Reschedule.
        reschedule(intent);
        return;
    }

    // Get the bus stop we are interested in. It should be the only one in
    // the HashMap anyway.
    final BusStop busStop = result.get(stopCode);
    int time;
    EdinburghBus edinBs;

    // Loop through all the bus services at this stop.
    for (BusService bs : busStop.getBusServices()) {
        // We are only interested in the next departure. Also get the time.
        edinBs = (EdinburghBus) bs.getFirstBus();
        if (edinBs == null) {
            continue;
        }

        time = edinBs.getArrivalMinutes();

        // Loop through all of the services we are interested in.
        for (String service : services) {
            // The service matches and meets the time criteria.
            if (service.equals(bs.getServiceName()) && time <= timeTrigger) {
                // The alert may have been cancelled by the user recently,
                // check it's still active to stay relevant. Cancel the
                // alert if we're continuing.
                if (!sd.isActiveTimeAlert(stopCode))
                    return;
                alertMan.removeTimeAlert();

                // Create the intent that's fired when the notification is
                // tapped. It shows the bus times view for that stop.
                final Intent launchIntent = new Intent(this, DisplayStopDataActivity.class);
                launchIntent.setAction(DisplayStopDataActivity.ACTION_VIEW_STOP_DATA);
                launchIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                launchIntent.putExtra(DisplayStopDataActivity.ARG_STOPCODE, stopCode);
                launchIntent.putExtra(DisplayStopDataActivity.ARG_FORCELOAD, true);

                final String stopName = bsd.getNameForBusStop(stopCode);

                final String title = getString(R.string.timeservice_notification_title);

                final String summary = getResources().getQuantityString(
                        R.plurals.timeservice_notification_summary, time == 0 ? 1 : time, service, time,
                        stopName);

                // Build the notification.
                final NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this);
                notifBuilder.setAutoCancel(true);
                notifBuilder.setSmallIcon(R.drawable.ic_status_bus);
                notifBuilder.setTicker(summary);
                notifBuilder.setContentTitle(title);
                notifBuilder.setContentText(summary);
                // Support for Jelly Bean notifications.
                notifBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(summary));
                notifBuilder.setContentIntent(
                        PendingIntent.getActivity(this, 0, launchIntent, PendingIntent.FLAG_ONE_SHOT));

                final Notification n = notifBuilder.build();
                if (sp.getBoolean(PreferencesActivity.PREF_ALERT_SOUND, true))
                    n.defaults |= Notification.DEFAULT_SOUND;

                if (sp.getBoolean(PreferencesActivity.PREF_ALERT_VIBRATE, true))
                    n.defaults |= Notification.DEFAULT_VIBRATE;

                if (sp.getBoolean(PreferencesActivity.PREF_ALERT_LED, true)) {
                    n.defaults |= Notification.DEFAULT_LIGHTS;
                    n.flags |= Notification.FLAG_SHOW_LIGHTS;
                }

                // Send the notification.
                notifMan.notify(ALERT_ID, n);
                return;
            }
        }
    }

    // All the services have been looped through and the criteria didn't
    // match. This means a reschedule should be attempted.
    reschedule(intent);
}