Example usage for android.graphics Bitmap getConfig

List of usage examples for android.graphics Bitmap getConfig

Introduction

In this page you can find the example usage for android.graphics Bitmap getConfig.

Prototype

public final Config getConfig() 

Source Link

Document

If the bitmap's internal config is in one of the public formats, return that config, otherwise return null.

Usage

From source file:org.thoughtcrime.securesms.ProfileFragment.java

public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
    int sourceWidth = source.getWidth();
    int sourceHeight = source.getHeight();

    float xScale = (float) newWidth / sourceWidth;
    float yScale = (float) newHeight / sourceHeight;
    float scale = Math.max(xScale, yScale);

    float scaledWidth = scale * sourceWidth;
    float scaledHeight = scale * sourceHeight;

    float left = (newWidth - scaledWidth) / 2;
    float top = (newHeight - scaledHeight) / 2;

    RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);

    Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
    Canvas canvas = new Canvas(dest);
    canvas.drawBitmap(source, null, targetRect, null);
    return dest;// ww w.  j  a  v  a2  s  . c o  m
}

From source file:io.mapsquare.osmcontributor.ui.utils.BitmapHandler.java

/**
 * Handle Bitmap load, storage and retrieval for MapFragment.
 * <br/>/*from  www. j a  v a2s  . co  m*/
 * Put the marker corresponding to a poiType into a color pin. The color depends of the poi's state.
 *
 * @param poiType The PoiType of the desired bitmap.
 * @param state   State of the Poi.
 * @return The marker corresponding to the poiType and the poi state.
 */
public Bitmap getMarkerBitmap(PoiType poiType, Poi.State state) {

    try {

        Integer markerId = null;
        Integer iconId = getIconDrawableId(poiType);

        Bitmap markerWrapper;
        Bitmap icon;

        // 3 states, n-pois -> 3 x n bitmaps.
        // Two choices: either we store all overlay combinations, or we store the markers and always process overlays.
        // As there might be more POIs than the number of combinations, I chose to store all combinations.

        switch (state) {
        case NORMAL:
            markerId = R.drawable.marker_white;
            break;
        case NOT_SYNCED:
            markerId = R.drawable.marker_grey;
            break;
        case SELECTED:
            markerId = R.drawable.marker_blue;
            break;
        case MOVING:
            markerId = R.drawable.marker_red;
            break;
        }

        String bitmapCacheId = markerId.toString() + iconId.toString();

        // Try to retrieve bmOverlay from cache
        Bitmap bmOverlay = getBitmapFromMemCache(bitmapCacheId);

        // If we don't have the combination into memory yet, compute it manually
        if (bmOverlay == null) {

            // If still too slow (lots of sources), we might change this and also include partials into cache
            // Right now, I don't think the use case proves its usefulness
            markerWrapper = BitmapFactory.decodeResource(context.getResources(), markerId);
            icon = BitmapFactory.decodeResource(context.getResources(), iconId);

            bmOverlay = Bitmap.createBitmap(markerWrapper.getWidth(), markerWrapper.getHeight(),
                    markerWrapper.getConfig());
            Canvas canvas = new Canvas(bmOverlay);

            int x = markerWrapper.getWidth() / 2 - icon.getWidth() / 2;
            int y = markerWrapper.getHeight() / 2 - icon.getHeight() / 2
                    - (int) (0.05 * markerWrapper.getHeight());

            canvas.drawBitmap(markerWrapper, 0, 0, null);
            canvas.drawBitmap(icon, x, y, null);
            addBitmapToMemoryCache(bitmapCacheId, bmOverlay);
        }

        return bmOverlay;

    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.creativeongreen.imageeffects.MainActivity.java

public static Bitmap fastblur(Bitmap bmImage, int radius) {

    // Stack Blur v1.0 from
    // http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
    ///*from ww  w .  j ava2s.c o m*/
    // Java Author: Mario Klingemann <mario at quasimondo.com>
    // http://incubator.quasimondo.com
    // created Feburary 29, 2004
    // Android port : Yahel Bouaziz <yahel at kayenko.com>
    // http://www.kayenko.com
    // ported april 5th, 2012

    // This is a compromise between Gaussian Blur and Box blur
    // It creates much better looking blurs than Box Blur, but is
    // 7x faster than my Gaussian Blur implementation.
    //
    // I called it Stack Blur because this describes best how this
    // filter works internally: it creates a kind of moving stack
    // of colors whilst scanning through the image. Thereby it
    // just has to add one new block of color to the right side
    // of the stack and remove the leftmost color. The remaining
    // colors on the topmost layer of the stack are either added on
    // or reduced by one, depending on if they are on the right or
    // on the left side of the stack.
    //
    // If you are using this algorithm in your code please add
    // the following line:
    //
    // Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>

    Bitmap bmTemp = bmImage.copy(bmImage.getConfig(), true);

    if (radius < 1) {
        return (null);
    }

    int w = bmTemp.getWidth();
    int h = bmTemp.getHeight();

    int[] pix = new int[w * h];
    bmTemp.getPixels(pix, 0, w, 0, 0, w, h);

    int wm = w - 1;
    int hm = h - 1;
    int wh = w * h;
    int div = radius + radius + 1;

    int r[] = new int[wh];
    int g[] = new int[wh];
    int b[] = new int[wh];
    int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
    int vmin[] = new int[Math.max(w, h)];

    int divsum = (div + 1) >> 1;
    divsum *= divsum;
    int dv[] = new int[256 * divsum];
    for (i = 0; i < 256 * divsum; i++) {
        dv[i] = (i / divsum);
    }

    yw = yi = 0;

    int[][] stack = new int[div][3];
    int stackpointer;
    int stackstart;
    int[] sir;
    int rbs;
    int r1 = radius + 1;
    int routsum, goutsum, boutsum;
    int rinsum, ginsum, binsum;

    for (y = 0; y < h; y++) {
        rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
        for (i = -radius; i <= radius; i++) {
            p = pix[yi + Math.min(wm, Math.max(i, 0))];
            sir = stack[i + radius];
            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);
            rbs = r1 - Math.abs(i);
            rsum += sir[0] * rbs;
            gsum += sir[1] * rbs;
            bsum += sir[2] * rbs;
            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
            }
        }
        stackpointer = radius;

        for (x = 0; x < w; x++) {

            r[yi] = dv[rsum];
            g[yi] = dv[gsum];
            b[yi] = dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];

            if (y == 0) {
                vmin[x] = Math.min(x + radius + 1, wm);
            }
            p = pix[yw + vmin[x]];

            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[(stackpointer) % div];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];

            yi++;
        }
        yw += w;
    }

    for (x = 0; x < w; x++) {
        rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
        yp = -radius * w;
        for (i = -radius; i <= radius; i++) {
            yi = Math.max(0, yp) + x;

            sir = stack[i + radius];

            sir[0] = r[yi];
            sir[1] = g[yi];
            sir[2] = b[yi];

            rbs = r1 - Math.abs(i);

            rsum += r[yi] * rbs;
            gsum += g[yi] * rbs;
            bsum += b[yi] * rbs;

            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
            }

            if (i < hm) {
                yp += w;
            }
        }
        yi = x;
        stackpointer = radius;
        for (y = 0; y < h; y++) {
            // Preserve alpha channel: ( 0xff000000 & pix[yi] )
            pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];

            if (x == 0) {
                vmin[y] = Math.min(y + r1, hm) * w;
            }
            p = x + vmin[y];

            sir[0] = r[p];
            sir[1] = g[p];
            sir[2] = b[p];

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[stackpointer];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];

            yi += w;
        }
    }

    bmTemp.setPixels(pix, 0, w, 0, 0, w, h);

    return bmTemp;
}

From source file:io.jawg.osmcontributor.ui.utils.BitmapHandler.java

/**
 * Handle Bitmap load, storage and retrieval for MapFragment.
 * <br/>/*  www. j  a  va2 s  .com*/
 * Put the marker corresponding to a poiType into a color pin. The color depends of the poi's state.
 *
 * @param poiType The PoiType of the desired bitmap.
 * @param state   State of the Poi.
 * @return The marker corresponding to the poiType and the poi state.
 */
public Bitmap getMarkerBitmap(PoiType poiType, Poi.State state) {

    try {

        Integer markerId = null;
        Integer iconId = getIconDrawableId(poiType);

        Bitmap markerWrapper;
        Bitmap icon;

        // 3 states, n-pois -> 3 x n bitmaps.
        // Two choices: either we store all overlay combinations, or we store the markers and always process overlays.
        // As there might be more POIs than the number of combinations, I chose to store all combinations.

        switch (state) {
        case NORMAL:
            markerId = R.drawable.marker_white;
            break;
        case NOT_SYNCED:
            markerId = R.drawable.marker_grey;
            break;
        case SELECTED:
            markerId = R.drawable.marker_blue;
            break;
        case MOVING:
            markerId = R.drawable.marker_red;
            break;
        case ITINERARY_SELECTED:
            markerId = R.drawable.marker_true_blue;
            break;
        }

        String bitmapCacheId = markerId.toString() + iconId.toString();

        // Try to retrieve bmOverlay from cache
        Bitmap bmOverlay = getBitmapFromMemCache(bitmapCacheId);

        // If we don't have the combination into memory yet, compute it manually
        if (bmOverlay == null) {

            // If still too slow (lots of sources), we might change this and also include partials into cache
            // Right now, I don't think the use case proves its usefulness
            markerWrapper = BitmapFactory.decodeResource(context.getResources(), markerId);
            icon = BitmapFactory.decodeResource(context.getResources(), iconId);

            bmOverlay = Bitmap.createBitmap(markerWrapper.getWidth(), markerWrapper.getHeight(),
                    markerWrapper.getConfig());
            Canvas canvas = new Canvas(bmOverlay);

            int x = markerWrapper.getWidth() / 2 - icon.getWidth() / 2;
            int y = markerWrapper.getHeight() / 2 - icon.getHeight() / 2
                    - (int) (0.05 * markerWrapper.getHeight());

            canvas.drawBitmap(markerWrapper, 0, 0, null);
            canvas.drawBitmap(icon, x, y, null);
            addBitmapToMemoryCache(bitmapCacheId, bmOverlay);
        }

        return bmOverlay;

    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.naman14.timber.musicplayer.MusicService.java

private void updateMediaSession(final String what) {
    int playState = mIsSupposedToBePlaying ? PlaybackStateCompat.STATE_PLAYING
            : PlaybackStateCompat.STATE_PAUSED;

    if (what.equals(PLAYSTATE_CHANGED) || what.equals(POSITION_CHANGED)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(playState, position(), 1.0f)
                    .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE
                            | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                            | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
                    .build());//from w  w  w  . j a va 2 s  .co  m
        }
    } else if (what.equals(META_CHANGED) || what.equals(QUEUE_CHANGED)) {
        //TODO: Replace below Image download using Picasso
        Bitmap albumArt = ImageLoader.getInstance()
                .loadImageSync(TimberUtils.getAlbumArtUri(getAlbumId()).toString());
        if (albumArt != null) {

            Bitmap.Config config = albumArt.getConfig();
            if (config == null) {
                config = Bitmap.Config.ARGB_8888;
            }
            albumArt = albumArt.copy(config, false);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setMetadata(new MediaMetadataCompat.Builder()
                    .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, getArtistName())
                    .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, getAlbumArtistName())
                    .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, getAlbumName())
                    .putString(MediaMetadataCompat.METADATA_KEY_TITLE, getTrackName())
                    .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration())
                    .putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, getQueuePosition() + 1)
                    .putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, getQueue().size())
                    .putString(MediaMetadataCompat.METADATA_KEY_GENRE, getGenreName())
                    .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART,
                            mShowAlbumArtOnLockscreen ? albumArt : null)
                    .build());

            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(playState, position(), 1.0f)
                    .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE
                            | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                            | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
                    .build());
        }
    }
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

public static Bitmap graphics_addWaterMarkToImage(Bitmap src, String watermark, Point location, int size,
        boolean underline) {
    Bitmap result = null;//from   ww  w. jav  a 2 s .  co m

    try {
        int w = src.getWidth();
        int h = src.getHeight();
        result = Bitmap.createBitmap(w, h, src.getConfig());

        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(src, 0, 0, null);

        Paint paint = new Paint();
        paint.setColor(Color.RED);
        //paint.setAlpha(alpha);
        paint.setTextSize(size);
        paint.setAntiAlias(true);
        paint.setUnderlineText(underline);
        canvas.drawText(watermark, location.x, location.y, paint);
    } catch (Exception e) {
        result = null;
        if (LOG_ENABLE)
            Log.e(TAG, "ERROR: graphics_addWaterMarkToImage() [" + e.getMessage() + "]", e);
    }

    return result;
}

From source file:com.andrew.apollo.MusicPlaybackService.java

private static void changeRemoteControlClientTask(MusicPlaybackService musicPlaybackService, int playState,
        long position) {
    // background portion
    Bitmap albumArt = musicPlaybackService.getAlbumArt();
    // RemoteControlClient wants to recycle the bitmaps thrown at it, so we need
    // to make sure not to hand out our cache copy
    Bitmap.Config config = null;/*  w w  w.j a  va2s  . co m*/
    if (albumArt != null) {
        config = albumArt.getConfig();
    }
    if (config == null) {
        config = Bitmap.Config.ARGB_8888;
    }
    Bitmap bmpCopy = null;
    try {
        if (albumArt != null) {
            bmpCopy = albumArt.copy(config, false);
        }
    } catch (OutOfMemoryError e) {
        // ignore, can't do anything meaningful here
    }
    final Bitmap albumArtCopy = bmpCopy;
    final String artistName = musicPlaybackService.getArtistName();
    final String albumName = musicPlaybackService.getAlbumName();
    final String trackName = musicPlaybackService.getTrackName();
    final String albumArtistName = musicPlaybackService.getAlbumArtistName();
    final long duration = musicPlaybackService.duration();

    // MusicPlayerHandler thread portion, we can't put this as a PostContextTask
    // in Async.async.
    final WeakReference<MusicPlaybackService> musicPlaybackServiceRef = Ref.weak(musicPlaybackService);
    Runnable postExecute = () -> {
        if (!Ref.alive(musicPlaybackServiceRef)) {
            return;
        }
        MusicPlaybackService musicPlaybackService1 = musicPlaybackServiceRef.get();
        try {
            RemoteControlClient.MetadataEditor editor = musicPlaybackService1.mRemoteControlClient
                    .editMetadata(true).putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, artistName)
                    .putString(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST, albumArtistName)
                    .putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, albumName)
                    .putString(MediaMetadataRetriever.METADATA_KEY_TITLE, trackName)
                    .putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, duration);

            if (albumArtCopy != null) {
                editor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK, albumArtCopy);
            }

            editor.apply();
        } catch (Throwable t) {
            // possible NPE on android.media.RemoteControlClient$MetadataEditor.apply()
        }
        musicPlaybackService1.mRemoteControlClient.setPlaybackState(playState, position, 1.0f);
    };
    musicPlaybackService.mPlayerHandler.post(postExecute);
}

From source file:io.jawg.osmcontributor.ui.utils.BitmapHandler.java

/**
 * Handle Bitmap load, storage and retrieval for MapFragment.
 * <br/>/*from w  w w . jav  a2 s . c o m*/
 * Put the marker corresponding to a poiType into a color pin. The color depends of the poi's state.
 *
 * @param poiType The PoiType of the desired bitmap.
 * @param state   State of the Poi.
 * @param accessibilityType Accessibility type of the Poi.
 * @return The marker corresponding to the poiType and the poi state.
 */
public Bitmap getMarkerBitmap(PoiType poiType, Poi.State state, Poi.AccessibilityType accessibilityType) {

    try {

        Integer markerId = null;
        Integer iconId = getIconDrawableId(poiType);

        Bitmap markerWrapper;
        Bitmap icon;

        // 3 states, n-pois -> 3 x n bitmaps.
        // Two choices: either we store all overlay combinations, or we store the markers and always process overlays.
        // As there might be more POIs than the number of combinations, I chose to store all combinations.

        switch (state) {
        case NORMAL:
            // 4 accessibility types :
            switch (accessibilityType) {
            case YES:
                markerId = R.drawable.marker_true_green;
                break;
            case NO:
                markerId = R.drawable.marker_true_red;
                break;
            case LIMITED:
                markerId = R.drawable.marker_true_orange;
                break;
            case UNKNOWN:
                markerId = R.drawable.marker_true_grey;
                break;
            }
            break;
        case NOT_SYNCED:
            markerId = R.drawable.marker_grey;
            break;
        case SELECTED:
            markerId = R.drawable.marker_blue;
            break;
        case MOVING:
            markerId = R.drawable.marker_red;
            break;
        case ITINERARY_SELECTED:
            markerId = R.drawable.marker_true_blue;
            break;
        }

        String bitmapCacheId = markerId.toString() + iconId.toString();

        // Try to retrieve bmOverlay from cache
        Bitmap bmOverlay = getBitmapFromMemCache(bitmapCacheId);

        // If we don't have the combination into memory yet, compute it manually
        if (bmOverlay == null) {

            // If still too slow (lots of sources), we might change this and also include partials into cache
            // Right now, I don't think the use case proves its usefulness
            markerWrapper = BitmapFactory.decodeResource(context.getResources(), markerId);
            icon = BitmapFactory.decodeResource(context.getResources(), iconId);

            bmOverlay = Bitmap.createBitmap(markerWrapper.getWidth(), markerWrapper.getHeight(),
                    markerWrapper.getConfig());
            Canvas canvas = new Canvas(bmOverlay);

            int x = markerWrapper.getWidth() / 2 - icon.getWidth() / 2;
            int y = markerWrapper.getHeight() / 2 - icon.getHeight() / 2
                    - (int) (0.05 * markerWrapper.getHeight());

            canvas.drawBitmap(markerWrapper, 0, 0, null);
            canvas.drawBitmap(icon, x, y, null);
            addBitmapToMemoryCache(bitmapCacheId, bmOverlay);
        }

        return bmOverlay;

    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.techmighty.baseplayer.MusicService.java

private void updateMediaSession(final String what) {
    int playState = mIsSupposedToBePlaying ? PlaybackStateCompat.STATE_PLAYING
            : PlaybackStateCompat.STATE_PAUSED;

    if (what.equals(PLAYSTATE_CHANGED) || what.equals(POSITION_CHANGED)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(playState, position(), 1.0f)
                    .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE
                            | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                            | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
                    .build());/* w  w w.java 2  s .com*/
        }
    } else if (what.equals(META_CHANGED) || what.equals(QUEUE_CHANGED)) {
        Bitmap albumArt = ImageLoader.getInstance()
                .loadImageSync(BasePlayerUtils.getAlbumArtUri(getAlbumId()).toString());
        if (albumArt != null) {

            Bitmap.Config config = albumArt.getConfig();
            if (config == null) {
                config = Bitmap.Config.ARGB_8888;
            }
            albumArt = albumArt.copy(config, false);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setMetadata(new MediaMetadataCompat.Builder()
                    .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, getArtistName())
                    .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, getAlbumArtistName())
                    .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, getAlbumName())
                    .putString(MediaMetadataCompat.METADATA_KEY_TITLE, getTrackName())
                    .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration())
                    .putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, getQueuePosition() + 1)
                    .putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, getQueue().length)
                    .putString(MediaMetadataCompat.METADATA_KEY_GENRE, getGenreName())
                    .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART,
                            mShowAlbumArtOnLockscreen ? albumArt : null)
                    .build());

            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(playState, position(), 1.0f)
                    .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE
                            | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                            | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
                    .build());
        }
    }
}

From source file:com.devalladolid.musictoday.MusicService.java

private void updateMediaSession(final String what) {
    int playState = mIsSupposedToBePlaying ? PlaybackStateCompat.STATE_PLAYING
            : PlaybackStateCompat.STATE_PAUSED;

    if (what.equals(PLAYSTATE_CHANGED) || what.equals(POSITION_CHANGED)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(playState, position(), 1.0f)
                    .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE
                            | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                            | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
                    .build());/* w  w  w.j ava 2 s .  c  o  m*/
        }
    } else if (what.equals(META_CHANGED) || what.equals(QUEUE_CHANGED)) {
        Bitmap albumArt = ImageLoader.getInstance()
                .loadImageSync(TimberUtils.getAlbumArtUri(getAlbumId()).toString());
        if (albumArt != null) {

            Bitmap.Config config = albumArt.getConfig();
            if (config == null) {
                config = Bitmap.Config.ARGB_8888;
            }
            albumArt = albumArt.copy(config, false);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setMetadata(new MediaMetadataCompat.Builder()
                    .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, getArtistName())
                    .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, getAlbumArtistName())
                    .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, getAlbumName())
                    .putString(MediaMetadataCompat.METADATA_KEY_TITLE, getTrackName())
                    .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration())
                    .putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, getQueuePosition() + 1)
                    .putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, getQueue().length)
                    .putString(MediaMetadataCompat.METADATA_KEY_GENRE, getGenreName())
                    .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART,
                            mShowAlbumArtOnLockscreen ? albumArt : null)
                    .build());

            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(playState, position(), 1.0f)
                    .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE
                            | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                            | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
                    .build());
        }
    }
}