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:no.firestorm.weathernotificatonservice.WeatherNotificationService.java

/**
 * Make notification and post it to the NotificationManager
 * /*from w ww  .j av a2s .  co  m*/
 * @param tickerIcon
 *            Icon shown in notification bar
 * @param contentIcon
 *            Icon shown in notification
 * @param tickerText
 *            Text shown in notification bar
 * @param contentTitle
 *            Title shown in notification
 * @param contentText
 *            Description shown in notification
 * @param contentTime
 *            Time shown in notification
 * @param when2
 */
private void makeNotification(int tickerIcon, int contentIcon, CharSequence tickerText,
        CharSequence contentTitle, CharSequence contentText, CharSequence contentTime, long when2,
        Float temperature) {
    final long when = System.currentTimeMillis();
    // Make notification
    Notification notification = null;

    final Intent notificationIntent = new Intent(WeatherNotificationService.this,
            WeatherNotificationService.class);
    final PendingIntent contentIntent = PendingIntent.getService(WeatherNotificationService.this, 0,
            notificationIntent, 0);

    // Check if Notification.Builder exists (11+)
    if (Build.VERSION.SDK_INT >= 11) {
        // Honeycomb ++
        NotificationBuilder builder = new NotificationBuilder(this);
        builder.setAutoCancel(false);
        builder.setContentTitle(contentTitle);
        builder.setContentText(contentText);
        builder.setTicker(tickerText);
        builder.setWhen(when2);
        builder.setSmallIcon(tickerIcon);
        builder.setOngoing(true);
        builder.setContentIntent(contentIntent);
        if (temperature != null)
            builder.makeContentView(contentTitle, contentText, when2, temperature, tickerIcon);
        notification = builder.getNotification();
    } else {
        // Gingerbread --
        notification = new Notification(tickerIcon, tickerText, when);
        notification.flags = Notification.FLAG_ONGOING_EVENT;

        final RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.weathernotification);
        contentView.setImageViewResource(R.id.icon, contentIcon);
        contentView.setTextViewText(R.id.title, contentTitle);
        contentView.setTextViewText(R.id.title, contentTitle);
        contentView.setTextViewText(R.id.text, contentText);
        contentView.setTextViewText(R.id.time, contentTime);
        notification.contentView = contentView;
    }
    notification.contentIntent = contentIntent;

    // Post notification
    final NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(1, notification);
}

From source file:com.commonsware.android.sawmonitor.SAWDetector.java

static void seeSAW(Context ctxt, String pkg, String operation) {
    if (hasSAW(ctxt, pkg)) {
        Uri pkgUri = Uri.parse("package:" + pkg);
        Intent manage = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);

        manage.setData(pkgUri);// www  .j  a v a 2 s .c o  m

        Intent whitelist = new Intent(ctxt, WhitelistReceiver.class);

        whitelist.setData(pkgUri);

        Intent main = new Intent(ctxt, MainActivity.class);

        main.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

        NotificationManager mgr = (NotificationManager) ctxt.getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
                && mgr.getNotificationChannel(CHANNEL_WHATEVER) == null) {
            mgr.createNotificationChannel(new NotificationChannel(CHANNEL_WHATEVER, "Whatever",
                    NotificationManager.IMPORTANCE_DEFAULT));
        }

        NotificationCompat.Builder b = new NotificationCompat.Builder(ctxt, CHANNEL_WHATEVER);
        String text = String.format(ctxt.getString(R.string.msg_requested), operation, pkg);

        b.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).setWhen(System.currentTimeMillis())
                .setContentTitle(ctxt.getString(R.string.msg_detected)).setContentText(text)
                .setSmallIcon(android.R.drawable.stat_notify_error)
                .setTicker(ctxt.getString(R.string.msg_detected))
                .setContentIntent(PendingIntent.getActivity(ctxt, 0, manage, PendingIntent.FLAG_UPDATE_CURRENT))
                .addAction(R.drawable.ic_verified_user_24dp, ctxt.getString(R.string.msg_whitelist),
                        PendingIntent.getBroadcast(ctxt, 0, whitelist, 0))
                .addAction(R.drawable.ic_settings_24dp, ctxt.getString(R.string.msg_settings),
                        PendingIntent.getActivity(ctxt, 0, main, 0));

        mgr.notify(NOTIFY_ID, b.build());
    }
}

From source file:com.ayogo.cordova.notification.ScheduledNotificationManager.java

public void showNotification(ScheduledNotification scheduledNotification) {
    LOG.v(NotificationPlugin.TAG, "showNotification: " + scheduledNotification.toString());

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

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

    // Build the notification options
    builder.setDefaults(Notification.DEFAULT_ALL).setTicker(scheduledNotification.body)
            .setPriority(Notification.PRIORITY_HIGH).setAutoCancel(true);

    // TODO: add sound support
    // if (scheduledNotification.sound != null) {
    //     builder.setSound(sound);
    // }//from  w w w .j a  va 2  s .c  o m

    if (scheduledNotification.body != null) {
        builder.setContentTitle(scheduledNotification.title);
        builder.setContentText(scheduledNotification.body);
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(scheduledNotification.body));
    } else {
        //Default the title to the app name
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo applicationInfo = pm.getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);

            String appName = applicationInfo.loadLabel(pm).toString();

            builder.setContentTitle(appName);
            builder.setContentText(scheduledNotification.title);
            builder.setStyle(new NotificationCompat.BigTextStyle().bigText(scheduledNotification.title));
        } catch (NameNotFoundException e) {
            LOG.v(NotificationPlugin.TAG, "Failed to set title for notification!");
            return;
        }
    }

    if (scheduledNotification.badge != null) {
        LOG.v(NotificationPlugin.TAG, "showNotification: has a badge!");
        builder.setSmallIcon(getResIdForDrawable(scheduledNotification.badge));
    } else {
        LOG.v(NotificationPlugin.TAG, "showNotification: has no badge, use app icon!");
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo applicationInfo = pm.getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
            Resources resources = pm.getResourcesForApplication(applicationInfo);
            builder.setSmallIcon(applicationInfo.icon);
        } catch (NameNotFoundException e) {
            LOG.v(NotificationPlugin.TAG, "Failed to set badge for notification!");
            return;
        }
    }

    if (scheduledNotification.icon != null) {
        LOG.v(NotificationPlugin.TAG, "showNotification: has an icon!");
        builder.setLargeIcon(getIconFromUri(scheduledNotification.icon));
    } else {
        LOG.v(NotificationPlugin.TAG, "showNotification: has no icon, use app icon!");
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo applicationInfo = pm.getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
            Resources resources = pm.getResourcesForApplication(applicationInfo);
            Bitmap appIconBitmap = BitmapFactory.decodeResource(resources, applicationInfo.icon);
            builder.setLargeIcon(appIconBitmap);
        } catch (NameNotFoundException e) {
            LOG.v(NotificationPlugin.TAG, "Failed to set icon for notification!");
            return;
        }
    }

    Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
    launchIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    launchIntent.setAction("notification");

    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, launchIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);

    Notification notification = builder.build();

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    LOG.v(NotificationPlugin.TAG, "notify!");
    notificationManager.notify(scheduledNotification.tag.hashCode(), notification);
}

From source file:io.github.carlorodriguez.alarmon.AlarmClockService.java

private void refreshNotification() {
    String resolvedString = getString(R.string.no_pending_alarms);

    AlarmTime nextTime = pendingAlarms.nextAlarmTime();

    if (nextTime != null) {
        Map<String, String> values = new HashMap<>();

        values.put("t", nextTime.localizedString(getApplicationContext()));

        values.put("c", nextTime.timeUntilString(getApplicationContext()));

        String templateString = AppSettings.getNotificationTemplate(getApplicationContext());

        StrSubstitutor sub = new StrSubstitutor(values);

        resolvedString = sub.replace(templateString);
    }/*from  ww w.  j  ava2s . c  o m*/

    // Make the notification launch the UI Activity when clicked.
    final Intent notificationIntent = new Intent(this, ActivityAlarmClock.class);
    final PendingIntent launch = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Context c = getApplicationContext();

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

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

    if (pendingAlarms.nextAlarmId() != AlarmClockServiceBinder.NO_ALARM_ID) {
        DbAccessor db = new DbAccessor(getApplicationContext());

        AlarmInfo alarmInfo = db.readAlarmInfo(pendingAlarms.nextAlarmId());

        if (alarmInfo != null) {
            notificationTitle = alarmInfo.getName() != null && !alarmInfo.getName().isEmpty()
                    ? alarmInfo.getName()
                    : getString(R.string.app_name);
        }

        db.closeConnections();
    }

    Notification notification = builder.setContentIntent(launch).setSmallIcon(R.drawable.ic_stat_notify_alarm)
            .setContentTitle(notificationTitle).setContentText(resolvedString)
            .setColor(ContextCompat.getColor(getApplicationContext(), R.color.notification_color)).build();
    notification.flags |= Notification.FLAG_ONGOING_EVENT;

    final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (pendingAlarms.size() > 0 && AppSettings.displayNotificationIcon(c)) {
        manager.notify(NOTIFICATION_BAR_ID, notification);
    } else {
        manager.cancel(NOTIFICATION_BAR_ID);
    }

    setSystemAlarmStringOnLockScreen(getApplicationContext(), nextTime);
}

From source file:com.commonsware.android.prognotify.SillyService.java

@Override
protected void onHandleIntent(Intent intent) {
    NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    builder.setTicker(getText(R.string.ticker)).setContentTitle(getString(R.string.progress_notification))
            .setContentText(getString(R.string.busy)).setContentIntent(buildContentIntent())
            .setSmallIcon(R.drawable.ic_stat_notif_small_icon).setOngoing(true);

    for (int i = 0; i < 20; i++) {
        builder.setProgress(20, i, false);
        mgr.notify(NOTIFICATION_ID, builder.build());

        SystemClock.sleep(1000);/*from  ww  w . ja  v  a2s .c o m*/
    }

    builder.setContentText(getString(R.string.done)).setProgress(0, 0, false).setOngoing(false);

    mgr.notify(NOTIFICATION_ID, builder.build());
}

From source file:com.android.stockbrowser.WebStorageSizeManager.java

private void scheduleOutOfSpaceNotification() {
    if (LOGV_ENABLED) {
        Log.v(LOGTAG, "scheduleOutOfSpaceNotification called.");
    }/* w w  w.  jav a 2  s .  c  o  m*/
    if ((mLastOutOfSpaceNotificationTime == -1)
            || (System.currentTimeMillis() - mLastOutOfSpaceNotificationTime > NOTIFICATION_INTERVAL)) {
        // setup the notification boilerplate.
        int icon = android.R.drawable.stat_sys_warning;
        CharSequence title = mContext.getString(R.string.webstorage_outofspace_notification_title);
        CharSequence text = mContext.getString(R.string.webstorage_outofspace_notification_text);
        long when = System.currentTimeMillis();
        Intent intent = new Intent(mContext, BrowserPreferencesPage.class);
        intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT, WebsiteSettingsFragment.class.getName());
        PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext).setContentTitle(title)
                .setContentIntent(contentIntent).setContentText(text).setSmallIcon(icon).setAutoCancel(true);

        NotificationManager mgr = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        if (mgr != null) {
            mLastOutOfSpaceNotificationTime = System.currentTimeMillis();
            mgr.notify(OUT_OF_SPACE_ID, builder.build());
        }
    }
}

From source file:org.ametro.util.WebUtil.java

public static void downloadFileAsync(final Context appContext, final File path, final URI uri,
        final File temp) {

    final DownloadContext context = new DownloadContext();
    context.Path = path;//from w  w w .j a v a  2s  .  c om
    context.IsCanceled = false;
    context.IsUnpackFinished = false;
    context.IsFailed = false;

    final NotificationManager notificationManager = (NotificationManager) appContext
            .getSystemService(Context.NOTIFICATION_SERVICE);

    final Handler handler = new Handler();

    final Runnable updateProgress = new Runnable() {
        public void run() {
            if (context.Notification == null) {
                context.Notification = new Notification(android.R.drawable.stat_sys_download,
                        "Downloading icons", System.currentTimeMillis());
                context.Notification.flags = Notification.FLAG_NO_CLEAR;
                Intent notificationIntent = new Intent();
                context.ContentIntent = PendingIntent.getActivity(appContext, 0, notificationIntent, 0);
            }
            if (context.IsFailed) {
                notificationManager.cancelAll();
                context.Notification = new Notification(android.R.drawable.stat_sys_warning,
                        "Icons download failed", System.currentTimeMillis());
                context.Notification.setLatestEventInfo(appContext, "aMetro", "Icons downloaded failed",
                        context.ContentIntent);
                notificationManager.notify(2, context.Notification);

            } else if (context.IsUnpackFinished) {
                notificationManager.cancelAll();
                context.Notification = new Notification(android.R.drawable.stat_sys_download_done,
                        "Icons unpacked", System.currentTimeMillis());
                context.Notification.setLatestEventInfo(appContext, "aMetro", "Icons downloaded and unpacked.",
                        context.ContentIntent);
                notificationManager.notify(3, context.Notification);

            } else if (context.Position == 0 && context.Total == 0) {
                context.Notification.setLatestEventInfo(appContext, "aMetro",
                        "Download icons: connecting server", context.ContentIntent);
                notificationManager.notify(1, context.Notification);
            } else if (context.Position < context.Total) {
                context.Notification.setLatestEventInfo(appContext, "aMetro",
                        "Download icons: " + context.Position + "/" + context.Total, context.ContentIntent);
                notificationManager.notify(1, context.Notification);
            } else {
                context.Notification.setLatestEventInfo(appContext, "aMetro", "Icons unpacking",
                        context.ContentIntent);
                notificationManager.notify(1, context.Notification);
            }
        }
    };

    final Thread async = new Thread() {
        public void run() {
            WebUtil.downloadFile(context, uri, temp, false, new IDownloadListener() {

                public void onBegin(Object context, File file) {
                    DownloadContext downloadContext = (DownloadContext) context;
                    downloadContext.Total = 0;
                    downloadContext.Position = 0;
                    handler.removeCallbacks(updateProgress);
                    handler.post(updateProgress);
                }

                public boolean onUpdate(Object context, long position, long total) {
                    DownloadContext downloadContext = (DownloadContext) context;
                    downloadContext.Total = total;
                    downloadContext.Position = position;
                    handler.removeCallbacks(updateProgress);
                    handler.post(updateProgress);
                    return !downloadContext.IsCanceled;
                }

                public void onDone(Object context, File file) throws Exception {
                    DownloadContext downloadContext = (DownloadContext) context;
                    File path = downloadContext.Path;
                    ZipUtil.unzip(file, path);
                    downloadContext.IsUnpackFinished = true;
                    handler.removeCallbacks(updateProgress);
                    handler.post(updateProgress);
                }

                public void onCanceled(Object context, File file) {
                    DownloadContext downloadContext = (DownloadContext) context;
                    downloadContext.IsCanceled = true;
                    handler.removeCallbacks(updateProgress);
                    handler.post(updateProgress);
                }

                public void onFailed(Object context, File file, Throwable reason) {
                    DownloadContext downloadContext = (DownloadContext) context;
                    downloadContext.IsFailed = true;
                    handler.removeCallbacks(updateProgress);
                    handler.post(updateProgress);
                }

            });
        };
    };
    async.start();
}

From source file:com.skalski.websocketsclient.ActivityMain.java

@Override
public void onTextMessage(String payload) {

    try {//  w w w  .j  ava 2  s  .co m

        Log.i(TAG_LOG, "New message from server");
        JSONObject jsonObj = new JSONObject(payload);

        if ((jsonObj.has(TAG_JSON_TYPE)) && (jsonObj.has(TAG_JSON_MSG))) {

            /*
             * Notification
             */
            if (jsonObj.getString(TAG_JSON_TYPE).equals("notification")) {

                if (ActivitySettings.pref_notifications_disabled(getBaseContext())) {

                    Log.i(TAG_LOG, "Notifications are disabled");

                } else {

                    int notification_id;

                    if (ActivitySettings.pref_multiple_notifications_disabled(getBaseContext()))
                        notification_id = 0;
                    else
                        notification_id = (int) System.currentTimeMillis();

                    /* create new notification */
                    Notification new_notification = new Notification.Builder(this)
                            .setContentTitle(getResources().getString(R.string.app_name))
                            .setContentText(jsonObj.getString(TAG_JSON_MSG))
                            .setSmallIcon(R.drawable.ic_launcher).build();
                    new_notification.defaults |= Notification.DEFAULT_ALL;
                    NotificationManager notificationManager = (NotificationManager) getSystemService(
                            NOTIFICATION_SERVICE);
                    notificationManager.notify(notification_id, new_notification);

                    appendText(cmdOutput, "[SERVER] Asynchronous Notification\n",
                            Color.parseColor("#ff0099cc"));
                }

                /*
                 * Standard message
                 */
            } else if (jsonObj.getString(TAG_JSON_TYPE).equals("standard")) {

                appendText(cmdOutput, "[SERVER] " + jsonObj.getString(TAG_JSON_MSG) + "\n",
                        Color.parseColor("#ff99cc00"));

                /*
                 * JSON object is not valid
                 */
            } else {
                show_info(getResources().getString(R.string.info_msg_4), false);
                Log.e(TAG_LOG, "Received invalid JSON from server");
            }
        }
    } catch (JSONException e) {

        /* JSON object is not valid */
        show_info(getResources().getString(R.string.info_msg_4), false);
        Log.e(TAG_LOG, "Received invalid JSON from server");
    }
}

From source file:com.ntsync.android.sync.activities.PaymentVerificationService.java

private static void sendNotification(Context context, Account account, int msg,
        Class<? extends Activity> activityClass, boolean showMsg) {
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    Intent viewIntent = new Intent(context, activityClass);
    if (ShopActivity.class.equals(activityClass)) {
        // Vollstndige Meldung in der View anzeigen
        CharSequence msgText = context.getText(msg);
        if (showMsg) {
            // Show Full Message in ShopActivity
            viewIntent.putExtra(ShopActivity.PARM_MSG, String
                    .format(context.getText(R.string.shop_activity_delayedverif_failed).toString(), msgText));
        }/*w ww .  ja  va 2  s.co m*/
        viewIntent.putExtra(ShopActivity.PARM_ACCOUNT_NAME, account.name);
    }

    // Adds the back stack
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(activityClass);
    stackBuilder.addNextIntent(viewIntent);

    // Photo sync possible.
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(Constants.NOTIF_ICON).setContentTitle(context.getText(msg))
            .setContentText(account.name).setAutoCancel(true).setOnlyAlertOnce(true)
            .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
    notificationManager.notify(Constants.NOTIF_PAYMENT_VERIFICATIONRESULT, builder.build());
}