Example usage for android.app Notification FLAG_NO_CLEAR

List of usage examples for android.app Notification FLAG_NO_CLEAR

Introduction

In this page you can find the example usage for android.app Notification FLAG_NO_CLEAR.

Prototype

int FLAG_NO_CLEAR

To view the source code for android.app Notification FLAG_NO_CLEAR.

Click Source Link

Document

Bit to be bitwise-ored into the #flags field that should be set if the notification should not be canceled when the user clicks the Clear all button.

Usage

From source file:com.geecko.QuickLyric.broadcastReceiver.MusicBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    /** Google Play Music
     //bool streaming            long position
     //long albumId               String album
     //bool currentSongLoaded      String track
     //long ListPosition         long ListSize
     //long id                  bool playing
     //long duration            int previewPlayType
     //bool supportsRating         int domain
     //bool albumArtFromService      String artist
     //int rating               bool local
     //bool preparing            bool inErrorState
     *//*from w w w .  j  av a 2  s. c  om*/

    Bundle extras = intent.getExtras();
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
    boolean lengthFilter = sharedPref.getBoolean("pref_filter_20min", true);

    if (extras != null)
        try {
            extras.getInt("state");
        } catch (BadParcelableException e) {
            return;
        }

    if (extras == null || extras.getInt("state") > 1 //Tracks longer than 20min are presumably not songs
            || (lengthFilter && (extras.get("duration") instanceof Long && extras.getLong("duration") > 1200000)
                    || (extras.get("duration") instanceof Double && extras.getDouble("duration") > 1200000)
                    || (extras.get("duration") instanceof Integer && extras.getInt("duration") > 1200))
            || (lengthFilter && (extras.get("secs") instanceof Long && extras.getLong("secs") > 1200000)
                    || (extras.get("secs") instanceof Double && extras.getDouble("secs") > 1200000)
                    || (extras.get("secs") instanceof Integer && extras.getInt("secs") > 1200))
            || (extras.containsKey("com.maxmpz.audioplayer.source") && Build.VERSION.SDK_INT >= 19))
        return;

    String artist = extras.getString("artist");
    String track = extras.getString("track");
    long position = extras.containsKey("position") && extras.get("position") instanceof Long
            ? extras.getLong("position")
            : -1;
    if (extras.get("position") instanceof Double)
        position = Double.valueOf(extras.getDouble("position")).longValue();
    boolean isPlaying = extras.getBoolean(extras.containsKey("playstate") ? "playstate" : "playing", true);

    if (intent.getAction().equals("com.amazon.mp3.metachanged")) {
        artist = extras.getString("com.amazon.mp3.artist");
        track = extras.getString("com.amazon.mp3.track");
    } else if (intent.getAction().equals("com.spotify.music.metadatachanged"))
        isPlaying = spotifyPlaying;
    else if (intent.getAction().equals("com.spotify.music.playbackstatechanged"))
        spotifyPlaying = isPlaying;

    if ((artist == null || "".equals(artist)) //Could be problematic
            || (track == null || "".equals(track) || track.startsWith("DTNS"))) // Ignore one of my favorite podcasts
        return;

    SharedPreferences current = context.getSharedPreferences("current_music", Context.MODE_PRIVATE);
    String currentArtist = current.getString("artist", "");
    String currentTrack = current.getString("track", "");

    SharedPreferences.Editor editor = current.edit();
    editor.putString("artist", artist);
    editor.putString("track", track);
    if (!(artist.equals(currentArtist) && track.equals(currentTrack) && position == -1))
        editor.putLong("position", position);
    editor.putBoolean("playing", isPlaying);
    if (isPlaying) {
        long currentTime = System.currentTimeMillis();
        editor.putLong("startTime", currentTime);
    }
    editor.apply();

    autoUpdate = autoUpdate || sharedPref.getBoolean("pref_auto_refresh", false);
    int notificationPref = Integer.valueOf(sharedPref.getString("pref_notifications", "0"));

    if (autoUpdate && App.isActivityVisible()) {
        Intent internalIntent = new Intent("Broadcast");
        internalIntent.putExtra("artist", artist).putExtra("track", track);
        LyricsViewFragment.sendIntent(context, internalIntent);
        forceAutoUpdate(false);
    }

    boolean inDatabase = DatabaseHelper.getInstance(context)
            .presenceCheck(new String[] { artist, track, artist, track });

    if (notificationPref != 0 && isPlaying && (inDatabase || OnlineAccessVerifier.check(context))) {
        Intent activityIntent = new Intent("com.geecko.QuickLyric.getLyrics").putExtra("TAGS",
                new String[] { artist, track });
        Intent wearableIntent = new Intent("com.geecko.QuickLyric.SEND_TO_WEARABLE").putExtra("artist", artist)
                .putExtra("track", track);
        PendingIntent openAppPending = PendingIntent.getActivity(context, 0, activityIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        PendingIntent wearablePending = PendingIntent.getBroadcast(context, 8, wearableIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.Action wearableAction = new NotificationCompat.Action.Builder(R.drawable.ic_watch,
                context.getString(R.string.wearable_prompt), wearablePending).build();

        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(context);
        NotificationCompat.Builder wearableNotifBuilder = new NotificationCompat.Builder(context);

        int[] themes = new int[] { R.style.Theme_QuickLyric, R.style.Theme_QuickLyric_Red,
                R.style.Theme_QuickLyric_Purple, R.style.Theme_QuickLyric_Indigo,
                R.style.Theme_QuickLyric_Green, R.style.Theme_QuickLyric_Lime, R.style.Theme_QuickLyric_Brown,
                R.style.Theme_QuickLyric_Dark };
        int themeNum = Integer.valueOf(sharedPref.getString("pref_theme", "0"));

        TypedValue primaryColorValue = new TypedValue();
        context.setTheme(themes[themeNum]);
        context.getTheme().resolveAttribute(R.attr.colorPrimary, primaryColorValue, true);

        notifBuilder.setSmallIcon(R.drawable.ic_notif).setContentTitle(context.getString(R.string.app_name))
                .setContentText(String.format("%s - %s", artist, track)).setContentIntent(openAppPending)
                .setVisibility(-1) // Notification.VISIBILITY_SECRET
                .setGroup("Lyrics_Notification").setColor(primaryColorValue.data).setGroupSummary(true);

        wearableNotifBuilder.setSmallIcon(R.drawable.ic_notif)
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(String.format("%s - %s", artist, track)).setContentIntent(openAppPending)
                .setVisibility(-1) // Notification.VISIBILITY_SECRET
                .setGroup("Lyrics_Notification").setOngoing(false).setColor(primaryColorValue.data)
                .setGroupSummary(false)
                .extend(new NotificationCompat.WearableExtender().addAction(wearableAction));

        if (notificationPref == 2) {
            notifBuilder.setOngoing(true).setPriority(-2); // Notification.PRIORITY_MIN
            wearableNotifBuilder.setPriority(-2);
        } else
            notifBuilder.setPriority(-1); // Notification.PRIORITY_LOW

        Notification notif = notifBuilder.build();
        Notification wearableNotif = wearableNotifBuilder.build();

        if (notificationPref == 2)
            notif.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
        else
            notif.flags |= Notification.FLAG_AUTO_CANCEL;

        NotificationManagerCompat.from(context).notify(0, notif);
        try {
            context.getPackageManager().getPackageInfo("com.google.android.wearable.app",
                    PackageManager.GET_META_DATA);
            NotificationManagerCompat.from(context).notify(8, wearableNotif);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    } else if (track.equals(current.getString("track", "")))
        NotificationManagerCompat.from(context).cancel(0);
}

From source file:com.ubikod.capptain.android.sdk.reach.CapptainDefaultNotifier.java

@Override
public Boolean handleNotification(CapptainReachInteractiveContent content) throws RuntimeException {
    /* System notification case */
    if (content.isSystemNotification()) {
        /* Big picture handling */
        Bitmap bigPicture = null;/*from   ww w .  j  av a 2 s .c o m*/
        String bigPictureURL = content.getNotificationBigPicture();
        if (bigPictureURL != null && Build.VERSION.SDK_INT >= 16) {
            /* Schedule picture download if needed, or load picture if download completed. */
            Long downloadId = content.getDownloadId();
            if (downloadId == null) {
                NotificationUtilsV11.downloadBigPicture(mContext, content);
                return null;
            } else
                bigPicture = NotificationUtilsV11.getBigPicture(mContext, downloadId);
        }

        /* Generate notification identifier */
        int notificationId = getNotificationId(content);

        /* Build notification using support lib to manage compatibility with old Android versions */
        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);

        /* Icon for ticker and content icon */
        builder.setSmallIcon(mNotificationIcon);

        /*
         * Large icon, handled only since API Level 11 (needs down scaling if too large because it's
         * cropped otherwise by the system).
         */
        Bitmap notificationImage = content.getNotificationImage();
        if (notificationImage != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            builder.setLargeIcon(scaleBitmapForLargeIcon(mContext, notificationImage));

        /* Texts */
        String notificationTitle = content.getNotificationTitle();
        String notificationMessage = content.getNotificationMessage();
        String notificationBigText = content.getNotificationBigText();
        builder.setContentTitle(notificationTitle);
        builder.setContentText(notificationMessage);

        /*
         * Replay: display original date and don't replay all the tickers (be as quiet as possible
         * when replaying).
         */
        Long notificationFirstDisplayedDate = content.getNotificationFirstDisplayedDate();
        if (notificationFirstDisplayedDate != null)
            builder.setWhen(notificationFirstDisplayedDate);
        else
            builder.setTicker(notificationTitle);

        /* Big picture */
        if (bigPicture != null)
            builder.setStyle(new BigPictureStyle().bigPicture(bigPicture).setBigContentTitle(notificationTitle)
                    .setSummaryText(notificationMessage));

        /* Big text */
        else if (notificationBigText != null)
            builder.setStyle(new BigTextStyle().bigText(notificationBigText));

        /* Vibration/sound if not a replay */
        if (notificationFirstDisplayedDate == null) {
            int defaults = 0;
            if (content.isNotificationSound())
                defaults |= Notification.DEFAULT_SOUND;
            if (content.isNotificationVibrate())
                defaults |= Notification.DEFAULT_VIBRATE;
            builder.setDefaults(defaults);
        }

        /* Launch the receiver on action */
        Intent actionIntent = new Intent(INTENT_ACTION_ACTION_NOTIFICATION);
        CapptainReachAgent.setContentIdExtra(actionIntent, content);
        actionIntent.putExtra(INTENT_EXTRA_NOTIFICATION_ID, notificationId);
        Intent intent = content.getIntent();
        if (intent != null)
            actionIntent.putExtra(INTENT_EXTRA_COMPONENT, intent.getComponent());
        actionIntent.setPackage(mContext.getPackageName());
        PendingIntent contentIntent = PendingIntent.getBroadcast(mContext, (int) content.getLocalId(),
                actionIntent, FLAG_CANCEL_CURRENT);
        builder.setContentIntent(contentIntent);

        /* Also launch receiver if the notification is exited (clear button) */
        Intent exitIntent = new Intent(INTENT_ACTION_EXIT_NOTIFICATION);
        exitIntent.putExtra(INTENT_EXTRA_NOTIFICATION_ID, notificationId);
        CapptainReachAgent.setContentIdExtra(exitIntent, content);
        exitIntent.setPackage(mContext.getPackageName());
        PendingIntent deleteIntent = PendingIntent.getBroadcast(mContext, (int) content.getLocalId(),
                exitIntent, FLAG_CANCEL_CURRENT);
        builder.setDeleteIntent(deleteIntent);

        /* Can be dismissed ? */
        Notification notification = builder.build();
        if (!content.isNotificationCloseable())
            notification.flags |= Notification.FLAG_NO_CLEAR;

        /* Allow overriding */
        if (onNotificationPrepared(notification, content))

            /*
             * Submit notification, replacing the previous one if any (this should happen only if the
             * application process is restarted).
             */
            mNotificationManager.notify(notificationId, notification);
    }

    /* Activity embedded notification case */
    else {
        /* Get activity */
        Activity activity = CapptainActivityManager.getInstance().getCurrentActivity().get();

        /* Cannot notify in app if no activity provided */
        if (activity == null)
            return false;

        /* Get notification area */
        String category = content.getCategory();
        int areaId = getInAppAreaId(category);
        View notificationAreaView = activity.findViewById(areaId);

        /* No notification area, check if we can install overlay */
        if (notificationAreaView == null) {
            /* Check overlay is not disabled in this activity */
            Bundle activityConfig = CapptainUtils.getActivityMetaData(activity);
            if (!activityConfig.getBoolean(METADATA_NOTIFICATION_OVERLAY, true))
                return false;

            /* Inflate overlay layout and get reference to notification area */
            View overlay = LayoutInflater.from(mContext).inflate(getOverlayLayoutId(category), null);
            activity.addContentView(overlay, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
            notificationAreaView = activity.findViewById(areaId);
        }

        /* Otherwise check if there is an overlay containing the area to restore visibility */
        else {
            View overlay = activity.findViewById(getOverlayViewId(category));
            if (overlay != null)
                overlay.setVisibility(View.VISIBLE);
        }

        /* Make the notification area visible */
        notificationAreaView.setVisibility(View.VISIBLE);

        /* Prepare area */
        prepareInAppArea(content, notificationAreaView);
    }

    /* Success */
    return true;
}

From source file:com.microsoft.azure.engagement.engagement.AzmeNotifier.java

@Override
protected boolean onNotificationPrepared(Notification notification, EngagementReachInteractiveContent content)
        throws RuntimeException {

    if (content.isSystemNotification() == true) {
        // Read http://developer.android.com/guide/topics/ui/notifiers/notifications.html
        final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext);

        // "Large Icon" : the left icon
        if (content.getNotificationImage() != null) {
            notificationBuilder.setLargeIcon(content.getNotificationImage());
        }/*  w  ww. jav  a2  s  .c o m*/
        // "Small Icon": the small icon on the bottom right
        notificationBuilder.setSmallIcon(R.drawable.ic_notification_default);

        // "Content Title": the legacy notification title, i.e. the text on the top
        notificationBuilder.setContentTitle(content.getNotificationTitle());
        // "Content Text": the legacy notification text, i.e. the text on the bottom
        notificationBuilder.setContentText(content.getNotificationMessage());

        // The ticker text
        notificationBuilder.setTicker(notification.tickerText);

        // The notification settings
        notificationBuilder.setDefaults(notification.defaults);
        if (content.isNotificationCloseable() == false) {
            notificationBuilder.setAutoCancel(false);
        }
        notificationBuilder.setContent(notification.contentView);
        notificationBuilder.setContentIntent(notification.contentIntent);
        notificationBuilder.setDeleteIntent(notification.deleteIntent);
        notificationBuilder.setWhen(notification.when);

        if (content.getNotificationBigText() != null) {
            final BigTextStyle bigTextStyle = new BigTextStyle();
            bigTextStyle.setBigContentTitle(content.getNotificationTitle());
            bigTextStyle.setSummaryText(content.getNotificationMessage());
            bigTextStyle.bigText(content.getNotificationBigText());
            notificationBuilder.setStyle(bigTextStyle);
        } else if (content.getNotificationBigPicture() != null) {
            final BigPictureStyle bigPictureStyle = new BigPictureStyle();
            final Bitmap bitmap = EngagementNotificationUtilsV11.getBigPicture(this.mContext,
                    content.getDownloadId().longValue());
            bigPictureStyle.bigPicture(bitmap);
            bigPictureStyle.setSummaryText(content.getNotificationMessage());
            notificationBuilder.setStyle(bigPictureStyle);
        }

        // Retrieves the actionURL from the content
        final String actionURL;
        if (content instanceof EngagementAbstractAnnouncement == true) {
            actionURL = ((EngagementAbstractAnnouncement) content).getActionURL();
        } else {
            // We are receiving a poll notification
            actionURL = null;
        }

        if (actionURL != null) {
            final Uri actionUri = Uri.parse(actionURL);

            // Retrieves the specify parameters from the actionURL
            final boolean displayShareButton = actionUri.getBooleanQueryParameter("displayShareButton", false);
            final boolean displayFeedbackButton = actionUri.getBooleanQueryParameter("displayFeedbackButton",
                    false);

            if (displayFeedbackButton == true) {
                final Intent feedbackIntent = new Intent();
                feedbackIntent.setAction(Intent.ACTION_VIEW);
                final Uri data = Uri.parse("mailto:");
                feedbackIntent.putExtra(Intent.EXTRA_SUBJECT,
                        mContext.getString(R.string.notification_feedback_email_subject));
                feedbackIntent.setData(data);
                final PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, feedbackIntent, 0);

                notificationBuilder.addAction(R.drawable.ic_out_of_app_send_feedback,
                        mContext.getString(R.string.notification_feedback_button_title), pendingIntent);
            }

            if (displayShareButton == true) {
                final Intent sharingIntent = new Intent();
                sharingIntent.setAction(Intent.ACTION_SEND);
                sharingIntent.putExtra(Intent.EXTRA_TEXT,
                        mContext.getString(R.string.notification_share_message));
                sharingIntent.setType("text/plain");
                final PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, sharingIntent, 0);

                notificationBuilder.addAction(R.drawable.ic_out_of_app_share,
                        mContext.getString(R.string.notification_share_button_title), pendingIntent);
            }

        }

        /* Dismiss option can be managed only after build */
        final Notification finalNotification = notificationBuilder.build();
        if (content.isNotificationCloseable() == false) {
            finalNotification.flags |= Notification.FLAG_NO_CLEAR;
        }

        /* Notify here instead of super class */
        final NotificationManager manager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(getNotificationId(content), finalNotification); // notice the call to get the right identifier

        /* Return false, we notify ourselves */
        return false;
    } else {
        return super.onNotificationPrepared(notification, content);
    }
}

From source file:com.marianhello.bgloc.LocationService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    log.info("Received start startId: {} intent: {}", startId, intent);

    if (provider != null) {
        provider.onDestroy();//  ww w.  j a  v  a2  s. co  m
    }

    if (intent == null) {
        //service has been probably restarted so we need to load config from db
        ConfigurationDAO dao = DAOFactory.createConfigurationDAO(this);
        try {
            config = dao.retrieveConfiguration();
        } catch (JSONException e) {
            log.error("Config exception: {}", e.getMessage());
            config = new Config(); //using default config
        }
    } else {
        if (intent.hasExtra("config")) {
            config = intent.getParcelableExtra("config");
        } else {
            config = new Config(); //using default config
        }
    }

    log.debug("Will start service with: {}", config.toString());

    LocationProviderFactory spf = new LocationProviderFactory(this);
    provider = spf.getInstance(config.getLocationProvider());

    if (config.getStartForeground()) {
        // Build a Notification required for running service in foreground.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle(config.getNotificationTitle());
        builder.setContentText(config.getNotificationText());
        if (config.getSmallNotificationIcon() != null) {
            builder.setSmallIcon(getDrawableResource(config.getSmallNotificationIcon()));
        } else {
            builder.setSmallIcon(android.R.drawable.ic_menu_mylocation);
        }
        if (config.getLargeNotificationIcon() != null) {
            builder.setLargeIcon(BitmapFactory.decodeResource(getApplication().getResources(),
                    getDrawableResource(config.getLargeNotificationIcon())));
        }
        if (config.getNotificationIconColor() != null) {
            builder.setColor(this.parseNotificationIconColor(config.getNotificationIconColor()));
        }

        // Add an onclick handler to the notification
        Context context = getApplicationContext();
        String packageName = context.getPackageName();
        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        launchIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, launchIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(contentIntent);

        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE
                | Notification.FLAG_NO_CLEAR;
        startForeground(startId, notification);
    }

    provider.startRecording();

    //We want this service to continue running until it is explicitly stopped
    return START_STICKY;
}

From source file:com.callrecorder.android.RecordService.java

private void startService() {
    if (!onForeground) {
        Log.d(Constants.TAG, "RecordService startService");
        Intent intent = new Intent(this, MainActivity.class);
        // intent.setAction(Intent.ACTION_VIEW);
        // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, intent, 0);

        Notification notification = new NotificationCompat.Builder(getBaseContext())
                .setContentTitle(this.getString(R.string.notification_title))
                .setTicker(this.getString(R.string.notification_ticker))
                .setContentText(this.getString(R.string.notification_text)).setSmallIcon(R.drawable.ic_launcher)
                .setContentIntent(pendingIntent).setOngoing(true).getNotification();

        notification.flags = Notification.FLAG_NO_CLEAR;

        startForeground(1337, notification);
        onForeground = true;//from w  w  w. j  a va  2 s.c  om
    }
}

From source file:com.fututel.service.SipNotifications.java

public synchronized void notifyRegisteredAccounts(ArrayList<SipProfileState> activeAccountsInfos,
        boolean showNumbers) {
    if (!isServiceWrapper) {
        Log.e(THIS_FILE, "Trying to create a service notification from outside the service");
        return;//from   www .  ja  va 2  s  .c  om
    }

    int icon = R.drawable.ic_stat_sipok;
    CharSequence tickerText = context.getString(R.string.service_ticker_registered_text);
    long when = System.currentTimeMillis();

    Builder nb = new NotificationCompat.Builder(context);
    nb.setSmallIcon(icon);
    nb.setTicker(tickerText);
    nb.setWhen(when);
    Intent notificationIntent = new Intent(SipManager.ACTION_SIP_DIALER);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    RegistrationNotification contentView = new RegistrationNotification(context.getPackageName());
    contentView.clearRegistrations();
    if (!Compatibility.isCompatible(9)) {
        contentView.setTextsColor(notificationPrimaryTextColor);
    }
    contentView.addAccountInfos(context, activeAccountsInfos);

    // notification.setLatestEventInfo(context, contentTitle,
    // contentText, contentIntent);
    nb.setOngoing(true);
    nb.setOnlyAlertOnce(true);
    nb.setContentIntent(contentIntent);
    nb.setContent(contentView);

    Notification notification = nb.build();
    notification.flags |= Notification.FLAG_NO_CLEAR;

    // We have to re-write content view because getNotification setLatestEventInfo implicitly
    notification.contentView = contentView;
    if (showNumbers) {
        // This only affects android 2.3 and lower
        notification.number = activeAccountsInfos.size();
    }
    startForegroundCompat(REGISTER_NOTIF_ID, notification);
}

From source file:com.csipsimple.service.SipNotifications.java

public synchronized void notifyRegisteredAccounts(ArrayList<SipProfileState> activeAccountsInfos,
        boolean showNumbers) {
    if (!isServiceWrapper) {
        Log.e(THIS_FILE, "Trying to create a service notification from outside the service");
        return;//from  w  w  w .  j ava  2  s  .c  om
    }
    int icon = R.drawable.ic_stat_sipok;
    CharSequence tickerText = context.getString(R.string.service_ticker_registered_text);
    long when = System.currentTimeMillis();

    Builder nb = new NotificationCompat.Builder(context);
    nb.setSmallIcon(icon);
    nb.setTicker(tickerText);
    nb.setWhen(when);
    Intent notificationIntent = new Intent(SipManager.ACTION_SIP_DIALER);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    RegistrationNotification contentView = new RegistrationNotification(context.getPackageName());
    contentView.clearRegistrations();
    if (!Compatibility.isCompatible(9)) {
        contentView.setTextsColor(notificationPrimaryTextColor);
    }
    contentView.addAccountInfos(context, activeAccountsInfos);

    // notification.setLatestEventInfo(context, contentTitle,
    // contentText, contentIntent);
    nb.setOngoing(true);
    nb.setOnlyAlertOnce(true);
    nb.setContentIntent(contentIntent);
    nb.setContent(contentView);

    Notification notification = nb.build();
    notification.flags |= Notification.FLAG_NO_CLEAR;
    // We have to re-write content view because getNotification setLatestEventInfo implicitly
    notification.contentView = contentView;
    if (showNumbers) {
        // This only affects android 2.3 and lower
        notification.number = activeAccountsInfos.size();
    }
    startForegroundCompat(REGISTER_NOTIF_ID, notification);
}

From source file:com.sip.pwc.sipphone.service.SipNotifications.java

public synchronized void notifyRegisteredAccounts(ArrayList<SipProfileState> activeAccountsInfos,
        boolean showNumbers) {
    if (!isServiceWrapper) {
        Log.e(THIS_FILE, "Trying to create a service notification from outside the service");
        return;/*ww w  .  ja v a  2s.com*/
    }
    int icon = R.mipmap.ic_stat_sipok;
    CharSequence tickerText = context.getString(R.string.service_ticker_registered_text);
    long when = System.currentTimeMillis();

    Builder nb = new NotificationCompat.Builder(context);
    nb.setSmallIcon(icon);
    nb.setTicker(tickerText);
    nb.setWhen(when);
    Intent notificationIntent = new Intent(SipManager.ACTION_SIP_DIALER);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    RegistrationNotification contentView = new RegistrationNotification(context.getPackageName());
    contentView.clearRegistrations();
    if (!Compatibility.isCompatible(9)) {
        contentView.setTextsColor(notificationPrimaryTextColor);
    }
    contentView.addAccountInfos(context, activeAccountsInfos);

    // notification.setLatestEventInfo(context, contentTitle,
    // contentText, contentIntent);
    nb.setOngoing(true);
    nb.setOnlyAlertOnce(true);
    nb.setContentIntent(contentIntent);
    nb.setContent(contentView);

    Notification notification = nb.build();
    notification.flags |= Notification.FLAG_NO_CLEAR;
    // We have to re-write content view because getNotification setLatestEventInfo implicitly
    notification.contentView = contentView;
    if (showNumbers) {
        // This only affects android 2.3 and lower
        notification.number = activeAccountsInfos.size();
    }
    startForegroundCompat(REGISTER_NOTIF_ID, notification);
}

From source file:com.parrot.cyclops.CameraView.java

private void startCyclopsServiceForeground() {
    logdebug("startCyclopsServiceForeground");
    SystemProperties.setTvBusyByCyclops(true);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle(mContext.getString(R.string.notif_title))
            .setContentText(mContext.getString(R.string.notif_text));
    PendingIntent pendingIntent;//from ww  w . ja v a 2  s  .c o  m
    Intent intent = new Intent(mContext, CyclopsActivity.class);
    pendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    builder.setContentIntent(pendingIntent);
    builder.setPriority(NotificationCompat.PRIORITY_MAX);
    Notification notif = builder.build();
    notif.flags = Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR;
    mCyclopsService.startForeground(Cyclops.CYCLOPS_FOREGROUND_NOTIFICATION, notif);
}

From source file:com.voiceblue.phone.service.SipNotifications.java

public synchronized void notifyRegisteredAccounts(ArrayList<SipProfileState> activeAccountsInfos,
        boolean showNumbers) {
    if (!isServiceWrapper) {
        Log.e(THIS_FILE, "Trying to create a service notification from outside the service");
        return;//from  w  w  w  . j a v a 2  s.  c  o  m
    }

    int icon = R.drawable.ic_logo_flat_tiny;
    CharSequence tickerText = context.getString(R.string.service_ticker_registered_text);
    long when = System.currentTimeMillis();

    Builder nb = new NotificationCompat.Builder(context);
    nb.setSmallIcon(icon);
    nb.setTicker(tickerText);
    nb.setWhen(when);
    Intent notificationIntent = new Intent(SipManager.ACTION_SIP_DIALER);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    RegistrationNotification contentView = new RegistrationNotification(context.getPackageName());
    contentView.clearRegistrations();
    if (!Compatibility.isCompatible(9)) {
        contentView.setTextsColor(notificationPrimaryTextColor);
    }
    contentView.addAccountInfos(context, activeAccountsInfos);

    // notification.setLatestEventInfo(context, contentTitle,
    // contentText, contentIntent);
    nb.setOngoing(true);
    nb.setOnlyAlertOnce(true);
    nb.setContentIntent(contentIntent);
    nb.setContent(contentView);

    Notification notification = nb.build();
    notification.flags |= Notification.FLAG_NO_CLEAR;
    // We have to re-write content view because getNotification setLatestEventInfo implicitly
    notification.contentView = contentView;
    if (showNumbers) {
        // This only affects android 2.3 and lower
        notification.number = activeAccountsInfos.size();
    }
    startForegroundCompat(REGISTER_NOTIF_ID, notification);
}