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(String tag, int id, Notification notification) 

Source Link

Document

Post a notification to be shown in the status bar.

Usage

From source file:com.baasbox.android.samples.aloa.receive.NewMessageNotification.java

@TargetApi(Build.VERSION_CODES.ECLAIR)
private static void notify(final Context context, final Notification notification) {
    final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
        nm.notify(NOTIFICATION_TAG, 0, notification);
    } else {/*ww  w . jav a  2 s.c o m*/
        nm.notify(NOTIFICATION_TAG.hashCode(), notification);
    }
}

From source file:com.android.usbtuner.setup.TunerSetupActivity.java

/**
 * Sends the recommendation card to start the USB tuner TV input setup activity.
 *
 * @param context a {@link Context} instance
 *///from w  w w.j  a v  a  2  s .  co m
private static void sendRecommendationCard(Context context) {
    Resources resources = context.getResources();
    String focusedTitle = resources.getString(R.string.ut_setup_recommendation_card_focused_title);
    String title = resources.getString(R.string.ut_setup_recommendation_card_title);
    Bitmap largeIcon = BitmapFactory.decodeResource(resources, R.drawable.recommendation_antenna);

    // Build and send the notification.
    Notification notification = new NotificationCompat.BigPictureStyle(new NotificationCompat.Builder(context)
            .setAutoCancel(false).setContentTitle(focusedTitle).setContentText(title).setContentInfo(title)
            .setCategory(Notification.CATEGORY_RECOMMENDATION).setLargeIcon(largeIcon)
            .setSmallIcon(resources.getIdentifier(TAG_ICON, TAG_DRAWABLE, context.getPackageName()))
            .setContentIntent(createPendingIntentForSetupActivity(context))).build();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFY_TAG, NOTIFY_ID, notification);
}

From source file:com.android.tv.tuner.setup.TunerSetupActivity.java

/**
 * Sends the recommendation card to start the tuner TV input setup activity.
 *
 * @param context a {@link Context} instance
 *//*  w ww. ja v  a2 s . c om*/
private static void sendRecommendationCard(Context context, String contentTitle, String contentText,
        Bitmap largeIcon) {
    // Build and send the notification.
    Notification notification = new NotificationCompat.BigPictureStyle(new NotificationCompat.Builder(context)
            .setAutoCancel(false).setContentTitle(contentTitle).setContentText(contentText)
            .setContentInfo(contentText).setCategory(Notification.CATEGORY_RECOMMENDATION)
            .setLargeIcon(largeIcon)
            .setSmallIcon(
                    context.getResources().getIdentifier(TAG_ICON, TAG_DRAWABLE, context.getPackageName()))
            .setContentIntent(createPendingIntentForSetupActivity(context))).build();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFY_TAG, NOTIFY_ID, notification);
}

From source file:org.wso2.iot.agent.utils.CommonUtils.java

public static void displayNotification(Context context, int icon, String title, String message,
        Class<?> sourceActivityClass, String tag, int id) {
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
    mBuilder.setSmallIcon(icon);//from  w  w  w .  j  a v  a 2  s .c  o  m
    mBuilder.setContentTitle(title);
    mBuilder.setContentText(message);
    mBuilder.setOngoing(true);
    mBuilder.setOnlyAlertOnce(true);

    Intent resultIntent = new Intent(context, sourceActivityClass);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(sourceActivityClass);

    // 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);
    mBuilder.setContentIntent(resultPendingIntent);

    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(tag, id, mBuilder.build());
}

From source file:ch.bfh.instacircle.service.NetworkService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    // Initializing the dbHelper in order to get access to the database
    dbHelper = NetworkDbHelper.getInstance(this);

    // Create a pending intent which will be invoked after tapping on the
    // Android notification
    Intent notificationIntent = new Intent(this, NetworkActiveActivity.class);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
    PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            notificationIntent.getFlags());

    // Setting up the notification which is being displayed
    Notification.Builder notificationBuilder = new Notification.Builder(this);
    notificationBuilder.setContentTitle(getResources().getString(R.string.app_name));
    notificationBuilder.setContentText("An InstaCircle Chat session is running. Tap to bring in front.");
    notificationBuilder.setSmallIcon(R.drawable.glyphicons_244_conversation);
    notificationBuilder.setContentIntent(pendingNotificationIntent);
    notificationBuilder.setOngoing(true);
    Notification notification = notificationBuilder.getNotification();

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

    notificationManager.notify(TAG, 1, notification);

    udpBroadcastReceiverThreads = new UDPBroadcastReceiverThread[100];
    tcpUnicastReceiverThreads = new TCPUnicastReceiverThread[100];

    // starting 100 threads allocating 100 Ports
    for (int i = 0; i < 50; i++) {
        udpBroadcastReceiverThreads[i] = new UDPBroadcastReceiverThread(this, i + 12300);
        tcpUnicastReceiverThreads[i] = new TCPUnicastReceiverThread(this, i + 12300);

        udpBroadcastReceiverThreads[i].start();
        tcpUnicastReceiverThreads[i].start();
    }// ww  w  .ja v a 2  s  . c om

    // Register a broadcastreceiver in order to get notification from the UI
    // when a message should be sent
    LocalBroadcastManager.getInstance(this).registerReceiver(messageSendReceiver,
            new IntentFilter("messageSend"));

    // Opening a conversation
    dbHelper.openConversation(getSharedPreferences(PREFS_NAME, 0).getString("password", "N/A"));

    // joining the conversation using the identification in the preferences
    // file
    joinNetwork(getSharedPreferences(PREFS_NAME, 0).getString("identification", "N/A"));

    // start the NetworkActiveActivity
    intent = new Intent(this, NetworkActiveActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
    startActivity(intent);
    return super.onStartCommand(intent, flags, startId);
}

From source file:com.facebook.notifications.NotificationsManager.java

/**
 * Present a {@link Notification} to be presented from a GCM push bundle.
 * <p/>/*from   w  w w.  j  a  va2s . co m*/
 * This does not present a notification immediately, instead it caches the assets from the
 * notification bundle, and then presents a notification to the user. This allows for a smoother
 * interaction without loading indicators for the user.
 * <p/>
 * Note that only one notification can be created for a specific push bundle, should you attempt
 * to present a new notification with the same payload bundle as an existing notification, it will
 * replace and update the old notification.
 *
 * @param context              The context to send the notification from
 * @param notificationBundle   The content of the push notification
 * @param launcherIntent       The launcher intent that contains your Application's activity.
 *                             This will be modified with the FLAG_ACTIVITY_CLEAR_TOP and
 *                             FLAG_ACTIVITY_SINGLE_TOP flags, in order to properly show the
 *                             notification in an already running application.
 *                             <p/>
 *                             Should you not want this behavior, you may use the notificationExtender
 *                             parameter to customize the contentIntent of the notification before
 *                             presenting it.
 * @param notificationExtender A nullable argument that allows you to customize the notification
 *                             before displaying it. Use this to configure Icons, text, sounds,
 *                             etc. before we pass the notification off to the OS.
 */
public static boolean presentNotification(@NonNull final Context context,
        @NonNull final Bundle notificationBundle, @NonNull final Intent launcherIntent,
        @Nullable final NotificationExtender notificationExtender) {
    final JSONObject alert;
    final int payloadHash;

    try {
        String payload = notificationBundle.getString(CARD_PAYLOAD_KEY);
        if (payload == null) {
            return false;
        }
        payloadHash = payload.hashCode();

        JSONObject payloadObject = new JSONObject(payload);
        alert = payloadObject.optJSONObject("alert") != null ? payloadObject.optJSONObject("alert")
                : new JSONObject();
    } catch (JSONException ex) {
        Log.e(LOG_TAG, "Error while parsing notification bundle JSON", ex);
        return false;
    }

    final boolean[] success = new boolean[1];

    final Thread backgroundThread = new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            prepareCard(context, notificationBundle, new PrepareCallback() {
                @Override
                public void onPrepared(@NonNull Intent presentationIntent) {
                    Intent contentIntent = new Intent(launcherIntent);
                    contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    contentIntent.putExtra(EXTRA_PAYLOAD_INTENT, presentationIntent);

                    NotificationManager manager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    Notification.Builder builder = new Notification.Builder(context)
                            .setSmallIcon(android.R.drawable.ic_dialog_alert)
                            .setContentTitle(alert.optString("title")).setContentText(alert.optString("body"))
                            .setAutoCancel(true)
                            .setContentIntent(PendingIntent.getActivity(context.getApplicationContext(),
                                    payloadHash, contentIntent, PendingIntent.FLAG_ONE_SHOT));

                    if (notificationExtender != null) {
                        builder = notificationExtender.extendNotification(builder);
                    }

                    manager.notify(NOTIFICATION_TAG, payloadHash, builder.getNotification());
                    success[0] = true;
                    Looper.myLooper().quit();
                }

                @Override
                public void onError(@NonNull Exception exception) {
                    Log.e(LOG_TAG, "Error while preparing card", exception);
                    Looper.myLooper().quit();
                }
            });

            Looper.loop();
        }
    });

    backgroundThread.start();

    try {
        backgroundThread.join();
    } catch (InterruptedException ex) {
        Log.e(LOG_TAG, "Failed to wait for background thread", ex);
        return false;
    }
    return success[0];
}

From source file:com.android.tv.tuner.setup.TunerSetupActivity.java

private static void sendNotificationInternal(Context context, String contentTitle, String contentText) {
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.createNotificationChannel(new NotificationChannel(TUNER_SET_UP_NOTIFICATION_CHANNEL_ID,
            context.getResources().getString(R.string.ut_setup_notification_channel_name),
            NotificationManager.IMPORTANCE_HIGH));
    Notification notification = new Notification.Builder(context, TUNER_SET_UP_NOTIFICATION_CHANNEL_ID)
            .setContentTitle(contentTitle).setContentText(contentText)
            .setSmallIcon(//from   w  ww. ja  v a  2 s  . c om
                    context.getResources().getIdentifier(TAG_ICON, TAG_DRAWABLE, context.getPackageName()))
            .setContentIntent(createPendingIntentForSetupActivity(context))
            .setVisibility(Notification.VISIBILITY_PUBLIC).extend(new Notification.TvExtender()).build();
    notificationManager.notify(NOTIFY_TAG, NOTIFY_ID, notification);
}

From source file:com.ntsync.android.sync.syncadapter.SyncAdapter.java

private void sendMissingKey(Account account, final String authToken, byte[] saltPwdCheck) {
    Intent intent = KeyPasswordActivity.createKeyPasswortActivity(mContext, account, authToken, saltPwdCheck);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
            .setSmallIcon(R.drawable.notif_key)
            .setContentTitle(String.format(mContext.getText(R.string.notif_missing_key).toString()))
            .setContentText(account.name).setAutoCancel(false).setOnlyAlertOnce(true)
            .setContentIntent(resultPendingIntent);

    NotificationManager mNotificationManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(account.name, Constants.NOTIF_MISSING_KEY, mBuilder.build());
}

From source file:com.codename1.impl.android.LocalNotificationPublisher.java

public void onReceive(Context context, Intent intent) {
    //Fire the notification to the display
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    Bundle extras = intent.getExtras();//from w  w w.  java 2 s .  c  om
    PendingIntent content = extras.getParcelable(NOTIFICATION_INTENT);
    Bundle b = extras.getParcelable(NOTIFICATION);
    LocalNotification notif = AndroidImplementation.createNotificationFromBundle(b);

    if (AndroidImplementation.BACKGROUND_FETCH_NOTIFICATION_ID.equals(notif.getId())) {
        PendingIntent backgroundFetchIntent = extras.getParcelable(BACKGROUND_FETCH_INTENT);
        if (backgroundFetchIntent != null) {
            try {
                backgroundFetchIntent.send();
            } catch (Exception ex) {
                Log.e("Codename One", "Failed to send BackgroundFetchHandler intent", ex);
            }
        } else {
            Log.d("Codename One", "BackgroundFetch intent was null");
        }
    } else {
        Notification notification = createAndroidNotification(context, notif, content);
        notification.when = System.currentTimeMillis();
        try {
            int notifId = Integer.parseInt(notif.getId());
            notificationManager.notify("CN1", notifId, notification);
        } catch (Exception e) {
            //that was a mistake, the first param is the tag not the id
            notificationManager.notify(notif.getId(), 0, notification);
        }
    }
}

From source file:com.github.vseguip.sweet.contacts.SweetContactSync.java

@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {
    Log.i(TAG, "onPerformSync()");
    // Get preferences
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
    boolean fullSync = settings.getBoolean(mContext.getString(R.string.full_sync), false);
    if (fullSync)
        mAccountManager.setUserData(account, LAST_SYNC_KEY, null);
    performNetOperation(new SugarRunnable(account, syncResult, new ISugarRunnable() {
        @Override/*from   w  w  w  .  j a v a  2 s  .co  m*/
        public void run() throws URISyntaxException, OperationCanceledException, AuthenticatorException,
                IOException, AuthenticationException {
            Log.i(TAG, "Running PerformSync closure()");

            mAuthToken = mAccountManager.blockingGetAuthToken(account, AUTH_TOKEN_TYPE, true);
            SugarAPI sugar = SugarAPIFactory.getSugarAPI(mAccountManager, account);
            String lastDate = mAccountManager.getUserData(account, LAST_SYNC_KEY);
            List<ISweetContact> contacts = null;
            try {
                contacts = fetchContacts(sugar, lastDate);
            } catch (AuthenticationException ex) {
                // maybe expired session, invalidate token and request new
                // one
                mAccountManager.invalidateAuthToken(account.type, mAuthToken);
                mAuthToken = mAccountManager.blockingGetAuthToken(account, AUTH_TOKEN_TYPE, false);
            } catch (NullPointerException npe) {
                // maybe expired session, invalidate token and request new
                // one               
                mAccountManager.invalidateAuthToken(account.type, mAuthToken);
                mAuthToken = mAccountManager.blockingGetAuthToken(account, AUTH_TOKEN_TYPE, false);
            }
            // try again, it could be due to an expired session
            if (contacts == null) {
                contacts = fetchContacts(sugar, lastDate);
            }
            List<ISweetContact> modifiedContacts = ContactManager.getLocallyModifiedContacts(mContext, account);
            List<ISweetContact> createdContacts = ContactManager.getLocallyCreatedContacts(mContext, account);
            // Get latest date from server
            for (ISweetContact c : contacts) {
                String contactDate = c.getDateModified();
                if ((lastDate == null) || (lastDate.compareTo(contactDate) < 0)) {
                    lastDate = contactDate;
                }
            }
            // Determine conflicting contacts
            Set<String> conflictSet = getConflictSet(contacts, modifiedContacts);
            Map<String, ISweetContact> conflictingSugarContacts = filterIds(contacts, conflictSet);
            Map<String, ISweetContact> conflictingLocalContacts = filterIds(modifiedContacts, conflictSet);

            if (modifiedContacts.size() > 0) {
                // Send modified local non conflicting contacts to the
                // server
                List<String> newIds = sugar.sendNewContacts(mAuthToken, modifiedContacts, false);
                if (newIds.size() != modifiedContacts.size()) {
                    throw new OperationCanceledException("Error updating local contacts in the remote server");
                }
                ContactManager.cleanDirtyFlag(mContext, modifiedContacts);
            }
            if (createdContacts.size() > 0) {
                List<String> newIds = sugar.sendNewContacts(mAuthToken, createdContacts, true);
                if (newIds.size() != createdContacts.size()) {
                    // something wrong happened, it's probable the user will
                    // have to clear the data
                    throw new OperationCanceledException("Error creating local contacts in the remote server");
                }
                ContactManager.assignSourceIds(mContext, createdContacts, newIds);
                ContactManager.cleanDirtyFlag(mContext, createdContacts);
            }
            // Sync remote contacts locally.
            if (contacts.size() > 0) {
                ContactManager.syncContacts(mContext, account, contacts);
            }
            // resolve remaining conflicts
            List<ISweetContact> resolvedContacts = new ArrayList<ISweetContact>();
            for (String id : conflictSet) {
                ISweetContact local = conflictingLocalContacts.get(id);
                ISweetContact remote = conflictingSugarContacts.get(id);
                if (local.equals(remote)) {
                    // no need to sync
                    resolvedContacts.add(local);
                    conflictingLocalContacts.remove(id);
                    conflictingSugarContacts.remove(id);
                } else {
                    Log.i(TAG, "Local contact differs from remote contact " + local.getFirstName() + " "
                            + local.getLastName());
                    if (local.equalUIFields(remote)) {
                        // Differed in a non visible field like the account
                        // id or similar, use server version and resolve
                        // automatically
                        resolvedContacts.add(remote);
                        conflictingLocalContacts.remove(id);
                        conflictingSugarContacts.remove(id);
                    }
                }

            }
            ContactManager.cleanDirtyFlag(mContext, resolvedContacts);
            if (conflictingLocalContacts.size() > 0) {
                // Create a notification that can launch an mActivity to
                // resolve the pending conflict
                NotificationManager nm = (NotificationManager) mContext
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                Notification notify = new Notification(R.drawable.icon,
                        mContext.getString(R.string.notify_sync_conflict_ticket), System.currentTimeMillis());
                Intent intent = new Intent(mContext, SweetConflictResolveActivity.class);
                intent.putExtra("account", account);
                SweetConflictResolveActivity.storeConflicts(conflictingLocalContacts, conflictingSugarContacts);

                notify.setLatestEventInfo(mContext, mContext.getString(R.string.notify_sync_conflict_title),
                        mContext.getString(R.string.notify_sync_conflict_message),
                        PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
                nm.notify(SweetConflictResolveActivity.NOTIFY_CONFLICT,
                        SweetConflictResolveActivity.NOTIFY_CONTACT, notify);

                throw new OperationCanceledException("Pending conflicts");
            }
            // Save the last sync time in the account if all went ok
            mAccountManager.setUserData(account, LAST_SYNC_KEY, lastDate);
        }
    }));
}