Example usage for android.app Notification VISIBILITY_PUBLIC

List of usage examples for android.app Notification VISIBILITY_PUBLIC

Introduction

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

Prototype

int VISIBILITY_PUBLIC

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

Click Source Link

Document

Notification visibility: Show this notification in its entirety on all lockscreens.

Usage

From source file:com.mb.android.playbackmediator.notification.VideoCastNotificationService.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void buildForLollipopAndAbove(SessionInfoDto info, Bitmap bitmap, boolean isPlaying)
        throws CastException, TransientNetworkDisconnectionException, NoConnectionException {

    // Playback PendingIntent
    Intent playbackIntent = new Intent(ACTION_TOGGLE_PLAYBACK);
    playbackIntent.setPackage(getPackageName());
    PendingIntent playbackPendingIntent = PendingIntent.getBroadcast(this, 0, playbackIntent, 0);

    // Disconnect PendingIntent
    Intent stopIntent = new Intent(ACTION_STOP);
    stopIntent.setPackage(getPackageName());
    PendingIntent stopPendingIntent = PendingIntent.getBroadcast(this, 0, stopIntent, 0);

    // Main Content PendingIntent
    mTargetActivity = RemoteControlActivity.class;
    Intent contentIntent = new Intent(this, mTargetActivity);
    contentIntent.putExtra("LAUNCHED_BY_NOTIFICATION", true);

    // Media metadata
    String castingTo = getResources().getString(R.string.casting_to_device, mCastManager.getDeviceName());
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(mTargetActivity);
    stackBuilder.addNextIntent(contentIntent);

    PendingIntent contentPendingIntent = stackBuilder.getPendingIntent(NOTIFICATION_ID,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mNotification = new Notification.Builder(this).setSmallIcon(R.drawable.ic_stat_action_notification)
            .setContentTitle(info.getNowPlayingItem().getName()).setContentText(castingTo)
            .setContentIntent(contentPendingIntent).setLargeIcon(bitmap)
            .addAction(isPlaying ? R.drawable.ic_av_pause_dark : R.drawable.ic_av_play_dark, "Pause",
                    playbackPendingIntent)
            .addAction(R.drawable.ic_cast_stop_wht, "Disconnect", stopPendingIntent)
            .setStyle(new Notification.MediaStyle().setShowActionsInCompactView(new int[] { 0, 1 }))
            .setOngoing(true).setShowWhen(false).setVisibility(Notification.VISIBILITY_PUBLIC).build();

}

From source file:com.google.sample.castcompanionlibrary.notification.VideoCastNotificationService.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void buildForLollipopAndAbove(MediaInfo info, Bitmap bitmap, boolean isPlaying)
        throws CastException, TransientNetworkDisconnectionException, NoConnectionException {

    // Playback PendingIntent
    Intent playbackIntent = new Intent(ACTION_TOGGLE_PLAYBACK);
    playbackIntent.setPackage(getPackageName());
    PendingIntent playbackPendingIntent = PendingIntent.getBroadcast(this, 0, playbackIntent, 0);

    // Disconnect PendingIntent
    Intent stopIntent = new Intent(ACTION_STOP);
    stopIntent.setPackage(getPackageName());
    PendingIntent stopPendingIntent = PendingIntent.getBroadcast(this, 0, stopIntent, 0);

    // Main Content PendingIntent
    Bundle mediaWrapper = Utils.fromMediaInfo(mCastManager.getRemoteMediaInformation());
    Intent contentIntent = new Intent(this, mTargetActivity);
    contentIntent.putExtra("media", mediaWrapper);

    // Media metadata
    MediaMetadata mm = info.getMetadata();
    String castingTo = getResources().getString(R.string.casting_to_device, mCastManager.getDeviceName());
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(mTargetActivity);
    stackBuilder.addNextIntent(contentIntent);
    if (stackBuilder.getIntentCount() > 1) {
        stackBuilder.editIntentAt(1).putExtra("media", mediaWrapper);
    }/*www  .j a  va 2s . c  o  m*/
    PendingIntent contentPendingIntent = stackBuilder.getPendingIntent(NOTIFICATION_ID,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mNotification = new Notification.Builder(this).setSmallIcon(R.drawable.ic_stat_action_notification)
            .setContentTitle(mm.getString(MediaMetadata.KEY_TITLE)).setContentText(castingTo)
            .setContentIntent(contentPendingIntent).setLargeIcon(bitmap)
            .addAction(isPlaying ? R.drawable.ic_pause_white_48dp : R.drawable.ic_play_arrow_white_48dp,
                    getString(R.string.pause), playbackPendingIntent)
            .addAction(R.drawable.ic_clear_white_24dp, getString(R.string.disconnect), stopPendingIntent)
            .setStyle(new Notification.MediaStyle().setShowActionsInCompactView(new int[] { 0, 1 }))
            .setOngoing(true).setShowWhen(false).setVisibility(Notification.VISIBILITY_PUBLIC).build();

}

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(// w ww.j ava  2 s.c  o  m
                    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.example.android.alertbuddy.BluetoothLeService.java

private void lockScreenNotification() {
    mBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
    mBuilder.setAutoCancel(true);
}

From source file:com.android.cts.verifier.managedprovisioning.ByodHelperActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        Log.w(TAG, "Restored state");
        mOriginalSettings = savedInstanceState.getBundle(ORIGINAL_SETTINGS_NAME);
    } else {//from   w  ww.  ja va 2s . c om
        mOriginalSettings = new Bundle();
    }

    mAdminReceiverComponent = new ComponentName(this, DeviceAdminTestReceiver.class.getName());
    mDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Intent intent = getIntent();
    String action = intent.getAction();
    Log.d(TAG, "ByodHelperActivity.onCreate: " + action);

    // we are explicitly started by {@link DeviceAdminTestReceiver} after a successful provisioning.
    if (action.equals(ACTION_PROFILE_PROVISIONED)) {
        // Jump back to CTS verifier with result.
        Intent response = new Intent(ACTION_PROFILE_OWNER_STATUS);
        response.putExtra(EXTRA_PROVISIONED, isProfileOwner());
        startActivityInPrimary(response);
        // Queried by CtsVerifier in the primary side using startActivityForResult.
    } else if (action.equals(ACTION_QUERY_PROFILE_OWNER)) {
        Intent response = new Intent();
        response.putExtra(EXTRA_PROVISIONED, isProfileOwner());
        setResult(RESULT_OK, response);
        // Request to delete work profile.
    } else if (action.equals(ACTION_REMOVE_MANAGED_PROFILE)) {
        if (isProfileOwner()) {
            Log.d(TAG, "Clearing cross profile intents");
            mDevicePolicyManager.clearCrossProfileIntentFilters(mAdminReceiverComponent);
            mDevicePolicyManager.wipeData(0);
            showToast(R.string.provisioning_byod_profile_deleted);
        }
    } else if (action.equals(ACTION_INSTALL_APK)) {
        boolean allowNonMarket = intent.getBooleanExtra(EXTRA_ALLOW_NON_MARKET_APPS, false);
        boolean wasAllowed = getAllowNonMarket();

        // Update permission to install non-market apps
        setAllowNonMarket(allowNonMarket);
        mOriginalSettings.putBoolean(INSTALL_NON_MARKET_APPS, wasAllowed);

        // Request to install a non-market application- easiest way is to reinstall ourself
        final Intent installIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE)
                .setData(Uri.parse("package:" + getPackageName()))
                .putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true).putExtra(Intent.EXTRA_RETURN_RESULT, true);
        startActivityForResult(installIntent, REQUEST_INSTALL_PACKAGE);

        // Not yet ready to finish- wait until the result comes back
        return;
        // Queried by CtsVerifier in the primary side using startActivityForResult.
    } else if (action.equals(ACTION_CHECK_INTENT_FILTERS)) {
        final boolean intentFiltersSetForManagedIntents = new IntentFiltersTestHelper(this)
                .checkCrossProfileIntentFilters(IntentFiltersTestHelper.FLAG_INTENTS_FROM_MANAGED);
        setResult(intentFiltersSetForManagedIntents ? RESULT_OK : RESULT_FAILED, null);
    } else if (action.equals(ACTION_CAPTURE_AND_CHECK_IMAGE)) {
        // We need the camera permission to send the image capture intent.
        grantCameraPermissionToSelf();
        Intent captureImageIntent = getCaptureImageIntent();
        Pair<File, Uri> pair = getTempUri("image.jpg");
        mImageFile = pair.first;
        mImageUri = pair.second;
        captureImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        if (captureImageIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(captureImageIntent, REQUEST_IMAGE_CAPTURE);
        } else {
            Log.e(TAG, "Capture image intent could not be resolved in managed profile.");
            showToast(R.string.provisioning_byod_capture_media_error);
            finish();
        }
        return;
    } else if (action.equals(ACTION_CAPTURE_AND_CHECK_VIDEO_WITH_EXTRA_OUTPUT)
            || action.equals(ACTION_CAPTURE_AND_CHECK_VIDEO_WITHOUT_EXTRA_OUTPUT)) {
        // We need the camera permission to send the video capture intent.
        grantCameraPermissionToSelf();
        Intent captureVideoIntent = getCaptureVideoIntent();
        int videoCaptureRequestId;
        if (action.equals(ACTION_CAPTURE_AND_CHECK_VIDEO_WITH_EXTRA_OUTPUT)) {
            mVideoUri = getTempUri("video.mp4").second;
            captureVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mVideoUri);
            videoCaptureRequestId = REQUEST_VIDEO_CAPTURE_WITH_EXTRA_OUTPUT;
        } else {
            videoCaptureRequestId = REQUEST_VIDEO_CAPTURE_WITHOUT_EXTRA_OUTPUT;
        }
        if (captureVideoIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(captureVideoIntent, videoCaptureRequestId);
        } else {
            Log.e(TAG, "Capture video intent could not be resolved in managed profile.");
            showToast(R.string.provisioning_byod_capture_media_error);
            finish();
        }
        return;
    } else if (action.equals(ACTION_CAPTURE_AND_CHECK_AUDIO)) {
        Intent captureAudioIntent = getCaptureAudioIntent();
        if (captureAudioIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(captureAudioIntent, REQUEST_AUDIO_CAPTURE);
        } else {
            Log.e(TAG, "Capture audio intent could not be resolved in managed profile.");
            showToast(R.string.provisioning_byod_capture_media_error);
            finish();
        }
        return;
    } else if (ACTION_KEYGUARD_DISABLED_FEATURES.equals(action)) {
        final int value = intent.getIntExtra(EXTRA_PARAMETER_1,
                DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE);
        mDevicePolicyManager.setKeyguardDisabledFeatures(mAdminReceiverComponent, value);
    } else if (ACTION_LOCKNOW.equals(action)) {
        mDevicePolicyManager.lockNow();
        setResult(RESULT_OK);
    } else if (action.equals(ACTION_TEST_NFC_BEAM)) {
        Intent testNfcBeamIntent = new Intent(this, NfcTestActivity.class);
        testNfcBeamIntent.putExtras(intent);
        startActivity(testNfcBeamIntent);
        finish();
        return;
    } else if (action.equals(ACTION_TEST_CROSS_PROFILE_INTENTS_DIALOG)) {
        sendIntentInsideChooser(new Intent(CrossProfileTestActivity.ACTION_CROSS_PROFILE_TO_PERSONAL));
    } else if (action.equals(ACTION_TEST_APP_LINKING_DIALOG)) {
        mDevicePolicyManager.addUserRestriction(DeviceAdminTestReceiver.getReceiverComponentName(),
                UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
        Intent toSend = new Intent(Intent.ACTION_VIEW);
        toSend.setData(Uri.parse("http://com.android.cts.verifier"));
        sendIntentInsideChooser(toSend);
    } else if (action.equals(ACTION_SET_USER_RESTRICTION)) {
        final String restriction = intent.getStringExtra(EXTRA_PARAMETER_1);
        if (restriction != null) {
            mDevicePolicyManager.addUserRestriction(DeviceAdminTestReceiver.getReceiverComponentName(),
                    restriction);
        }
    } else if (action.equals(ACTION_CLEAR_USER_RESTRICTION)) {
        final String restriction = intent.getStringExtra(EXTRA_PARAMETER_1);
        if (restriction != null) {
            mDevicePolicyManager.clearUserRestriction(DeviceAdminTestReceiver.getReceiverComponentName(),
                    restriction);
        }
    } else if (action.equals(ACTION_BYOD_SET_LOCATION_AND_CHECK_UPDATES)) {
        handleLocationAction();
        return;
    } else if (action.equals(ACTION_NOTIFICATION)) {
        showNotification(Notification.VISIBILITY_PUBLIC);
    } else if (ACTION_NOTIFICATION_ON_LOCKSCREEN.equals(action)) {
        mDevicePolicyManager.lockNow();
        showNotification(Notification.VISIBILITY_PRIVATE);
    } else if (ACTION_CLEAR_NOTIFICATION.equals(action)) {
        mNotificationManager.cancel(NOTIFICATION_ID);
    } else if (ACTION_TEST_SELECT_WORK_CHALLENGE.equals(action)) {
        mDevicePolicyManager.setOrganizationColor(mAdminReceiverComponent, Color.BLUE);
        mDevicePolicyManager.setOrganizationName(mAdminReceiverComponent,
                getResources().getString(R.string.provisioning_byod_confirm_work_credentials_header));
        startActivity(new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD));
    } else if (ACTION_LAUNCH_CONFIRM_WORK_CREDENTIALS.equals(action)) {
        KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        Intent launchIntent = keyguardManager.createConfirmDeviceCredentialIntent(null, null);
        startActivity(launchIntent);
    } else if (ACTION_SET_ORGANIZATION_INFO.equals(action)) {
        if (intent.hasExtra(OrganizationInfoTestActivity.EXTRA_ORGANIZATION_NAME)) {
            final String organizationName = intent
                    .getStringExtra(OrganizationInfoTestActivity.EXTRA_ORGANIZATION_NAME);
            mDevicePolicyManager.setOrganizationName(mAdminReceiverComponent, organizationName);
        }
        final int organizationColor = intent.getIntExtra(OrganizationInfoTestActivity.EXTRA_ORGANIZATION_COLOR,
                mDevicePolicyManager.getOrganizationColor(mAdminReceiverComponent));
        mDevicePolicyManager.setOrganizationColor(mAdminReceiverComponent, organizationColor);
    } else if (ACTION_TEST_PARENT_PROFILE_PASSWORD.equals(action)) {
        startActivity(new Intent(DevicePolicyManager.ACTION_SET_NEW_PARENT_PROFILE_PASSWORD));
    }
    // This activity has no UI and is only used to respond to CtsVerifier in the primary side.
    finish();
}

From source file:net.exclaimindustries.geohashdroid.services.WikiService.java

@SuppressLint("NewApi")
private Notification.Builder getFreshNotificationBuilder() {
    // This just returns a fresh new Notification.Builder with the default
    // images.  We're resetting everything on each notification anyway, so
    // sharing the object is sort of a waste.
    Notification.Builder builder = new Notification.Builder(this)
            .setSmallIcon(R.drawable.geohashing_logo_notification);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        builder.setVisibility(Notification.VISIBILITY_PUBLIC);

    return builder;
}

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   w  w  w .  j  a v a  2  s. com*/
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:org.videolan.vlc.PlaybackService.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void showNotification() {
    try {/*from  w w  w .  j  av a 2 s. c  o  m*/
        MediaWrapper media = getCurrentMedia();
        if (media == null)
            return;
        Bitmap cover = AudioUtil.getCover(this, media, 64);
        String title = media.getTitle();
        String artist = Util.getMediaArtist(this, media);
        String album = Util.getMediaAlbum(this, media);
        Notification notification;

        if (media.isArtistUnknown() && media.isAlbumUnknown() && media.getNowPlaying() != null) {
            artist = media.getNowPlaying();
            album = "";
        }

        //Watch notification dismissed
        PendingIntent piStop = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_REMOTE_STOP),
                PendingIntent.FLAG_UPDATE_CURRENT);

        // add notification to status bar
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_vlc).setTicker(title + " - " + artist)
                .setAutoCancel(!MediaPlayer().isPlaying()).setOngoing(MediaPlayer().isPlaying())
                .setDeleteIntent(piStop);

        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setAction(AudioPlayerContainerActivity.ACTION_SHOW_PLAYER);
        notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        notificationIntent.putExtra(START_FROM_NOTIFICATION, true);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        if (AndroidUtil.isJellyBeanOrLater()) {
            Intent iBackward = new Intent(ACTION_REMOTE_BACKWARD);
            Intent iPlay = new Intent(ACTION_REMOTE_PLAYPAUSE);
            Intent iForward = new Intent(ACTION_REMOTE_FORWARD);
            PendingIntent piBackward = PendingIntent.getBroadcast(this, 0, iBackward,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            PendingIntent piPlay = PendingIntent.getBroadcast(this, 0, iPlay,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            PendingIntent piForward = PendingIntent.getBroadcast(this, 0, iForward,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            RemoteViews view = new RemoteViews(BuildConfig.APPLICATION_ID, R.layout.notification);
            view.setImageViewBitmap(R.id.cover,
                    cover == null ? BitmapFactory.decodeResource(getResources(), R.drawable.icon) : cover);
            view.setTextViewText(R.id.songName, title);
            view.setTextViewText(R.id.artist, artist);
            view.setImageViewResource(R.id.play_pause,
                    MediaPlayer().isPlaying() ? R.drawable.ic_pause_w : R.drawable.ic_play_w);
            view.setOnClickPendingIntent(R.id.play_pause, piPlay);
            view.setOnClickPendingIntent(R.id.forward, piForward);
            view.setOnClickPendingIntent(R.id.stop, piStop);
            view.setOnClickPendingIntent(R.id.content, pendingIntent);

            RemoteViews view_expanded = new RemoteViews(BuildConfig.APPLICATION_ID,
                    R.layout.notification_expanded);
            view_expanded.setImageViewBitmap(R.id.cover,
                    cover == null ? BitmapFactory.decodeResource(getResources(), R.drawable.icon) : cover);
            view_expanded.setTextViewText(R.id.songName, title);
            view_expanded.setTextViewText(R.id.artist, artist);
            view_expanded.setTextViewText(R.id.album, album);
            view_expanded.setImageViewResource(R.id.play_pause,
                    MediaPlayer().isPlaying() ? R.drawable.ic_pause_w : R.drawable.ic_play_w);
            view_expanded.setOnClickPendingIntent(R.id.backward, piBackward);
            view_expanded.setOnClickPendingIntent(R.id.play_pause, piPlay);
            view_expanded.setOnClickPendingIntent(R.id.forward, piForward);
            view_expanded.setOnClickPendingIntent(R.id.stop, piStop);
            view_expanded.setOnClickPendingIntent(R.id.content, pendingIntent);

            if (AndroidUtil.isLolliPopOrLater()) {
                //Hide stop button on pause, we swipe notification to stop
                view.setViewVisibility(R.id.stop, MediaPlayer().isPlaying() ? View.VISIBLE : View.INVISIBLE);
                view_expanded.setViewVisibility(R.id.stop,
                        MediaPlayer().isPlaying() ? View.VISIBLE : View.INVISIBLE);
                //Make notification appear on lockscreen
                builder.setVisibility(Notification.VISIBILITY_PUBLIC);
            }

            notification = builder.build();
            notification.contentView = view;
            notification.bigContentView = view_expanded;
        } else {
            builder.setLargeIcon(
                    cover == null ? BitmapFactory.decodeResource(getResources(), R.drawable.icon) : cover)
                    .setContentTitle(title)
                    .setContentText(
                            AndroidUtil.isJellyBeanOrLater() ? artist : Util.getMediaSubtitle(this, media))
                    .setContentInfo(album).setContentIntent(pendingIntent);
            notification = builder.build();
        }

        startService(new Intent(this, PlaybackService.class));
        if (!AndroidUtil.isLolliPopOrLater() || MediaPlayer().isPlaying())
            startForeground(3, notification);
        else {
            stopForeground(false);
            NotificationManagerCompat.from(this).notify(3, notification);
        }
    } catch (NoSuchMethodError e) {
        // Compat library is wrong on 3.2
        // http://code.google.com/p/android/issues/detail?id=36359
        // http://code.google.com/p/android/issues/detail?id=36502
    }
}

From source file:ro.ciubex.keepscreenlock.MainApplication.java

/**
 * Build the notification item./*from   w  ww. ja va  2s . c o m*/
 *
 * @param allowDismiss Flag used to create a dismissible notification.
 * @return The notification item.
 */
private Notification getNotification(boolean allowDismiss) {
    if (mNotification == null) {
        PendingIntent pendingScreenLockIntent = PendingIntent.getBroadcast(this, 0,
                getNotificationScreenLockIntent(), PendingIntent.FLAG_UPDATE_CURRENT);

        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_layout);
        remoteViews.setOnClickPendingIntent(R.id.lockScreenView, pendingScreenLockIntent);

        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this);
        notifBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
        notifBuilder.setSmallIcon(R.mipmap.ic_launcher_red);
        notifBuilder.setContent(remoteViews);

        notifBuilder.setContentTitle(getString(R.string.app_name));
        notifBuilder.setContentText(getString(R.string.notification_text));

        mNotification = notifBuilder.build();
    }
    if (isNotificationAlwaysDismissible() || allowDismiss) {
        mNotification.flags &= ~Notification.FLAG_NO_CLEAR;
    } else {
        mNotification.flags |= Notification.FLAG_NO_CLEAR;
    }
    return mNotification;
}

From source file:com.rohan.app.MusicService.java

private Notification buildNotification() {
    final String albumName = getAlbumName();
    final String artistName = getArtistName();
    final boolean isPlaying = isPlaying();
    String text = TextUtils.isEmpty(albumName) ? artistName : artistName + " - " + albumName;

    int playButtonResId = isPlaying ? R.drawable.ic_pause_white_36dp : R.drawable.ic_play_white_36dp;

    Intent nowPlayingIntent = NavigationUtils.getNowPlayingIntent(this);
    PendingIntent clickIntent = PendingIntent.getActivity(this, 0, nowPlayingIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    Bitmap artwork;/*  ww w. java2  s  .  c o  m*/
    artwork = ImageLoader.getInstance().loadImageSync(TimberUtils.getAlbumArtUri(getAlbumId()).toString());

    if (artwork == null) {
        artwork = ImageLoader.getInstance().loadImageSync("drawable://" + R.drawable.ic_dribble);
    }

    if (mNotificationPostTime == 0) {
        mNotificationPostTime = System.currentTimeMillis();
    }

    android.support.v4.app.NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_play_circle_filled_white_24dp).setLargeIcon(artwork)
            .setContentIntent(clickIntent).setContentTitle(getTrackName()).setContentText(text)
            .setWhen(mNotificationPostTime)
            .addAction(R.drawable.ic_skip_previous_white_36dp, "", retrievePlaybackAction(PREVIOUS_ACTION))
            .addAction(playButtonResId, "", retrievePlaybackAction(TOGGLEPAUSE_ACTION))
            .addAction(R.drawable.ic_skip_next_white_36dp, "", retrievePlaybackAction(NEXT_ACTION));

    if (TimberUtils.isJellyBeanMR1()) {
        builder.setShowWhen(false);
    }
    if (TimberUtils.isLollipop()) {
        builder.setVisibility(Notification.VISIBILITY_PUBLIC);
        NotificationCompat.MediaStyle style = new NotificationCompat.MediaStyle()
                .setMediaSession(mSession.getSessionToken()).setShowActionsInCompactView(0, 1, 2, 3);
        builder.setStyle(style);
    }
    if (artwork != null && TimberUtils.isLollipop())
        builder.setColor(Palette.from(artwork).generate().getVibrantColor(Color.parseColor("#403f4d")));
    Notification n = builder.build();

    if (PreferencesUtility.getInstance(this).getXPosedTrackselectorEnabled()) {
        addXTrackSelector(n);
    }

    return n;
}