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.airbop.client.GCMIntentService.java

private static void generateNotification(Context context, String title, String message, String url,
        String large_icon) {//  w w  w  .  j av  a 2  s  . c  om

    int icon = R.drawable.ic_stat_gcm;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    if ((title == null) || (title.equals(""))) {
        title = context.getString(R.string.app_name);
    }

    Intent notificationIntent = null;
    if ((url == null) || (url.equals(""))) {
        //just bring up the app
        notificationIntent = new Intent(context, DemoActivity.class);
    } else {
        //Launch the URL
        notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setData(Uri.parse(url));
        notificationIntent.addCategory(Intent.CATEGORY_BROWSABLE);
    }

    // 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 notification = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(message).setContentIntent(intent).setSmallIcon(icon)
            .setLargeIcon(decodeImage(large_icon)).setWhen(when)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(message)).build();

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);
}

From source file:cl.iluminadoschile.pako.floatingdiv.CustomOverlayService.java

@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    if (Constants.SETTINGS.ACTIVATION_METHOD_KEY.equals(key)) {
        activation_method = prefs.getString(Constants.SETTINGS.ACTIVATION_METHOD_KEY,
                Constants.SETTINGS.ACTIVATION_METHOD_ALONGWITHINGRESS);
        if (android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            if (activation_method.equals(Constants.SETTINGS.ACTIVATION_METHOD_ALONGWITHINGRESS)) {
                startMonitorIngressRunning();
            } else {
                stoptMonitorIngressRunning();
            }/*ww  w.  jav  a 2s  .  com*/
        }
        Toast.makeText(CustomOverlayService.instance, "Service needs to restart to reflect changes",
                Toast.LENGTH_SHORT).show();
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE);

        Notification notification = foregroundNotification(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE);
        mNotificationManager.notify(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, notification);
    }
}

From source file:com.a3did.partner.recosample.RecoBackgroundMonitoringService.java

private void popupNotification(String msg) {
    Log.i("BackMonitoringService", "popupNotification()");
    String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.KOREA).format(new Date());
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_menu_camera).setContentTitle(msg + " " + currentTime)
            .setContentText(msg);//from ww w  . j ava 2s  .co  m

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    builder.setStyle(inboxStyle);
    nm.notify(mNotificationID, builder.build());
    mNotificationID = (mNotificationID - 1) % 1000 + 9000;
}

From source file:com.ravi.apps.android.newsbytes.sync.NewsSyncAdapter.java

/**
 * Notifies the user that fresh news updates are now available.
 *//*ww w  . j a  va2s.  c o  m*/
private void sendNewsNotification(Context context) {
    // Create the intent to open the app when the user taps on the notification.
    Intent mainIntent = new Intent(context, MainActivity.class);

    // Create the stack builder object.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);

    // Add the intent to the top of the stack.
    stackBuilder.addNextIntent(mainIntent);

    // Get a pending intent containing the entire back stack.
    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    // Create the notification builder object.
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    // Set the pending intent onto the notification.
    builder.setContentIntent(pendingIntent);

    // Set the notification to automatically dismiss after the user taps it.
    builder.setAutoCancel(true);

    // Set the notification title and text.
    builder.setContentTitle(context.getString(R.string.app_name))
            .setContentText(context.getString(R.string.msg_notification_text));

    // Set the notification ticker.
    builder.setTicker(context.getString(R.string.msg_notification_text));

    // Set the notification large and small icons.
    builder.setSmallIcon(R.drawable.ic_notify_small)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_notify_large));

    // Send the notification.
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(context.NOTIFICATION_SERVICE);
    notificationManager.notify(NEWS_NOTIFICATION_ID, builder.build());
}

From source file:com.aniruddhc.acemusic.player.AsyncTasks.AsyncAutoGetAlbumArtTask.java

@Override
protected void onPostExecute(Void arg0) {

    Intent intent = new Intent(mContext, AutoFetchAlbumArtService.class);
    mContext.stopService(intent);/* www  . j  a  va 2 s.c o m*/

    if (pd.isShowing() && DIALOG_VISIBLE == true) {
        pd.dismiss();
    }

    //Dismiss the notification.
    AutoFetchAlbumArtService.builder
            .setTicker(mContext.getResources().getString(R.string.done_downloading_art));
    AutoFetchAlbumArtService.builder
            .setContentTitle(mContext.getResources().getString(R.string.done_downloading_art));
    AutoFetchAlbumArtService.builder.setSmallIcon(R.drawable.notif_icon);
    AutoFetchAlbumArtService.builder.setContentInfo(null);
    AutoFetchAlbumArtService.builder.setContentText(null);
    AutoFetchAlbumArtService.builder.setProgress(0, 0, false);
    AutoFetchAlbumArtService.notification = AutoFetchAlbumArtService.builder.build();
    AutoFetchAlbumArtService.notification.flags = Notification.FLAG_AUTO_CANCEL;

    NotificationManager notifyManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notifyManager.notify(AutoFetchAlbumArtService.NOTIFICATION_ID, AutoFetchAlbumArtService.notification);

    Toast.makeText(mContext, R.string.done_downloading_art, Toast.LENGTH_LONG).show();

    //Rescan for album art.
    //Seting the "RESCAN_ALBUM_ART" flag to true will force MainActivity to rescan the folders.
    sharedPreferences.edit().putBoolean("RESCAN_ALBUM_ART", true).commit();

    //Restart the app.
    final Intent i = mActivity.getBaseContext().getPackageManager()
            .getLaunchIntentForPackage(mActivity.getBaseContext().getPackageName());

    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    mActivity.startActivity(i);
    mActivity.finish();

}

From source file:at.flack.receiver.SmsReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    notify = sharedPrefs.getBoolean("notifications", true);
    vibrate = sharedPrefs.getBoolean("vibration", true);
    headsup = sharedPrefs.getBoolean("headsup", true);
    led_color = sharedPrefs.getInt("notification_light", -16776961);
    boolean all = sharedPrefs.getBoolean("all_sms", true);

    if (notify == false)
        return;//from   ww  w .j ava2s  . c  o  m

    Bundle bundle = intent.getExtras();
    SmsMessage[] msgs = null;
    String str = "";
    if (bundle != null) {
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];
        for (int i = 0; i < msgs.length; i++) {
            msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            str += msgs[i].getMessageBody().toString();
            str += "\n";
        }

        NotificationCompat.Builder mBuilder;

        if (main != null) {
            main.addNewMessage(str);
            return;
        }

        boolean use_profile_picture = false;
        Bitmap profile_picture = null;

        String origin_name = null;
        try {
            origin_name = getContactName(context, msgs[0].getDisplayOriginatingAddress());
            if (origin_name == null)
                origin_name = msgs[0].getDisplayOriginatingAddress();
        } catch (Exception e) {
        }
        if (origin_name == null)
            origin_name = "Unknown";
        try {
            profile_picture = RoundedImageView.getCroppedBitmap(Bitmap.createScaledBitmap(
                    fetchThumbnail(context, msgs[0].getDisplayOriginatingAddress()), 200, 200, false), 300);
            use_profile_picture = true;
        } catch (Exception e) {
            use_profile_picture = false;
        }

        Resources res = context.getResources();
        int positionOfBase64End = str.lastIndexOf("=");
        if (positionOfBase64End > 0 && Base64.isBase64(str.substring(0, positionOfBase64End))) {
            mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.raven_notification_icon)
                    .setContentTitle(origin_name).setColor(0xFFB71C1C)
                    .setContentText(res.getString(R.string.sms_receiver_new_encrypted)).setAutoCancel(true);
            if (use_profile_picture && profile_picture != null) {
                mBuilder = mBuilder.setLargeIcon(profile_picture);
            } else {
                mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                        context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
            }

        } else if (str.toString().charAt(0) == '%'
                && (str.toString().length() == 10 || str.toString().length() == 9)) {
            int lastIndex = str.toString().lastIndexOf("=");
            if (lastIndex > 0 && Base64.isBase64(str.toString().substring(1, lastIndex))) {
                mBuilder = new NotificationCompat.Builder(context).setContentTitle(origin_name)
                        .setColor(0xFFB71C1C)
                        .setContentText(res.getString(R.string.sms_receiver_handshake_received))
                        .setSmallIcon(R.drawable.raven_notification_icon).setAutoCancel(true);
                if (use_profile_picture && profile_picture != null) {
                    mBuilder = mBuilder.setLargeIcon(profile_picture);
                } else {
                    mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                            context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                }
            } else {
                return;
            }
        } else if (str.toString().charAt(0) == '%' && str.toString().length() >= 120
                && str.toString().length() < 125) { // DH Handshake
            int lastIndex = str.toString().lastIndexOf("=");
            if (lastIndex > 0 && Base64.isBase64(str.toString().substring(1, lastIndex))) {
                mBuilder = new NotificationCompat.Builder(context).setContentTitle(origin_name)
                        .setColor(0xFFB71C1C)
                        .setContentText(res.getString(R.string.sms_receiver_handshake_received))
                        .setSmallIcon(R.drawable.raven_notification_icon).setAutoCancel(true);
                if (use_profile_picture && profile_picture != null) {
                    mBuilder = mBuilder.setLargeIcon(profile_picture);
                } else {
                    mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                            context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                }
            } else {
                return;
            }
        } else { // unencrypted messages
            if (all) {
                mBuilder = new NotificationCompat.Builder(context).setContentTitle(origin_name)
                        .setColor(0xFFB71C1C).setContentText(str).setAutoCancel(true)
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(str))
                        .setSmallIcon(R.drawable.raven_notification_icon);
                if (use_profile_picture && profile_picture != null) {
                    mBuilder = mBuilder.setLargeIcon(profile_picture);
                } else {
                    mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                            context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                }
            } else {
                return;
            }
        }

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);
        mBuilder.setLights(led_color, 750, 4000);
        if (vibrate) {
            mBuilder.setVibrate(new long[] { 0, 100, 200, 300 });
        }

        Intent resultIntent = new Intent(context, MainActivity.class);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        resultIntent.putExtra("CONTACT_NUMBER", msgs[0].getOriginatingAddress());

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        if (Build.VERSION.SDK_INT >= 16 && headsup)
            mBuilder.setPriority(Notification.PRIORITY_HIGH);
        if (Build.VERSION.SDK_INT >= 21)
            mBuilder.setCategory(Notification.CATEGORY_MESSAGE);

        final NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED") && !MainActivity.isOnTop)
            mNotificationManager.notify(7, mBuilder.build());

        // Save SMS if default app
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT
                && Telephony.Sms.getDefaultSmsPackage(context).equals(context.getPackageName())) {
            ContentValues values = new ContentValues();
            values.put("address", msgs[0].getDisplayOriginatingAddress());
            values.put("body", str.replace("\n", "").replace("\r", ""));

            if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED"))
                context.getContentResolver().insert(Telephony.Sms.Inbox.CONTENT_URI, values);

        }
    }

}

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

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

    builder.setContent(buildContent(0)).setTicker(getText(R.string.ticker), buildTicker())
            .setContentIntent(buildContentIntent()).setLargeIcon(buildLargeIcon())
            .setSmallIcon(R.drawable.ic_stat_notif_small_icon).setOngoing(true);

    Notification notif = builder.build();

    for (int i = 0; i < 20; i++) {
        notif.contentView.setProgressBar(android.R.id.progress, 100, i * 5, false);
        mgr.notify(NOTIFICATION_ID, notif);

        if (i == 0) {
            notif.tickerText = null;/*  www . j ava2  s  .c  o m*/
            notif.tickerView = null;
        }

        SystemClock.sleep(1000);
    }

    mgr.cancel(NOTIFICATION_ID);
}

From source file:com.airbop.client.GCMIntentService.java

private static void generateImageNotification(Context context, String title, String message, String url,
        String image_url, String large_icon) {

    // The bitmap to download
    Bitmap message_bitmap = null;/* w  w w .  java2s  .  co  m*/
    // Should we download the image?
    if ((image_url != null) && (!image_url.equals(""))) {
        message_bitmap = AirBopImageDownloader.downloadBitmap(image_url);
    }
    // If we didn't get the image, we're out of here
    if (message_bitmap == null) {
        generateNotification(context, title, message, url, large_icon);
        return;
    }

    int icon = R.drawable.ic_stat_gcm;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    if ((title == null) || (title.equals(""))) {
        title = context.getString(R.string.app_name);
    }

    Intent notificationIntent = null;
    if ((url == null) || (url.equals(""))) {
        //just bring up the app
        notificationIntent = new Intent(context, DemoActivity.class);
    } else {
        //Launch the URL
        notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setData(Uri.parse(url));
        notificationIntent.addCategory(Intent.CATEGORY_BROWSABLE);
    }

    // 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 notification = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(message).setContentIntent(intent).setSmallIcon(icon)
            .setLargeIcon(decodeImage(large_icon)).setWhen(when)
            .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(message_bitmap)).build();

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);
}

From source file:de.appplant.cordova.plugin.notification.NotificationWrapper.java

/**
 * Shows the notification//from w  w  w  .j  ava  2s  .  c o  m
 */
@SuppressWarnings("deprecation")
public void showNotification(Builder notification, Options options) {
    NotificationManager mgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    int id = 0;

    try {
        id = Integer.parseInt(options.getId());
    } catch (Exception e) {
    }

    if (Build.VERSION.SDK_INT < 16) {
        // build notification for HoneyComb to ICS
        mgr.notify(id, notification.getNotification());
    } else if (Build.VERSION.SDK_INT > 15) {
        // Notification for Jellybean and above
        mgr.notify(id, notification.build());
    }
}

From source file:com.chrynan.guitartuner.NotificationPublishReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setContentTitle(NOTIFICATION_TITLE);
    builder.setContentText(NOTIFICATION_TEXT);
    builder.setSmallIcon(R.mipmap.ic_launcher);
    builder.setAutoCancel(true);//from  w w w .  j  av a 2 s . co m
    Intent i = new Intent(context, TunerActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, REQUEST_CODE, i, 0);
    builder.setContentIntent(pendingIntent);
    notificationManager.notify(ID, builder.build());
}