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.snappy.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *//*from  ww  w.jav a  2s  .  c o m*/
private void generateNotification(Context context, String message, String fromName, Bundle pushExtras,
        String body) {

    db = new LocalDB(context);
    List<LocalMessage> myMessages = db.getAllMessages();

    // Open a new activity called GCMMessageView
    Intent intento = new Intent(this, SplashScreenActivity.class);
    intento.replaceExtras(pushExtras);
    // Pass data to the new activity
    intento.putExtra(Const.PUSH_INTENT, true);
    intento.setAction(Long.toString(System.currentTimeMillis()));
    intento.addFlags(
            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_FROM_BACKGROUND | Intent.FLAG_ACTIVITY_TASK_ON_HOME);

    // Starts the activity on notification click
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intento, PendingIntent.FLAG_UPDATE_CURRENT);

    // Create the notification with a notification builder
    NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon_notification).setWhen(System.currentTimeMillis())
            .setContentTitle(myMessages.size() + " " + this.getString(R.string.push_new_message_message))
            .setStyle(new NotificationCompat.BigTextStyle().bigText("Mas mensajes")).setAutoCancel(true)
            .setDefaults(
                    Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS)
            .setContentText(body).setContentIntent(pIntent);

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    inboxStyle.setBigContentTitle(myMessages.size() + " " + this.getString(R.string.push_new_message_message));

    for (int i = 0; i < myMessages.size(); i++) {

        inboxStyle.addLine(myMessages.get(i).getMessage());
    }

    notification.setStyle(inboxStyle);

    // Remove the notification on click
    //notification.flags |= Notification.FLAG_AUTO_CANCEL;
    //notification.defaults |= Notification.DEFAULT_VIBRATE;
    //notification.defaults |= Notification.DEFAULT_SOUND;
    //notification.defaults |= Notification.DEFAULT_LIGHTS;

    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.notify(R.string.app_name, notification.build());
    {
        // Wake Android Device when notification received
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

        final PowerManager.WakeLock mWakelock = pm
                .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
        mWakelock.acquire();
        // Timer before putting Android Device to sleep mode.
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            public void run() {
                mWakelock.release();
            }
        };
        timer.schedule(task, 5000);
    }
}

From source file:ca.mudar.snoozy.receiver.PowerConnectionReceiver.java

private void notify(Context context, boolean isConnectedPower, boolean hasVibration, boolean hasSound,
        int notifyCount) {
    final Resources res = context.getResources();

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_notify).setContentTitle(res.getString(R.string.notify_content_title))
            .setAutoCancel(true);// w ww  . java 2s.c o m

    if (notifyCount == 1) {
        final int resContentTextSingle = (isConnectedPower ? R.string.notify_content_text_single_on
                : R.string.notify_content_text_single_off);
        mBuilder.setContentText(res.getString(resContentTextSingle));
    } else {
        mBuilder.setNumber(notifyCount).setContentText(res.getString(R.string.notify_content_text_multi));
    }

    if (hasVibration && hasSound) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND);
    } else if (hasVibration) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    } else if (hasSound) {
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
    }

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, MainActivity.class);
    final Bundle extras = new Bundle();
    extras.putBoolean(Const.IntentExtras.INCREMENT_NOTIFY_GROUP, true);
    extras.putBoolean(Const.IntentExtras.RESET_NOTIFY_NUMBER, true);
    resultIntent.putExtras(extras);
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    mBuilder.setContentIntent(
            PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    Intent receiverIntent = new Intent(context, PowerConnectionReceiver.class);
    receiverIntent.setAction(Const.IntentActions.NOTIFY_DELETE);
    PendingIntent deleteIntent = PendingIntent.getBroadcast(context, Const.RequestCodes.RESET_NOTIFY_NUMBER,
            receiverIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setDeleteIntent(deleteIntent);

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

    // NOTIFY_ID allows updates to the notification later on.
    mNotificationManager.notify(Const.NOTIFY_ID, mBuilder.build());
}

From source file:com.chess.genesis.net.GenesisNotifier.java

private void SendNotification(final int id, final String text) {
    final Intent intent;
    if (Pref.getBool(this, R.array.pf_tabletMode)) {
        intent = new Intent(this, MainMenuTablet.class);

        final Bundle bundle = new Bundle();
        bundle.putInt("loadFrag", Enums.ONLINE_LIST);
        intent.putExtras(bundle);//from  w  w w .  j a v  a2s.c o m
    } else {
        intent = new Intent(this, GameListOnline.class);
    }

    final PendingIntent pintent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    final Notification note = createNotification(id, text, pintent);

    nm.notify(id, note);
}

From source file:io.indy.drone.service.ScheduledService.java

public void createNotification() {
    // get the id of the latest strike
    String region = SQLDatabase.regionFromIndex(0); // worldwide
    String id = mDatabase.getRecentStrikeIdInRegion(region);
    Strike strike = mDatabase.getStrike(id);

    String title = getString(R.string.notification_preface) + " " + strike.getCountry();
    String droneSummary = strike.getDroneSummary();

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notification).setContentTitle(title).setContentText(droneSummary)
            .setAutoCancel(true);/*  ww  w  .j  a  v  a  2 s . c o m*/

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(this, StrikeDetailActivity.class);
    resultIntent.putExtra(SQLDatabase.KEY_ID, id);
    resultIntent.putExtra(SQLDatabase.REGION, region);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(StrikeDetailActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
        bigTextStyle.setBigContentTitle(title);
        bigTextStyle.bigText(strike.getBijSummaryShort());
        bigTextStyle.setSummaryText(droneSummary);

        // Moves the big view style object into the notification object.
        mBuilder.setStyle(bigTextStyle);
    }

    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    mNotificationManager.notify(33, mBuilder.build());
}

From source file:com.google.android.gms.location.sample.geofencing.GeofenceTransitionsIntentService.java

/**
 * Posts a notification in the notification bar when a transition is detected.
 * If the user clicks the notification, control goes to the MainActivity.
 *///from   w ww.j a va2 s .c om
private void sendNotification(String notificationDetails) {
    // Create an explicit content Intent that starts the main Activity.
    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    // Construct a task stack.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // Add the main Activity to the task stack as the parent.
    stackBuilder.addParentStack(MainActivity.class);

    // Push the content Intent onto the stack.
    stackBuilder.addNextIntent(notificationIntent);

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

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    // Define the notification settings.
    builder.setSmallIcon(R.drawable.ic_launcher)
            // In a real app, you may want to use a library like Volley
            // to decode the Bitmap.
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
            .setColor(Color.RED).setContentTitle(notificationDetails)
            .setContentText(getString(R.string.geofence_transition_notification_text))
            .setContentIntent(notificationPendingIntent);

    // Dismiss notification once the user touches it.
    builder.setAutoCancel(true);

    // Get an instance of the Notification manager
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    // Issue the notification
    mNotificationManager.notify(0, builder.build());
}

From source file:com.configurer.easyscreenlock.service.ForegroundSensorService.java

void handleCommand() {
    mBuilder = getBuilder();/*  www  .  j a  v a2  s . c  om*/

    Bitmap largeImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher);

    mBuilder.setSmallIcon(R.drawable.ic_launcher).setLargeIcon(largeImage)
            .setContentTitle(getString(R.string.app_name)).setContentText(getText(R.string.service_running))
            .setWhen(getPreviousTimeStamp());

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

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addNextIntent(resultIntent);

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

    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification late
    notificationManager.notify(AppUtils.notification_id, mBuilder.build());

    startForegroundCompat(AppUtils.notification_id, mBuilder.build());
}

From source file:com.bluros.updater.service.UpdateCheckService.java

private void recordAvailableUpdates(LinkedList<UpdateInfo> availableUpdates, Intent finishedIntent) {

    if (availableUpdates == null) {
        sendBroadcast(finishedIntent);/*from   ww  w  . j av  a  2 s.  c  om*/
        return;
    }

    // Store the last update check time and ensure boot check completed is true
    Date d = new Date();
    PreferenceManager.getDefaultSharedPreferences(UpdateCheckService.this).edit()
            .putLong(Constants.LAST_UPDATE_CHECK_PREF, d.getTime())
            .putBoolean(Constants.BOOT_CHECK_COMPLETED, true).apply();

    int realUpdateCount = finishedIntent.getIntExtra(EXTRA_REAL_UPDATE_COUNT, 0);
    UpdateApplication app = (UpdateApplication) getApplicationContext();

    // Write to log
    Log.i(TAG, "The update check successfully completed at " + d + " and found " + availableUpdates.size()
            + " updates (" + realUpdateCount + " newer than installed)");

    if (realUpdateCount != 0 && !app.isMainActivityActive()) {
        // There are updates available
        // The notification should launch the main app
        Intent i = new Intent(this, UpdatesSettings.class);
        i.putExtra(UpdatesSettings.EXTRA_UPDATE_LIST_UPDATED, true);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_ONE_SHOT);

        Resources res = getResources();
        String text = res.getQuantityString(R.plurals.not_new_updates_found_body, realUpdateCount,
                realUpdateCount);

        // Get the notification ready
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_system_update).setWhen(System.currentTimeMillis())
                .setTicker(res.getString(R.string.not_new_updates_found_ticker))
                .setContentTitle(res.getString(R.string.not_new_updates_found_title)).setContentText(text)
                .setContentIntent(contentIntent).setLocalOnly(true).setAutoCancel(true);

        LinkedList<UpdateInfo> realUpdates = new LinkedList<UpdateInfo>();
        for (UpdateInfo ui : availableUpdates) {
            if (ui.isNewerThanInstalled()) {
                realUpdates.add(ui);
            }
        }

        Collections.sort(realUpdates, new Comparator<UpdateInfo>() {
            @Override
            public int compare(UpdateInfo lhs, UpdateInfo rhs) {
                /* sort by date descending */
                long lhsDate = lhs.getDate();
                long rhsDate = rhs.getDate();
                if (lhsDate == rhsDate) {
                    return 0;
                }
                return lhsDate < rhsDate ? 1 : -1;
            }
        });

        NotificationCompat.InboxStyle inbox = new NotificationCompat.InboxStyle(builder)
                .setBigContentTitle(text);
        int added = 0, count = realUpdates.size();

        for (UpdateInfo ui : realUpdates) {
            if (added < EXPANDED_NOTIF_UPDATE_COUNT) {
                inbox.addLine(ui.getName());
                added++;
            }
        }
        if (added != count) {
            inbox.setSummaryText(
                    res.getQuantityString(R.plurals.not_additional_count, count - added, count - added));
        }
        builder.setStyle(inbox);
        builder.setNumber(availableUpdates.size());

        if (count == 1) {
            i = new Intent(this, DownloadReceiver.class);
            i.setAction(DownloadReceiver.ACTION_START_DOWNLOAD);
            i.putExtra(DownloadReceiver.EXTRA_UPDATE_INFO, (Parcelable) realUpdates.getFirst());
            PendingIntent downloadIntent = PendingIntent.getBroadcast(this, 0, i,
                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

            builder.addAction(R.drawable.ic_tab_download, res.getString(R.string.not_action_download),
                    downloadIntent);
        }

        // Trigger the notification
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.notify(R.string.not_new_updates_found_title, builder.build());
    }

    sendBroadcast(finishedIntent);
}

From source file:com.bcp.bcp.geofencing.GeofenceTransitionsIntentService.java

/**
 * Posts a notification in the notification bar when a transition is detected.
 * If the user clicks the notification, control goes to the MainActivity.
 *//*w ww .j a v a2  s .com*/
private void sendNotification(String notificationDetails) {
    // Create an explicit content Intent that starts the main Activity.
    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    // Construct a task stack.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // Add the main Activity to the task stack as the parent.
    stackBuilder.addParentStack(MainActivity.class);

    // Push the content Intent onto the stack.
    stackBuilder.addNextIntent(notificationIntent);

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

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    // Define the notification settings.
    builder.setSmallIcon(R.mipmap.ic_launcher)
            // In a real app, you may want to use a library like Volley
            // to decode the Bitmap.
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
            .setColor(Color.RED).setContentTitle(notificationDetails)
            .setContentText(getString(R.string.geofence_transition_notification_text))
            .setContentIntent(notificationPendingIntent);

    // Dismiss notification once the user touches it.
    builder.setAutoCancel(true);

    // Get an instance of the Notification manager
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    // Issue the notification
    mNotificationManager.notify(0, builder.build());
}

From source file:com.bhb27.isu.tools.Tools.java

public static void DoNotification(Context context) {

    NotificationCompat.Builder notification = new NotificationCompat.Builder(context);
    notification.setSmallIcon(R.drawable.ic_notification);
    notification.setContentTitle(context.getString(R.string.notification_title));
    notification.setOngoing(true);/*from   w w w  .  jav a2  s  .co  m*/
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(context.NOTIFICATION_SERVICE);

    Intent yesReceiver = new Intent();
    yesReceiver.setAction(Constants.YES_ACTION);
    PendingIntent pendingIntentYes = PendingIntent.getBroadcast(context, 12345, yesReceiver,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Action actiony = new NotificationCompat.Action.Builder(R.drawable.ic_notification,
            context.getString(R.string.yes), pendingIntentYes).build();
    notification.addAction(actiony);

    Intent dismissReceiver = new Intent();
    dismissReceiver.setAction(Constants.DISSMISS_ACTION);
    PendingIntent pendingIntentYes2 = PendingIntent.getBroadcast(context, 12345, dismissReceiver,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Action actionn = new NotificationCompat.Action.Builder(R.drawable.ic_notification,
            context.getString(R.string.dismiss), pendingIntentYes2).build();
    notification.addAction(actionn);

    notificationManager.notify(10, notification.build());
}