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.artech.android.gcm.GcmIntentService.java

@SuppressLint("InlinedApi")
public void createNotification(String payload, String action, String notificationParameters) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    String appName = getString(R.string.app_name);

    SharedPreferences settings = MyApplication.getInstance().getAppSharedPreferences();
    int notificatonID = settings.getInt("notificationID", 0); // allow multiple notifications //$NON-NLS-1$

    Intent intent = new Intent("android.intent.action.MAIN"); //$NON-NLS-1$
    intent.setClassName(this, getPackageName() + ".Main"); //$NON-NLS-1$
    intent.addCategory("android.intent.category.LAUNCHER"); //$NON-NLS-1$

    if (Services.Strings.hasValue(action)) {
        // call main as root of the stack with the action as intent parameter. Use clear_task like GoHome
        if (CompatibilityHelper.isApiLevel(Build.VERSION_CODES.HONEYCOMB))
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        else/* ww  w  . j a  v  a  2s.  c o  m*/
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

        intent.putExtra(IntentParameters.NotificationAction, action);
        intent.putExtra(IntentParameters.NotificationParameters, notificationParameters);
        intent.setAction(String.valueOf(Math.random()));
    } else {
        // call main like main application shortcut
        intent.setFlags(0);
        intent.setAction("android.intent.action.MAIN");
    }

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = NotificationHelper.newBuilder(this).setWhen(System.currentTimeMillis())
            .setContentTitle(appName).setContentText(payload).setContentIntent(pendingIntent)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(payload))
            .setDefaults(Notification.DEFAULT_ALL).setAutoCancel(true).build();

    notificationManager.notify(notificatonID, notification);

    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("notificationID", ++notificatonID % 32); //$NON-NLS-1$
    editor.commit();
}

From source file:com.chasetech.pcount.autoupdate.AutoUpdateApk.java

protected void raise_notification() {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager nm = (NotificationManager) context.getSystemService(ns);

    String update_file = preferences.getString(UPDATE_FILE, "");

    if (update_file.length() > 0) {
        setChanged();//from  w  w w  .  j  av a  2 s .c om
        notifyObservers(AUTOUPDATE_HAVE_UPDATE);

        // raise notification
        //            Notification notification = new Notification(
        //                    appIcon, appName + " update", System.currentTimeMillis());
        //            notification.flags |= NOTIFICATION_FLAGS;

        CharSequence contentTitle = appName + " update available";
        CharSequence contentText = "Click this to install..";
        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setDataAndType(
                Uri.parse("file://" + context.getFilesDir().getAbsolutePath() + "/" + update_file),
                ANDROID_PACKAGE);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        Notification.Builder builder = new Notification.Builder(context);

        builder.setAutoCancel(false);
        builder.setTicker("An update is available.");
        builder.setContentTitle(contentTitle);
        builder.setContentText(contentText);
        builder.setSmallIcon(appIcon);
        builder.setContentIntent(contentIntent);
        builder.setOngoing(true);
        builder.setSubText(appName + " update"); //API level 16
        builder.setNumber(100);
        builder.build();

        Notification myNotication = builder.getNotification();
        nm.notify(NOTIFICATION_ID, myNotication);

        //            notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        //            nm.notify( NOTIFICATION_ID, notification);
    } else {
        nm.cancel(NOTIFICATION_ID);
    }

    //      if( update_file.length() > 0 ) {
    //         setChanged();
    //         notifyObservers(AUTOUPDATE_HAVE_UPDATE);
    //
    //         // raise notification
    ///*         Notification notification = new Notification(
    //               appIcon, appName + " update", System.currentTimeMillis());*/
    //            Notification.Builder notifBuilder = new Notification.Builder(context);
    //         //notification.flags |= NOTIFICATION_FLAGS;
    //
    //         CharSequence contentTitle = appName + " update available";
    //         CharSequence contentText = "Select to install";
    //         Intent notificationIntent = new Intent(Intent.ACTION_VIEW );
    //         Uri uriFile = Uri.parse("file://" + context.getFilesDir().getAbsolutePath() + "/" + update_file);
    //         notificationIntent.setDataAndType(uriFile, ANDROID_PACKAGE);
    //         PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    //
    //            notifBuilder.setContentTitle(contentTitle);
    //            notifBuilder.setContentText(contentText);
    //            notifBuilder.setContentIntent(contentIntent);
    //            notifBuilder.setSubText("Update available.");
    //            notifBuilder.build();
    //
    //            Notification notification = notifBuilder.build();
    //            notification.flags |= NOTIFICATION_FLAGS;
    //
    //            nm.notify(NOTIFICATION_ID, notification);
    //
    //         //notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    //         //nm.notify( NOTIFICATION_ID, notification);
    //      } else {
    //         nm.cancel( NOTIFICATION_ID );
    //      }
}

From source file:ch.carteggio.provider.sync.NotificationService.java

private void updateUnreadNotification(boolean newMessage) {

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    CarteggioProviderHelper helper = new CarteggioProviderHelper(this);

    int unreadCount = helper.getUnreadCount();

    if (unreadCount == 0) {

        mNotificationManager.cancel(INCOMING_NOTIFICATION_ID);

    } else {/*from   w  w  w .j  ava2  s. co  m*/

        String quantityString = getResources().getQuantityString(R.plurals.notification_new_incoming_messages,
                unreadCount);

        NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(String.format(quantityString, unreadCount))
                .setSmallIcon(android.R.drawable.stat_notify_chat)
                .setContentText(getString(R.string.notification_text_new_messages));

        Intent resultIntent = new Intent(this, MainActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);

        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        notifyBuilder.setContentIntent(resultPendingIntent);

        if (newMessage) {

            Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            AudioManager manager = (AudioManager) getSystemService(AUDIO_SERVICE);

            long pattern[] = { 1000, 500, 2000 };

            if (manager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {
                notifyBuilder.setSound(uri);
                notifyBuilder.setVibrate(pattern);
            } else if (manager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
                notifyBuilder.setVibrate(pattern);
            }
        }

        mNotificationManager.notify(INCOMING_NOTIFICATION_ID, notifyBuilder.build());

    }

}

From source file:jmri.enginedriver.threaded_application.java

/**
 * Display OnGoing Notification that indicates EngineDriver is Running.
 * Should only be called when ED is going into the background.
 * Currently call this from each activity onPause, passing the current intent 
 * to return to when reopening.  */
void addNotification(Intent notificationIntent) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.icon)
            .setContentTitle(this.getString(R.string.notification_title))
            .setContentText(this.getString(R.string.notification_text)).setOngoing(true);

    PendingIntent contentIntent = PendingIntent.getActivity(this, ED_NOTIFICATION_ID, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setContentIntent(contentIntent);

    // Add as notification
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(ED_NOTIFICATION_ID, builder.build());
}

From source file:com.hhunj.hhudata.ForegroundService.java

protected void showNotification(CharSequence from, CharSequence message) {
    // look up the notification manager service
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // The PendingIntent to launch our activity if the user selects this
    // notification

    //,//from ww  w . j ava  2s .co  m
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, IncomingMessageView.class), 0);

    // The ticker text, this uses a formatted string so our message could be
    // localized
    String tickerText = getString(R.string.imcoming_message_ticker_text, message);

    // construct the Notification object.
    Notification notif = new Notification(R.drawable.stat_sample, tickerText, System.currentTimeMillis());

    // Set the info for the views that show in the notification panel.
    notif.setLatestEventInfo(this, from, message, contentIntent);

    //   

    //
    Date dt = new Date();
    if (IsDuringWorkHours(dt)) {
        notif.defaults |= (Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
    } else {
        notif.defaults |= (Notification.DEFAULT_VIBRATE);
    }

    // after a 100ms delay, vibrate for 250ms, pause for 100 ms and
    // then vibrate for 500ms.//
    notif.vibrate = new long[] { 100, 250, 100, 500 };

    nm.notify(R.string.imcoming_message_ticker_text, notif);
}

From source file:jp.co.conit.sss.sp.ex1.billing.BillingService.java

/**
 * ????/*from w  w w  .  j ava 2s .  c o m*/
 * 
 * @param purchases
 */
private void notificationVerifiedProduct(List<VerifiedProduct> purchases) {

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

    HashMap<String, VerifiedProduct> orderMap = new HashMap<String, VerifiedProduct>();
    int size = purchases.size() - 1;

    // ????Map???????????
    for (int i = size; i >= 0; i--) {
        VerifiedProduct vp = purchases.get(i);
        if (vp.getPurchaseState() == PurchaseState.PURCHASED) {
            orderMap.put(vp.getProductId(), vp);
        }
    }

    // ?????Notification??
    // ?????
    if (orderMap.size() > 0) {

        Notification notification = new Notification();
        notification.icon = R.drawable.ic_status;
        notification.tickerText = context.getString(R.string.notification_buy_result);
        notification.flags = Notification.FLAG_AUTO_CANCEL;

        Intent intent = new Intent();
        PendingIntent pendingintent = PendingIntent.getActivity(context, 0, intent, 0);

        String title = context.getString(R.string.notification_book);

        notification.setLatestEventInfo(context, context.getString(R.string.notification_buy_finish, title),
                context.getString(R.string.notification_urge_download), pendingintent);

        notificationManager.notify(0, notification);
    }

}

From source file:dev.ukanth.ufirewall.Api.java

public static void showNotification(boolean status, Context context) {
    final int NOTIF_ID = 33341;
    String notificationText = "";
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

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

    Intent appIntent = new Intent(context, MainActivity.class);
    PendingIntent in = PendingIntent.getActivity(context, 0, appIntent, 0);
    int icon = R.drawable.widget_on;

    if (status) {
        notificationText = context.getString(R.string.active);
        icon = R.drawable.widget_on;/* w  w  w  .  java 2  s.  c  o  m*/
    } else {
        notificationText = context.getString(R.string.inactive);
        icon = R.drawable.widget_off;
    }

    builder.setSmallIcon(icon).setOngoing(true).setAutoCancel(false)
            .setContentTitle(context.getString(R.string.app_name))
            .setTicker(context.getString(R.string.app_name)).setContentText(notificationText);

    builder.setContentIntent(in);

    mNotificationManager.notify(NOTIF_ID, builder.build());

}

From source file:cn.studyjams.s2.sj0132.bowenyan.mygirlfriend.nononsenseapps.notepad.data.receiver.NotificationHelper.java

/**
 * Needs the builder that contains non-note specific values.
 *
 *///from w  w w  .j a  v a 2  s  . c o  m
private static void notifyBigText(final Context context, final NotificationManager notificationManager,
        final NotificationCompat.Builder builder,
        final cn.studyjams.s2.sj0132.bowenyan.mygirlfriend.nononsenseapps.notepad.data.model.sql.Notification note) {
    final Intent delIntent = new Intent(Intent.ACTION_DELETE, note.getUri());
    if (note.repeats != 0) {
        delIntent.setAction(ACTION_RESCHEDULE);
    }
    // Add extra so we don't delete all
    // if (note.time != null) {
    // delIntent.putExtra(ARG_MAX_TIME, note.time);
    // }
    delIntent.putExtra(ARG_TASKID, note.taskID);
    // Delete it on clear
    PendingIntent deleteIntent = PendingIntent.getBroadcast(context, 0, delIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Open intent
    final Intent openIntent = new Intent(Intent.ACTION_VIEW, Task.getUri(note.taskID));
    // Should create a new instance to avoid fragment problems
    openIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

    // Delete intent on non-location repeats
    // Opening the note should delete/reschedule the notification
    openIntent.putExtra(NOTIFICATION_DELETE_ARG, note._id);

    // Opening always cancels the notification though
    openIntent.putExtra(NOTIFICATION_CANCEL_ARG, note._id);

    // Open note on click
    PendingIntent clickIntent = PendingIntent.getActivity(context, 0, openIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Action to complete
    PendingIntent completeIntent = PendingIntent.getBroadcast(context, 0,
            new Intent(ACTION_COMPLETE, note.getUri()).putExtra(ARG_TASKID, note.taskID),
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Action to snooze
    PendingIntent snoozeIntent = PendingIntent.getBroadcast(context, 0,
            new Intent(ACTION_SNOOZE, note.getUri()).putExtra(ARG_TASKID, note.taskID),
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Build notification
    builder.setContentTitle(note.taskTitle).setContentText(note.taskNote).setContentIntent(clickIntent)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(note.taskNote));

    // Delete intent on non-location repeats
    builder.setDeleteIntent(deleteIntent);

    // Snooze button only on time non-repeating
    if (note.time != null && note.repeats == 0) {
        builder.addAction(R.drawable.ic_alarm_24dp_white, context.getText(R.string.snooze), snoozeIntent);
    }
    // Complete button only on non-repeating, both time and location
    if (note.repeats == 0) {
        builder.addAction(R.drawable.ic_check_24dp_white, context.getText(R.string.completed), completeIntent);
    }

    final Notification noti = builder.build();

    notificationManager.notify((int) note._id, noti);
}

From source file:org.kegbot.app.service.CheckinService.java

/**
 * Processes the checkin response message.
 *///from  ww  w .jav  a 2 s  .  co  m
private void processLastCheckinResponse(JsonNode response) {
    Log.d(TAG, "Checkin response: " + response);

    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    final JsonNode statusNode = response.get("status");
    if (statusNode == null || !statusNode.isTextual()) {
        Log.d(TAG, "Invalid checkin response: no status.");
        return;
    }

    final String status = statusNode.getTextValue();
    if (STATUS_OK.equals(status)) {
        Log.d(TAG, "Checkin status: " + status);
    } else {
        Log.d(TAG, "Invalid checkin response: unknown status: " + status);
        return;
    }

    boolean updateNeeded = false;
    final JsonNode updateNeededNode = response.get("update_needed");
    if (updateNeededNode != null && updateNeededNode.isBoolean() && updateNeededNode.getBooleanValue()) {
        updateNeeded = true;
    }

    boolean updateRequired = false;
    final JsonNode updateRequiredNode = response.get("update_required");
    if (updateRequiredNode != null && updateRequiredNode.isBoolean() && updateRequiredNode.getBooleanValue()) {
        updateRequired = true;
    }

    mPrefsHelper.setLastCheckinStatus(status);
    mPrefsHelper.setUpdateNeeded(updateNeeded);
    mPrefsHelper.setUpdateRequired(updateRequired);

    if (updateNeeded) {
        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setData(Uri.parse("market://details?id=org.kegbot.app"));
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        int titleRes = updateRequired ? R.string.checkin_update_required_title
                : R.string.checkin_update_available_title;

        Notification noti = new Notification.Builder(this)
                .setSmallIcon(updateRequired ? R.drawable.icon_warning : R.drawable.icon_download)
                .setContentTitle(getString(titleRes))
                .setContentText(getString(R.string.checkin_update_description)).setContentIntent(contentIntent)
                .setOngoing(true).setOnlyAlertOnce(true).getNotification();

        Log.d(TAG, "Posting notification.");
        nm.notify(CHECKIN_NOTIFICATION_ID, noti);
    } else {
        nm.cancel(CHECKIN_NOTIFICATION_ID);
    }
}

From source file:de.hackerspacebremen.push.PushIntentService.java

public void displayNotification(final Context context, final SpaceData data, final boolean vibrationEnabled,
        final boolean permanentNotification) throws JSONException {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);

    final boolean permanent = permanentNotification && data.isSpaceOpen();

    String timeString = context.getString(R.string.unknown);
    Date time = data.getTime();/*from   ww  w.java2 s . co  m*/
    if (time != null) {
        timeString = SpeakingDateFormat.format(time);
    }

    int icon;
    CharSequence notificationText;
    final CharSequence contentTitle;
    if (data.isSpaceOpen()) {
        icon = R.drawable.notification_open;
        notificationText = context.getString(R.string.space_open, timeString);
        contentTitle = context.getString(R.string.space_open_simple);
    } else {
        icon = R.drawable.notification_closed;
        notificationText = context.getString(R.string.space_closed, timeString);
        contentTitle = context.getString(R.string.space_closed_simple);
    }

    long when = System.currentTimeMillis();

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setSmallIcon(icon);
    builder.setTicker(notificationText);
    builder.setWhen(when);
    if (data.getMessage() != null && data.getMessage().length() > 0) {
        builder.setStyle(new NotificationCompat.BigTextStyle().setSummaryText(notificationText)
                .bigText("Nachricht: \n" + data.getMessage()));
    }
    if (!permanent) {
        builder.setAutoCancel(true);
    }
    builder.setContentTitle(contentTitle);
    builder.setContentText(notificationText);
    Intent notificationIntent = new Intent(context, StartActivity.class);
    notificationIntent.putExtra("status_json", SpaceDataJsonParser.parse(data).toString());
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    builder.setContentIntent(contentIntent);

    final Notification notification = builder.build();
    if (vibrationEnabled) {
        notification.defaults |= Notification.DEFAULT_VIBRATE;
    }
    if (permanent) {
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
    }
    mNotificationManager.notify(Constants.NOTIFICATION_ID, notification);
}