Example usage for android.app Notification.Builder setSmallIcon

List of usage examples for android.app Notification.Builder setSmallIcon

Introduction

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

Prototype

@UnsupportedAppUsage
public void setSmallIcon(Icon icon) 

Source Link

Document

Used when notifying to clean up legacy small icons.

Usage

From source file:com.chasetech.pcount.autoupdate.AutoUpdateApk.java

protected void raise_notification() {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager nm = (NotificationManager) context.getSystemService(ns);

    String update_file = preferences.getString(UPDATE_FILE, "");

    if (update_file.length() > 0) {
        setChanged();/*  w  ww  .ja  v  a 2s .  co m*/
        notifyObservers(AUTOUPDATE_HAVE_UPDATE);

        // raise notification
        //            Notification notification = new Notification(
        //                    appIcon, appName + " update", System.currentTimeMillis());
        //            notification.flags |= NOTIFICATION_FLAGS;

        CharSequence contentTitle = appName + " update available";
        CharSequence contentText = "Click this to install..";
        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setDataAndType(
                Uri.parse("file://" + context.getFilesDir().getAbsolutePath() + "/" + update_file),
                ANDROID_PACKAGE);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

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

        builder.setAutoCancel(false);
        builder.setTicker("An update is available.");
        builder.setContentTitle(contentTitle);
        builder.setContentText(contentText);
        builder.setSmallIcon(appIcon);
        builder.setContentIntent(contentIntent);
        builder.setOngoing(true);
        builder.setSubText(appName + " update"); //API level 16
        builder.setNumber(100);
        builder.build();

        Notification myNotication = builder.getNotification();
        nm.notify(NOTIFICATION_ID, myNotication);

        //            notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        //            nm.notify( NOTIFICATION_ID, notification);
    } else {
        nm.cancel(NOTIFICATION_ID);
    }

    //      if( update_file.length() > 0 ) {
    //         setChanged();
    //         notifyObservers(AUTOUPDATE_HAVE_UPDATE);
    //
    //         // raise notification
    ///*         Notification notification = new Notification(
    //               appIcon, appName + " update", System.currentTimeMillis());*/
    //            Notification.Builder notifBuilder = new Notification.Builder(context);
    //         //notification.flags |= NOTIFICATION_FLAGS;
    //
    //         CharSequence contentTitle = appName + " update available";
    //         CharSequence contentText = "Select to install";
    //         Intent notificationIntent = new Intent(Intent.ACTION_VIEW );
    //         Uri uriFile = Uri.parse("file://" + context.getFilesDir().getAbsolutePath() + "/" + update_file);
    //         notificationIntent.setDataAndType(uriFile, ANDROID_PACKAGE);
    //         PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    //
    //            notifBuilder.setContentTitle(contentTitle);
    //            notifBuilder.setContentText(contentText);
    //            notifBuilder.setContentIntent(contentIntent);
    //            notifBuilder.setSubText("Update available.");
    //            notifBuilder.build();
    //
    //            Notification notification = notifBuilder.build();
    //            notification.flags |= NOTIFICATION_FLAGS;
    //
    //            nm.notify(NOTIFICATION_ID, notification);
    //
    //         //notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    //         //nm.notify( NOTIFICATION_ID, notification);
    //      } else {
    //         nm.cancel( NOTIFICATION_ID );
    //      }
}

From source file:hu.zelena.guide.MainActivity.java

/**
 * Verzi ellenrzs (async)/*from  w w w .ja  v a 2 s .  c o  m*/
 */

private void VersionNotify() {

    NotificationManager manager;
    Notification myNotication;

    manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Intent intent = new Intent(Intent.ACTION_VIEW);
    String url = "http://users.iit.uni-miskolc.hu/~zelena5/work/telekom/mobiltud/version/current/guide.apk";
    if (betaMode) {
        url = "http://users.iit.uni-miskolc.hu/~zelena5/work/telekom/mobiltud/version/beta/guide.apk";
    }

    intent.setData(Uri.parse(url));
    PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 1, intent, 0);

    Notification.Builder builder = new Notification.Builder(MainActivity.this);

    builder.setAutoCancel(false);
    builder.setTicker("j verzi rhet el");
    builder.setContentTitle("j verzi rhet el");
    builder.setContentText("Letltshez rintsd meg");
    builder.setSmallIcon(R.drawable.ic_stat_name);
    builder.setContentIntent(pendingIntent);
    builder.setSubText("Verzi vltozs"); //API level 16
    builder.setNumber(100);
    builder.build();
    builder.setAutoCancel(true);

    myNotication = builder.getNotification();
    manager.notify(11, myNotication);
}

From source file:com.marianhello.cordova.bgloc.LocationUpdateService.java

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "Received start id " + startId + ": " + intent);
        if (intent != null) {
            try {
                params = new JSONObject(intent.getStringExtra("params"));
                headers = new JSONObject(intent.getStringExtra("headers"));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//from   w w w .  java  2s . c  o  m
            }
            url = intent.getStringExtra("url");
            stationaryRadius = Float.parseFloat(intent.getStringExtra("stationaryRadius"));
            distanceFilter = Integer.parseInt(intent.getStringExtra("distanceFilter"));
            scaledDistanceFilter = distanceFilter;
            desiredAccuracy = Integer.parseInt(intent.getStringExtra("desiredAccuracy"));
            locationTimeout = Integer.parseInt(intent.getStringExtra("locationTimeout"));
            isDebugging = Boolean.parseBoolean(intent.getStringExtra("isDebugging"));
            notificationTitle = intent.getStringExtra("notificationTitle");
            notificationText = intent.getStringExtra("notificationText");

            // Build a Notification required for running service in foreground.
            Intent main = new Intent(this, BackgroundGpsPlugin.class);
            main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            Notification.Builder builder = new Notification.Builder(this);
            builder.setContentTitle(notificationTitle);
            builder.setContentText(notificationText);
            builder.setSmallIcon(android.R.drawable.ic_menu_mylocation);
            builder.setContentIntent(pendingIntent);
            Notification notification;
            if (android.os.Build.VERSION.SDK_INT >= 16) {
                notification = buildForegroundNotification(builder);
            } else {
                notification = buildForegroundNotificationCompat(builder);
            }
            notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE
                    | Notification.FLAG_NO_CLEAR;
            startForeground(startId, notification);
        }
        Log.i(TAG, "- url: " + url);
        Log.i(TAG, "- params: " + params.toString());
        Log.i(TAG, "- headers: " + headers.toString());
        Log.i(TAG, "- stationaryRadius: " + stationaryRadius);
        Log.i(TAG, "- distanceFilter: " + distanceFilter);
        Log.i(TAG, "- desiredAccuracy: " + desiredAccuracy);
        Log.i(TAG, "- locationTimeout: " + locationTimeout);
        Log.i(TAG, "- isDebugging: " + isDebugging);
        Log.i(TAG, "- notificationTitle: " + notificationTitle);
        Log.i(TAG, "- notificationText: " + notificationText);

        this.setPace(false);

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

From source file:com.ucmap.dingdinghelper.services.DingDingHelperAccessibilityService.java

private void increasePriority() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        Notification.Builder mBuilder = new Notification.Builder(this);
        mBuilder.setSmallIcon(R.mipmap.ic_launcher);
        startForeground(NOTIFICATION_ID, mBuilder.build());
        InnerService.startInnerService(this);
    } else {/*from   w w  w  . j  a v  a2  s .c  om*/
        startForeground(NOTIFICATION_ID, new Notification());
    }
}

From source file:com.android.mms.transaction.MessagingNotification.java

public static void blockingUpdateNewIccMessageIndicator(Context context, String address, String message,
        int subId, long timeMillis) {
    final Notification.Builder noti = new Notification.Builder(context).setWhen(timeMillis);
    Contact contact = Contact.get(address, false);
    NotificationInfo info = getNewIccMessageNotificationInfo(context, true /* isSms */, address, message,
            null /* subject */, subId, timeMillis, null /* attachmentBitmap */, contact, WorkingMessage.TEXT);
    noti.setSmallIcon(R.drawable.stat_notify_sms);
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    //        TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
    // Update the notification.
    PendingIntent pendingIntent;/*from ww w .  ja v  a 2 s  . c  o  m*/
    if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
        pendingIntent = PendingIntent.getActivity(context, 0, info.mClickIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    } else {
        // Use requestCode to avoid updating all intents of previous notifications
        pendingIntent = PendingIntent.getActivity(context, ICC_NOTIFICATION_ID_BASE + subId, info.mClickIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    }
    String title = info.mTitle;
    noti.setContentTitle(title).setContentIntent(pendingIntent)
            //taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT))
            .setCategory(Notification.CATEGORY_MESSAGE).setPriority(Notification.PRIORITY_DEFAULT);

    int defaults = 0;
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    boolean vibrate = false;
    if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) {
        // The most recent change to the vibrate preference is to store a boolean
        // value in NOTIFICATION_VIBRATE. If prefs contain that preference, use that
        // first.
        vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false);
    } else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) {
        // This is to support the pre-JellyBean MR1.1 version of vibrate preferences
        // when vibrate was a tri-state setting. As soon as the user opens the Messaging
        // app's settings, it will migrate this setting from NOTIFICATION_VIBRATE_WHEN
        // to the boolean value stored in NOTIFICATION_VIBRATE.
        String vibrateWhen = sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null);
        vibrate = "always".equals(vibrateWhen);
    }
    if (vibrate) {
        defaults |= Notification.DEFAULT_VIBRATE;
    }
    String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null);
    noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
    Log.d(TAG, "blockingUpdateNewIccMessageIndicator: adding sound to the notification");

    defaults |= Notification.DEFAULT_LIGHTS;

    noti.setDefaults(defaults);

    // set up delete intent
    noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0));

    final Notification notification;
    // This sets the text for the collapsed form:
    noti.setContentText(info.formatBigMessage(context));

    if (info.mAttachmentBitmap != null) {
        // The message has a picture, show that

        notification = new Notification.BigPictureStyle(noti).bigPicture(info.mAttachmentBitmap)
                // This sets the text for the expanded picture form:
                .setSummaryText(info.formatPictureMessage(context)).build();
    } else {
        // Show a single notification -- big style with the text of the whole message
        notification = new Notification.BigTextStyle(noti).bigText(info.formatBigMessage(context)).build();
    }

    notifyUserIfFullScreen(context, title);
    nm.notify(ICC_NOTIFICATION_ID_BASE + subId, notification);
}

From source file:fr.vassela.acrrd.notifier.TelephoneCallNotifier.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void displayNotification(Context context, String ticker, String contentTitle, String contentText,
        boolean autoCancel, boolean ongoingEvent, boolean activateEvent) {
    try {/*from   w ww.  ja  va 2 s .  com*/
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        boolean isPreferencesNotificationsActivated = sharedPreferences
                .getBoolean("preferences_notifications_activate", false);
        boolean isPreferencesNotificationsSoundActivated = sharedPreferences
                .getBoolean("preferences_notifications_sound_activate", false);
        boolean isPreferencesNotificationsVibrateActivated = sharedPreferences
                .getBoolean("preferences_notifications_vibrate_activate", false);
        boolean isPreferencesNotificationsLedActivated = sharedPreferences
                .getBoolean("preferences_notifications_led_activate", false);

        if (isPreferencesNotificationsActivated == true) {
            long notificationWhen = System.currentTimeMillis();
            int notificationDefaults = 0;

            Intent intent;

            if (ongoingEvent == true) {
                intent = new Intent(context, Main.class);
                intent.putExtra("setCurrentTab", "home");
            } else {
                intent = new Intent(SHOW_RECORDS);
            }

            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder notificationBuilder = new Notification.Builder(context);

            if (ongoingEvent == false) {
                notificationBuilder.setWhen(notificationWhen);
            }

            if (isPreferencesNotificationsSoundActivated == true) {
                notificationDefaults = notificationDefaults | Notification.DEFAULT_SOUND;
            }

            if (isPreferencesNotificationsVibrateActivated == true) {
                notificationDefaults = notificationDefaults | Notification.DEFAULT_VIBRATE;
            }

            if (isPreferencesNotificationsLedActivated == true) {
                notificationDefaults = notificationDefaults | Notification.DEFAULT_LIGHTS;
            }

            if (ongoingEvent == false) {
                notificationBuilder.setDefaults(notificationDefaults);
            }

            if (activateEvent == true) {
                notificationBuilder.setSmallIcon(R.drawable.presence_audio_online);
            } else {
                notificationBuilder.setSmallIcon(R.drawable.presence_audio_busy);
            }

            if (ongoingEvent == false) {
                notificationBuilder.setTicker(ticker);
            }

            notificationBuilder.setContentTitle(contentTitle);
            notificationBuilder.setContentText(contentText);
            notificationBuilder.setContentIntent(pendingIntent);
            notificationBuilder.setAutoCancel(autoCancel);
            notificationBuilder.setOngoing(ongoingEvent);

            Notification notification = notificationBuilder.build();

            if (ongoingEvent == true) {
                notificationManager.notify(getOngoingNotificationId(), notification);
            } else {
                notificationManager.notify(getNotificationId(), notification);
            }
        }
    } catch (Exception e) {
        Log.w("TelephoneCallNotifier", "displayNotification : " + context.getApplicationContext()
                .getString(R.string.log_telephone_call_notifier_error_display_notification) + " : " + e);
        databaseManager.insertLog(context.getApplicationContext(),
                "" + context.getApplicationContext()
                        .getString(R.string.log_telephone_call_notifier_error_display_notification),
                new Date().getTime(), 2, false);
    }
}

From source file:com.dwdesign.tweetings.activity.HomeActivity.java

public void connectToStream() {
    if (mPreferences.getBoolean(PREFERENCE_KEY_STREAMING_ENABLED, false) == true) {
        if (mService != null && twitterStream != null) {
            try {
                // user() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
                ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null) {
                    if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
                        hasStreamLoaded = true;
                        twitterStream.user();
                        if (mPreferences.getBoolean(PREFERENCE_KEY_STREAMING_NOTIFICATION, false) == true) {
                            NotificationManager notificationManager = (NotificationManager) getSystemService(
                                    Context.NOTIFICATION_SERVICE);
                            final Intent intent = new Intent(this, HomeActivity.class);
                            final Notification.Builder builder = new Notification.Builder(this);
                            builder.setOngoing(true);
                            builder.setContentIntent(PendingIntent.getActivity(this, 0, intent,
                                    PendingIntent.FLAG_UPDATE_CURRENT));
                            builder.setSmallIcon(R.drawable.ic_launcher);
                            builder.setContentTitle(getString(R.string.app_name));
                            builder.setContentText(getString(R.string.streaming_service_running));
                            builder.setTicker(getString(R.string.streaming_service_running));
                            notificationManager.notify(NOTIFICATION_ID_STREAMING, builder.build());
                        }//from  w w w.  j a v  a 2 s.c om
                    }
                }
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.mishiranu.dashchan.ui.navigator.NavigatorActivity.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override/*from  ww w  .jav a 2 s  .  co  m*/
public void onReadUpdateComplete(ReadUpdateTask.UpdateDataMap updateDataMap) {
    readUpdateTask = null;
    if (updateDataMap == null) {
        return;
    }
    Preferences.setLastUpdateCheck(System.currentTimeMillis());
    int count = PreferencesActivity.checkNewVersions(updateDataMap);
    if (count <= 0) {
        return;
    }
    Notification.Builder builder = new Notification.Builder(this);
    builder.setSmallIcon(R.drawable.ic_new_releases_white_24dp);
    String text = getString(R.string.text_updates_available_format, count);
    if (C.API_LOLLIPOP) {
        builder.setColor(ResourceUtils.getColor(this, android.R.attr.colorAccent));
        builder.setPriority(Notification.PRIORITY_HIGH);
        builder.setVibrate(new long[0]);
    } else {
        builder.setTicker(text);
    }
    builder.setContentTitle(getString(R.string.text_app_name_update, getString(R.string.const_app_name)));
    builder.setContentText(text);
    builder.setContentIntent(PendingIntent.getActivity(this, 0,
            PreferencesActivity.createUpdateIntent(this, updateDataMap).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
            PendingIntent.FLAG_UPDATE_CURRENT));
    builder.setAutoCancel(true);
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(C.NOTIFICATION_TAG_UPDATE, 0, builder.build());
}

From source file:uk.org.ngo.squeezer.service.SqueezeService.java

/**
 * Manages the state of any ongoing notification based on the player and connection state.
 *///from   ww w .j  a v  a 2  s . c o  m
private void updateOngoingNotification() {
    Player activePlayer = this.mActivePlayer.get();
    PlayerState activePlayerState = getActivePlayerState();

    // Update scrobble state, if either we're currently scrobbling, or we
    // were (to catch the case where we started scrobbling a song, and the
    // user went in to settings to disable scrobbling).
    if (scrobblingEnabled || scrobblingPreviouslyEnabled) {
        scrobblingPreviouslyEnabled = scrobblingEnabled;
        Scrobble.scrobbleFromPlayerState(this, activePlayerState);
    }

    // If there's no active player then kill the notification and get out.
    // TODO: Have a "There are no connected players" notification text.
    if (activePlayer == null || activePlayerState == null) {
        clearOngoingNotification();
        return;
    }

    boolean playing = activePlayerState.isPlaying();

    // If the song is not playing and the user wants notifications only when playing then
    // kill the notification and get out.
    if (!playing && !mShowNotificationWhenNotPlaying) {
        clearOngoingNotification();
        return;
    }

    // If there's no current song then kill the notification and get out.
    // TODO: Have a "There's nothing playing" notification text.
    final Song currentSong = activePlayerState.getCurrentSong();
    if (currentSong == null) {
        clearOngoingNotification();
        return;
    }

    // Compare the current state with the state when the notification was last updated.
    // If there are no changes (same song, same playing state) then there's nothing to do.
    String songName = currentSong.getName();
    String albumName = currentSong.getAlbumName();
    String artistName = currentSong.getArtist();
    Uri url = currentSong.getArtworkUrl();
    String playerName = activePlayer.getName();

    if (mNotifiedPlayerState == null) {
        mNotifiedPlayerState = new PlayerState();
    } else {
        boolean lastPlaying = mNotifiedPlayerState.isPlaying();
        Song lastNotifiedSong = mNotifiedPlayerState.getCurrentSong();

        // No change in state
        if (playing == lastPlaying && currentSong.equals(lastNotifiedSong)) {
            return;
        }
    }

    mNotifiedPlayerState.setCurrentSong(currentSong);
    mNotifiedPlayerState.setPlayStatus(activePlayerState.getPlayStatus());
    final NotificationManagerCompat nm = NotificationManagerCompat.from(this);

    PendingIntent nextPendingIntent = getPendingIntent(ACTION_NEXT_TRACK);
    PendingIntent prevPendingIntent = getPendingIntent(ACTION_PREV_TRACK);
    PendingIntent playPendingIntent = getPendingIntent(ACTION_PLAY);
    PendingIntent pausePendingIntent = getPendingIntent(ACTION_PAUSE);
    PendingIntent closePendingIntent = getPendingIntent(ACTION_CLOSE);

    Intent showNowPlaying = new Intent(this, NowPlayingActivity.class)
            .setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, showNowPlaying, 0);
    Notification notification;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        final Notification.Builder builder = new Notification.Builder(this);
        builder.setContentIntent(pIntent);
        builder.setSmallIcon(R.drawable.squeezer_notification);
        builder.setVisibility(Notification.VISIBILITY_PUBLIC);
        builder.setShowWhen(false);
        builder.setContentTitle(songName);
        builder.setContentText(albumName);
        builder.setSubText(playerName);
        builder.setStyle(new Notification.MediaStyle().setShowActionsInCompactView(1, 2)
                .setMediaSession(mMediaSession.getSessionToken()));

        final MediaMetadata.Builder metaBuilder = new MediaMetadata.Builder();
        metaBuilder.putString(MediaMetadata.METADATA_KEY_ARTIST, artistName);
        metaBuilder.putString(MediaMetadata.METADATA_KEY_ALBUM, albumName);
        metaBuilder.putString(MediaMetadata.METADATA_KEY_TITLE, songName);
        mMediaSession.setMetadata(metaBuilder.build());

        // Don't set an ongoing notification, otherwise wearable's won't show it.
        builder.setOngoing(false);

        builder.setDeleteIntent(closePendingIntent);
        if (playing) {
            builder.addAction(
                    new Notification.Action(R.drawable.ic_action_previous, "Previous", prevPendingIntent))
                    .addAction(new Notification.Action(R.drawable.ic_action_pause, "Pause", pausePendingIntent))
                    .addAction(new Notification.Action(R.drawable.ic_action_next, "Next", nextPendingIntent));
        } else {
            builder.addAction(
                    new Notification.Action(R.drawable.ic_action_previous, "Previous", prevPendingIntent))
                    .addAction(new Notification.Action(R.drawable.ic_action_play, "Play", playPendingIntent))
                    .addAction(new Notification.Action(R.drawable.ic_action_next, "Next", nextPendingIntent));
        }

        ImageFetcher.getInstance(this).loadImage(url,
                getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_width),
                getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_height),
                new ImageWorker.ImageWorkerCallback() {
                    @Override
                    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                    public void process(Object data, @Nullable Bitmap bitmap) {
                        if (bitmap == null) {
                            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_album_noart);
                        }

                        metaBuilder.putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, bitmap);
                        metaBuilder.putBitmap(MediaMetadata.METADATA_KEY_ART, bitmap);
                        mMediaSession.setMetadata(metaBuilder.build());
                        builder.setLargeIcon(bitmap);
                        nm.notify(PLAYBACKSERVICE_STATUS, builder.build());
                    }
                });
    } else {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

        builder.setOngoing(true);
        builder.setCategory(NotificationCompat.CATEGORY_SERVICE);
        builder.setSmallIcon(R.drawable.squeezer_notification);

        RemoteViews normalView = new RemoteViews(this.getPackageName(), R.layout.notification_player_normal);
        RemoteViews expandedView = new RemoteViews(this.getPackageName(),
                R.layout.notification_player_expanded);

        normalView.setOnClickPendingIntent(R.id.next, nextPendingIntent);

        expandedView.setOnClickPendingIntent(R.id.previous, prevPendingIntent);
        expandedView.setOnClickPendingIntent(R.id.next, nextPendingIntent);

        builder.setContent(normalView);

        normalView.setTextViewText(R.id.trackname, songName);
        normalView.setTextViewText(R.id.albumname, albumName);

        expandedView.setTextViewText(R.id.trackname, songName);
        expandedView.setTextViewText(R.id.albumname, albumName);
        expandedView.setTextViewText(R.id.player_name, playerName);

        if (playing) {
            normalView.setImageViewResource(R.id.pause, R.drawable.ic_action_pause);
            normalView.setOnClickPendingIntent(R.id.pause, pausePendingIntent);

            expandedView.setImageViewResource(R.id.pause, R.drawable.ic_action_pause);
            expandedView.setOnClickPendingIntent(R.id.pause, pausePendingIntent);
        } else {
            normalView.setImageViewResource(R.id.pause, R.drawable.ic_action_play);
            normalView.setOnClickPendingIntent(R.id.pause, playPendingIntent);

            expandedView.setImageViewResource(R.id.pause, R.drawable.ic_action_play);
            expandedView.setOnClickPendingIntent(R.id.pause, playPendingIntent);
        }

        builder.setContentTitle(songName);
        builder.setContentText(getString(R.string.notification_playing_text, playerName));
        builder.setContentIntent(pIntent);

        notification = builder.build();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            notification.bigContentView = expandedView;
        }

        nm.notify(PLAYBACKSERVICE_STATUS, notification);

        ImageFetcher.getInstance(this).loadImage(this, url, normalView, R.id.album,
                getResources().getDimensionPixelSize(R.dimen.album_art_icon_normal_notification_width),
                getResources().getDimensionPixelSize(R.dimen.album_art_icon_normal_notification_height), nm,
                PLAYBACKSERVICE_STATUS, notification);
        ImageFetcher.getInstance(this).loadImage(this, url, expandedView, R.id.album,
                getResources().getDimensionPixelSize(R.dimen.album_art_icon_expanded_notification_width),
                getResources().getDimensionPixelSize(R.dimen.album_art_icon_expanded_notification_height), nm,
                PLAYBACKSERVICE_STATUS, notification);
    }
}

From source file:dk.bearware.gui.MainActivity.java

@Override
public void onCmdUserTextMessage(TextMessage textmessage) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    switch (textmessage.nMsgType) {
    case TextMsgType.MSGTYPE_CHANNEL:
    case TextMsgType.MSGTYPE_BROADCAST:
        accessibilityAssistant.lockEvents();
        textmsgAdapter.notifyDataSetChanged();
        accessibilityAssistant.unlockEvents();

        // audio event
        if (sounds.get(SOUND_CHANMSG) != 0)
            audioIcons.play(sounds.get(SOUND_CHANMSG), 1.0f, 1.0f, 0, 0, 1.0f);
        // TTS event
        if (ttsWrapper != null && prefs.getBoolean("broadcast_message_checkbox", false)) {
            User sender = ttservice.getUsers().get(textmessage.nFromUserID);
            String name = Utils.getDisplayName(getBaseContext(), sender);
            ttsWrapper.speak(getString(R.string.text_tts_broadcast_message, (sender != null) ? name : ""));
        }// w  w  w  .j  a v  a2s .  c  o m
        Log.d(TAG, "Channel message in " + this.hashCode());
        break;
    case TextMsgType.MSGTYPE_USER:
        if (sounds.get(SOUND_USERMSG) != 0)
            audioIcons.play(sounds.get(SOUND_USERMSG), 1.0f, 1.0f, 0, 0, 1.0f);

        User sender = ttservice.getUsers().get(textmessage.nFromUserID);
        String name = Utils.getDisplayName(getBaseContext(), sender);
        String senderName = (sender != null) ? name : "";
        if (ttsWrapper != null && prefs.getBoolean("personal_message_checkbox", false))
            ttsWrapper.speak(getString(R.string.text_tts_personal_message, senderName));
        Intent action = new Intent(this, TextMessageActivity.class);
        Notification.Builder notification = new Notification.Builder(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel("TT_PM", "Teamtalk incoming message",
                    NotificationManager.IMPORTANCE_HIGH);
            mChannel.enableVibration(false);
            mChannel.setVibrationPattern(null);
            mChannel.enableLights(false);
            mChannel.setSound(null, null);
            notificationManager.createNotificationChannel(mChannel);
        }
        notification.setSmallIcon(R.drawable.message)
                .setContentTitle(getString(R.string.personal_message_notification, senderName))
                .setContentText(getString(R.string.personal_message_notification_hint))
                .setContentIntent(PendingIntent.getActivity(this, textmessage.nFromUserID,
                        action.putExtra(TextMessageActivity.EXTRA_USERID, textmessage.nFromUserID), 0))
                .setAutoCancel(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notification.setChannelId("TT_PM");
        }
        notificationManager.notify(MESSAGE_NOTIFICATION_TAG, textmessage.nFromUserID, notification.build());
        break;
    case TextMsgType.MSGTYPE_CUSTOM:
    default:
        break;
    }
}