2 * Copyright (C) 2008 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.music;
19 import android.app.Activity;
20 import android.content.ComponentName;
21 import android.content.ContentResolver;
22 import android.content.ContentUris;
23 import android.content.ContentValues;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.ServiceConnection;
27 import android.content.SharedPreferences;
28 import android.content.SharedPreferences.Editor;
29 import android.content.res.Resources;
30 import android.database.Cursor;
31 import android.graphics.Bitmap;
32 import android.graphics.BitmapFactory;
33 import android.graphics.Canvas;
34 import android.graphics.ColorFilter;
35 import android.graphics.PixelFormat;
36 import android.graphics.drawable.BitmapDrawable;
37 import android.graphics.drawable.Drawable;
38 import android.net.Uri;
39 import android.os.Environment;
40 import android.os.ParcelFileDescriptor;
41 import android.os.RemoteException;
42 import android.provider.MediaStore;
43 import android.provider.Settings;
44 import android.util.Log;
45 import android.view.SubMenu;
46 import android.view.View;
47 import android.view.Window;
48 import android.widget.TextView;
49 import android.widget.Toast;
52 import java.io.FileDescriptor;
53 import java.io.FileNotFoundException;
54 import java.io.IOException;
55 import java.io.InputStream;
56 import java.util.Arrays;
57 import java.util.Formatter;
58 import java.util.HashMap;
59 import java.util.Locale;
61 public class MusicUtils {
63 private static final String TAG = "MusicUtils";
65 public interface Defs {
66 public final static int OPEN_URL = 0;
67 public final static int ADD_TO_PLAYLIST = 1;
68 public final static int USE_AS_RINGTONE = 2;
69 public final static int PLAYLIST_SELECTED = 3;
70 public final static int NEW_PLAYLIST = 4;
71 public final static int PLAY_SELECTION = 5;
72 public final static int GOTO_START = 6;
73 public final static int GOTO_PLAYBACK = 7;
74 public final static int PARTY_SHUFFLE = 8;
75 public final static int SHUFFLE_ALL = 9;
76 public final static int DELETE_ITEM = 10;
77 public final static int SCAN_DONE = 11;
78 public final static int QUEUE = 12;
79 public final static int CHILD_MENU_BASE = 13; // this should be the last item
82 public static String makeAlbumsLabel(Context context, int numalbums, int numsongs, boolean isUnknown) {
83 // There are two formats for the albums/songs information:
84 // "N Song(s)" - used for unknown artist/album
85 // "N Album(s)" - used for known albums
87 StringBuilder songs_albums = new StringBuilder();
89 Resources r = context.getResources();
92 songs_albums.append(context.getString(R.string.onesong));
94 String f = r.getQuantityText(R.plurals.Nsongs, numsongs).toString();
95 sFormatBuilder.setLength(0);
96 sFormatter.format(f, Integer.valueOf(numsongs));
97 songs_albums.append(sFormatBuilder);
100 String f = r.getQuantityText(R.plurals.Nalbums, numalbums).toString();
101 sFormatBuilder.setLength(0);
102 sFormatter.format(f, Integer.valueOf(numalbums));
103 songs_albums.append(sFormatBuilder);
104 songs_albums.append(context.getString(R.string.albumsongseparator));
106 return songs_albums.toString();
110 * This is now only used for the query screen
112 public static String makeAlbumsSongsLabel(Context context, int numalbums, int numsongs, boolean isUnknown) {
113 // There are several formats for the albums/songs information:
114 // "1 Song" - used if there is only 1 song
115 // "N Songs" - used for the "unknown artist" item
116 // "1 Album"/"N Songs"
117 // "N Album"/"M Songs"
118 // Depending on locale, these may need to be further subdivided
120 StringBuilder songs_albums = new StringBuilder();
123 songs_albums.append(context.getString(R.string.onesong));
125 Resources r = context.getResources();
127 String f = r.getQuantityText(R.plurals.Nalbums, numalbums).toString();
128 sFormatBuilder.setLength(0);
129 sFormatter.format(f, Integer.valueOf(numalbums));
130 songs_albums.append(sFormatBuilder);
131 songs_albums.append(context.getString(R.string.albumsongseparator));
133 String f = r.getQuantityText(R.plurals.Nsongs, numsongs).toString();
134 sFormatBuilder.setLength(0);
135 sFormatter.format(f, Integer.valueOf(numsongs));
136 songs_albums.append(sFormatBuilder);
138 return songs_albums.toString();
141 public static IMediaPlaybackService sService = null;
142 private static HashMap<Context, ServiceBinder> sConnectionMap = new HashMap<Context, ServiceBinder>();
144 public static boolean bindToService(Context context) {
145 return bindToService(context, null);
148 public static boolean bindToService(Context context, ServiceConnection callback) {
149 context.startService(new Intent(context, MediaPlaybackService.class));
150 ServiceBinder sb = new ServiceBinder(callback);
151 sConnectionMap.put(context, sb);
152 return context.bindService((new Intent()).setClass(context,
153 MediaPlaybackService.class), sb, 0);
156 public static void unbindFromService(Context context) {
157 ServiceBinder sb = (ServiceBinder) sConnectionMap.remove(context);
159 Log.e("MusicUtils", "Trying to unbind for unknown Context");
162 context.unbindService(sb);
163 if (sConnectionMap.isEmpty()) {
164 // presumably there is nobody interested in the service at this point,
165 // so don't hang on to the ServiceConnection
170 private static class ServiceBinder implements ServiceConnection {
171 ServiceConnection mCallback;
172 ServiceBinder(ServiceConnection callback) {
173 mCallback = callback;
176 public void onServiceConnected(ComponentName className, android.os.IBinder service) {
177 sService = IMediaPlaybackService.Stub.asInterface(service);
179 if (mCallback != null) {
180 mCallback.onServiceConnected(className, service);
184 public void onServiceDisconnected(ComponentName className) {
185 if (mCallback != null) {
186 mCallback.onServiceDisconnected(className);
192 public static long getCurrentAlbumId() {
193 if (sService != null) {
195 return sService.getAlbumId();
196 } catch (RemoteException ex) {
202 public static long getCurrentArtistId() {
203 if (MusicUtils.sService != null) {
205 return sService.getArtistId();
206 } catch (RemoteException ex) {
212 public static long getCurrentAudioId() {
213 if (MusicUtils.sService != null) {
215 return sService.getAudioId();
216 } catch (RemoteException ex) {
222 public static int getCurrentShuffleMode() {
223 int mode = MediaPlaybackService.SHUFFLE_NONE;
224 if (sService != null) {
226 mode = sService.getShuffleMode();
227 } catch (RemoteException ex) {
234 * Returns true if a file is currently opened for playback (regardless
235 * of whether it's playing or paused).
237 public static boolean isMusicLoaded() {
238 if (MusicUtils.sService != null) {
240 return sService.getPath() != null;
241 } catch (RemoteException ex) {
247 private final static long [] sEmptyList = new long[0];
249 public static long [] getSongListForCursor(Cursor cursor) {
250 if (cursor == null) {
253 int len = cursor.getCount();
254 long [] list = new long[len];
255 cursor.moveToFirst();
258 colidx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members.AUDIO_ID);
259 } catch (IllegalArgumentException ex) {
260 colidx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
262 for (int i = 0; i < len; i++) {
263 list[i] = cursor.getLong(colidx);
269 public static long [] getSongListForArtist(Context context, long id) {
270 final String[] ccols = new String[] { MediaStore.Audio.Media._ID };
271 String where = MediaStore.Audio.Media.ARTIST_ID + "=" + id + " AND " +
272 MediaStore.Audio.Media.IS_MUSIC + "=1";
273 Cursor cursor = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
275 MediaStore.Audio.Media.ALBUM_KEY + "," + MediaStore.Audio.Media.TRACK);
277 if (cursor != null) {
278 long [] list = getSongListForCursor(cursor);
285 public static long [] getSongListForAlbum(Context context, long id) {
286 final String[] ccols = new String[] { MediaStore.Audio.Media._ID };
287 String where = MediaStore.Audio.Media.ALBUM_ID + "=" + id + " AND " +
288 MediaStore.Audio.Media.IS_MUSIC + "=1";
289 Cursor cursor = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
290 ccols, where, null, MediaStore.Audio.Media.TRACK);
292 if (cursor != null) {
293 long [] list = getSongListForCursor(cursor);
300 public static long [] getSongListForPlaylist(Context context, long plid) {
301 final String[] ccols = new String[] { MediaStore.Audio.Playlists.Members.AUDIO_ID };
302 Cursor cursor = query(context, MediaStore.Audio.Playlists.Members.getContentUri("external", plid),
303 ccols, null, null, MediaStore.Audio.Playlists.Members.DEFAULT_SORT_ORDER);
305 if (cursor != null) {
306 long [] list = getSongListForCursor(cursor);
313 public static void playPlaylist(Context context, long plid) {
314 long [] list = getSongListForPlaylist(context, plid);
316 playAll(context, list, -1, false);
320 public static long [] getAllSongs(Context context) {
321 Cursor c = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
322 new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
325 if (c == null || c.getCount() == 0) {
328 int len = c.getCount();
329 long [] list = new long[len];
330 for (int i = 0; i < len; i++) {
332 list[i] = c.getLong(0);
344 * Fills out the given submenu with items for "new playlist" and
345 * any existing playlists. When the user selects an item, the
346 * application will receive PLAYLIST_SELECTED with the Uri of
347 * the selected playlist, NEW_PLAYLIST if a new playlist
348 * should be created, and QUEUE if the "current playlist" was
350 * @param context The context to use for creating the menu items
351 * @param sub The submenu to add the items to.
353 public static void makePlaylistMenu(Context context, SubMenu sub) {
354 String[] cols = new String[] {
355 MediaStore.Audio.Playlists._ID,
356 MediaStore.Audio.Playlists.NAME
358 ContentResolver resolver = context.getContentResolver();
359 if (resolver == null) {
360 System.out.println("resolver = null");
362 String whereclause = MediaStore.Audio.Playlists.NAME + " != ''";
363 Cursor cur = resolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
364 cols, whereclause, null,
365 MediaStore.Audio.Playlists.NAME);
367 sub.add(1, Defs.QUEUE, 0, R.string.queue);
368 sub.add(1, Defs.NEW_PLAYLIST, 0, R.string.new_playlist);
369 if (cur != null && cur.getCount() > 0) {
370 //sub.addSeparator(1, 0);
372 while (! cur.isAfterLast()) {
373 Intent intent = new Intent();
374 intent.putExtra("playlist", cur.getLong(0));
375 // if (cur.getInt(0) == mLastPlaylistSelected) {
376 // sub.add(0, MusicBaseActivity.PLAYLIST_SELECTED, cur.getString(1)).setIntent(intent);
378 sub.add(1, Defs.PLAYLIST_SELECTED, 0, cur.getString(1)).setIntent(intent);
389 public static void clearPlaylist(Context context, int plid) {
391 Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", plid);
392 context.getContentResolver().delete(uri, null, null);
396 public static void deleteTracks(Context context, long [] list) {
398 String [] cols = new String [] { MediaStore.Audio.Media._ID,
399 MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM_ID };
400 StringBuilder where = new StringBuilder();
401 where.append(MediaStore.Audio.Media._ID + " IN (");
402 for (int i = 0; i < list.length; i++) {
403 where.append(list[i]);
404 if (i < list.length - 1) {
409 Cursor c = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cols,
410 where.toString(), null, null);
414 // step 1: remove selected tracks from the current playlist, as well
415 // as from the album art cache
418 while (! c.isAfterLast()) {
419 // remove from current playlist
420 long id = c.getLong(0);
421 sService.removeTrack(id);
422 // remove from album art cache
423 long artIndex = c.getLong(2);
424 synchronized(sArtCache) {
425 sArtCache.remove(artIndex);
429 } catch (RemoteException ex) {
432 // step 2: remove selected tracks from the database
433 context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, where.toString(), null);
435 // step 3: remove files from card
437 while (! c.isAfterLast()) {
438 String name = c.getString(1);
439 File f = new File(name);
440 try { // File.delete can throw a security exception
442 // I'm not sure if we'd ever get here (deletion would
443 // have to fail, but no exception thrown)
444 Log.e("MusicUtils", "Failed to delete file " + name);
447 } catch (SecurityException ex) {
454 String message = context.getResources().getQuantityString(
455 R.plurals.NNNtracksdeleted, list.length, Integer.valueOf(list.length));
457 Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
458 // We deleted a number of tracks, which could affect any number of things
459 // in the media content domain, so update everything.
460 context.getContentResolver().notifyChange(Uri.parse("content://media"), null);
463 public static void addToCurrentPlaylist(Context context, long [] list) {
464 if (sService == null) {
468 sService.enqueue(list, MediaPlaybackService.LAST);
469 String message = context.getResources().getQuantityString(
470 R.plurals.NNNtrackstoplaylist, list.length, Integer.valueOf(list.length));
471 Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
472 } catch (RemoteException ex) {
476 public static void addToPlaylist(Context context, long [] ids, long playlistid) {
478 // this shouldn't happen (the menuitems shouldn't be visible
479 // unless the selected item represents something playable
480 Log.e("MusicBase", "ListSelection null");
482 int size = ids.length;
483 ContentValues values [] = new ContentValues[size];
484 ContentResolver resolver = context.getContentResolver();
485 // need to determine the number of items currently in the playlist,
486 // so the play_order field can be maintained.
487 String[] cols = new String[] {
490 Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
491 Cursor cur = resolver.query(uri, cols, null, null, null);
493 int base = cur.getInt(0);
496 for (int i = 0; i < size; i++) {
497 values[i] = new ContentValues();
498 values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, Integer.valueOf(base + i));
499 values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, ids[i]);
501 resolver.bulkInsert(uri, values);
502 String message = context.getResources().getQuantityString(
503 R.plurals.NNNtrackstoplaylist, size, Integer.valueOf(size));
504 Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
505 //mLastPlaylistSelected = playlistid;
509 public static Cursor query(Context context, Uri uri, String[] projection,
510 String selection, String[] selectionArgs, String sortOrder) {
512 ContentResolver resolver = context.getContentResolver();
513 if (resolver == null) {
516 return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
517 } catch (UnsupportedOperationException ex) {
523 public static boolean isMediaScannerScanning(Context context) {
524 boolean result = false;
525 Cursor cursor = query(context, MediaStore.getMediaScannerUri(),
526 new String [] { MediaStore.MEDIA_SCANNER_VOLUME }, null, null, null);
527 if (cursor != null) {
528 if (cursor.getCount() == 1) {
529 cursor.moveToFirst();
530 result = "external".equals(cursor.getString(0));
538 public static void setSpinnerState(Activity a) {
539 if (isMediaScannerScanning(a)) {
540 // start the progress spinner
541 a.getWindow().setFeatureInt(
542 Window.FEATURE_INDETERMINATE_PROGRESS,
543 Window.PROGRESS_INDETERMINATE_ON);
545 a.getWindow().setFeatureInt(
546 Window.FEATURE_INDETERMINATE_PROGRESS,
547 Window.PROGRESS_VISIBILITY_ON);
549 // stop the progress spinner
550 a.getWindow().setFeatureInt(
551 Window.FEATURE_INDETERMINATE_PROGRESS,
552 Window.PROGRESS_VISIBILITY_OFF);
556 public static void displayDatabaseError(Activity a) {
557 String status = Environment.getExternalStorageState();
558 int title = R.string.sdcard_error_title;
559 int message = R.string.sdcard_error_message;
561 if (status.equals(Environment.MEDIA_SHARED) ||
562 status.equals(Environment.MEDIA_UNMOUNTED)) {
563 title = R.string.sdcard_busy_title;
564 message = R.string.sdcard_busy_message;
565 } else if (status.equals(Environment.MEDIA_REMOVED)) {
566 title = R.string.sdcard_missing_title;
567 message = R.string.sdcard_missing_message;
568 } else if (status.equals(Environment.MEDIA_MOUNTED)){
569 // The card is mounted, but we didn't get a valid cursor.
570 // This probably means the mediascanner hasn't started scanning the
571 // card yet (there is a small window of time during boot where this
574 Intent intent = new Intent();
575 intent.setClass(a, ScanningProgress.class);
576 a.startActivityForResult(intent, Defs.SCAN_DONE);
578 Log.d(TAG, "sd card: " + status);
582 View v = a.findViewById(R.id.sd_message);
584 v.setVisibility(View.VISIBLE);
586 v = a.findViewById(R.id.sd_icon);
588 v.setVisibility(View.VISIBLE);
590 v = a.findViewById(android.R.id.list);
592 v.setVisibility(View.GONE);
594 TextView tv = (TextView) a.findViewById(R.id.sd_message);
598 public static void hideDatabaseError(Activity a) {
599 View v = a.findViewById(R.id.sd_message);
601 v.setVisibility(View.GONE);
603 v = a.findViewById(R.id.sd_icon);
605 v.setVisibility(View.GONE);
607 v = a.findViewById(android.R.id.list);
609 v.setVisibility(View.VISIBLE);
613 static protected Uri getContentURIForPath(String path) {
614 return Uri.fromFile(new File(path));
618 /* Try to use String.format() as little as possible, because it creates a
619 * new Formatter every time you call it, which is very inefficient.
620 * Reusing an existing Formatter more than tripled the speed of
622 * This Formatter/StringBuilder are also used by makeAlbumSongsLabel()
624 private static StringBuilder sFormatBuilder = new StringBuilder();
625 private static Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault());
626 private static final Object[] sTimeArgs = new Object[5];
628 public static String makeTimeString(Context context, long secs) {
629 String durationformat = context.getString(R.string.durationformat);
631 /* Provide multiple arguments so the format can be changed easily
632 * by modifying the xml.
634 sFormatBuilder.setLength(0);
636 final Object[] timeArgs = sTimeArgs;
637 timeArgs[0] = secs / 3600;
638 timeArgs[1] = secs / 60;
639 timeArgs[2] = (secs / 60) % 60;
641 timeArgs[4] = secs % 60;
643 return sFormatter.format(durationformat, timeArgs).toString();
646 public static void shuffleAll(Context context, Cursor cursor) {
647 playAll(context, cursor, 0, true);
650 public static void playAll(Context context, Cursor cursor) {
651 playAll(context, cursor, 0, false);
654 public static void playAll(Context context, Cursor cursor, int position) {
655 playAll(context, cursor, position, false);
658 public static void playAll(Context context, long [] list, int position) {
659 playAll(context, list, position, false);
662 private static void playAll(Context context, Cursor cursor, int position, boolean force_shuffle) {
664 long [] list = getSongListForCursor(cursor);
665 playAll(context, list, position, force_shuffle);
668 private static void playAll(Context context, long [] list, int position, boolean force_shuffle) {
669 if (list.length == 0 || sService == null) {
670 Log.d("MusicUtils", "attempt to play empty song list");
671 // Don't try to play empty playlists. Nothing good will come of it.
672 String message = context.getString(R.string.emptyplaylist, list.length);
673 Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
678 sService.setShuffleMode(MediaPlaybackService.SHUFFLE_NORMAL);
680 long curid = sService.getAudioId();
681 int curpos = sService.getQueuePosition();
682 if (position != -1 && curpos == position && curid == list[position]) {
683 // The selected file is the file that's currently playing;
684 // figure out if we need to restart with a new playlist,
685 // or just launch the playback activity.
686 long [] playlist = sService.getQueue();
687 if (Arrays.equals(list, playlist)) {
688 // we don't need to set a new list, but we should resume playback if needed
690 return; // the 'finally' block will still run
696 sService.open(list, force_shuffle ? -1 : position);
698 } catch (RemoteException ex) {
700 Intent intent = new Intent("com.android.music.PLAYBACK_VIEWER")
701 .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
702 context.startActivity(intent);
706 public static void clearQueue() {
708 sService.removeTracks(0, Integer.MAX_VALUE);
709 } catch (RemoteException ex) {
713 // A really simple BitmapDrawable-like class, that doesn't do
714 // scaling, dithering or filtering.
715 private static class FastBitmapDrawable extends Drawable {
716 private Bitmap mBitmap;
717 public FastBitmapDrawable(Bitmap b) {
721 public void draw(Canvas canvas) {
722 canvas.drawBitmap(mBitmap, 0, 0, null);
725 public int getOpacity() {
726 return PixelFormat.OPAQUE;
729 public void setAlpha(int alpha) {
732 public void setColorFilter(ColorFilter cf) {
736 private static int sArtId = -2;
737 private static Bitmap mCachedBit = null;
738 private static final BitmapFactory.Options sBitmapOptionsCache = new BitmapFactory.Options();
739 private static final BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options();
740 private static final Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
741 private static final HashMap<Long, Drawable> sArtCache = new HashMap<Long, Drawable>();
742 private static int sArtCacheId = -1;
746 // 565 is faster to decode and display
747 // and we don't want to dither here because the image will be scaled down later
748 sBitmapOptionsCache.inPreferredConfig = Bitmap.Config.RGB_565;
749 sBitmapOptionsCache.inDither = false;
751 sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
752 sBitmapOptions.inDither = false;
755 public static void initAlbumArtCache() {
757 int id = sService.getMediaMountedCount();
758 if (id != sArtCacheId) {
759 clearAlbumArtCache();
762 } catch (RemoteException e) {
767 public static void clearAlbumArtCache() {
768 synchronized(sArtCache) {
773 public static Drawable getCachedArtwork(Context context, long artIndex, BitmapDrawable defaultArtwork) {
775 synchronized(sArtCache) {
776 d = sArtCache.get(artIndex);
780 final Bitmap icon = defaultArtwork.getBitmap();
781 int w = icon.getWidth();
782 int h = icon.getHeight();
783 Bitmap b = MusicUtils.getArtworkQuick(context, artIndex, w, h);
785 d = new FastBitmapDrawable(b);
786 synchronized(sArtCache) {
787 // the cache may have changed since we checked
788 Drawable value = sArtCache.get(artIndex);
790 sArtCache.put(artIndex, d);
800 // Get album art for specified album. This method will not try to
801 // fall back to getting artwork directly from the file, nor will
802 // it attempt to repair the database.
803 private static Bitmap getArtworkQuick(Context context, long album_id, int w, int h) {
804 // NOTE: There is in fact a 1 pixel border on the right side in the ImageView
805 // used to display this drawable. Take it into account now, so we don't have to
808 ContentResolver res = context.getContentResolver();
809 Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
811 ParcelFileDescriptor fd = null;
813 fd = res.openFileDescriptor(uri, "r");
816 // Compute the closest power-of-two scale factor
817 // and pass that to sBitmapOptionsCache.inSampleSize, which will
818 // result in faster decoding and better quality
819 sBitmapOptionsCache.inJustDecodeBounds = true;
820 BitmapFactory.decodeFileDescriptor(
821 fd.getFileDescriptor(), null, sBitmapOptionsCache);
822 int nextWidth = sBitmapOptionsCache.outWidth >> 1;
823 int nextHeight = sBitmapOptionsCache.outHeight >> 1;
824 while (nextWidth>w && nextHeight>h) {
830 sBitmapOptionsCache.inSampleSize = sampleSize;
831 sBitmapOptionsCache.inJustDecodeBounds = false;
832 Bitmap b = BitmapFactory.decodeFileDescriptor(
833 fd.getFileDescriptor(), null, sBitmapOptionsCache);
836 // finally rescale to exactly the size we need
837 if (sBitmapOptionsCache.outWidth != w || sBitmapOptionsCache.outHeight != h) {
838 Bitmap tmp = Bitmap.createScaledBitmap(b, w, h, true);
839 // Bitmap.createScaledBitmap() can return the same bitmap
840 if (tmp != b) b.recycle();
846 } catch (FileNotFoundException e) {
851 } catch (IOException e) {
858 /** Get album art for specified album. You should not pass in the album id
859 * for the "unknown" album here (use -1 instead)
861 public static Bitmap getArtwork(Context context, long song_id, long album_id) {
864 // This is something that is not in the database, so get the album art directly
867 Bitmap bm = getArtworkFromFile(context, song_id, -1);
872 return getDefaultArtwork(context);
875 ContentResolver res = context.getContentResolver();
876 Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
878 InputStream in = null;
880 in = res.openInputStream(uri);
881 return BitmapFactory.decodeStream(in, null, sBitmapOptions);
882 } catch (FileNotFoundException ex) {
883 // The album art thumbnail does not actually exist. Maybe the user deleted it, or
884 // maybe it never existed to begin with.
885 Bitmap bm = getArtworkFromFile(context, song_id, album_id);
887 if (bm.getConfig() == null) {
888 bm = bm.copy(Bitmap.Config.RGB_565, false);
890 return getDefaultArtwork(context);
894 bm = getDefaultArtwork(context);
902 } catch (IOException ex) {
910 // get album art for specified file
911 private static final String sExternalMediaUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString();
912 private static Bitmap getArtworkFromFile(Context context, long songid, long albumid) {
917 if (albumid < 0 && songid < 0) {
918 throw new IllegalArgumentException("Must specify an album or a song id");
923 Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart");
924 ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
926 FileDescriptor fd = pfd.getFileDescriptor();
927 bm = BitmapFactory.decodeFileDescriptor(fd);
930 Uri uri = ContentUris.withAppendedId(sArtworkUri, albumid);
931 ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
933 FileDescriptor fd = pfd.getFileDescriptor();
934 bm = BitmapFactory.decodeFileDescriptor(fd);
937 } catch (FileNotFoundException ex) {
946 private static Bitmap getDefaultArtwork(Context context) {
947 BitmapFactory.Options opts = new BitmapFactory.Options();
948 opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
949 return BitmapFactory.decodeStream(
950 context.getResources().openRawResource(R.drawable.albumart_mp_unknown), null, opts);
953 static int getIntPref(Context context, String name, int def) {
954 SharedPreferences prefs =
955 context.getSharedPreferences("com.android.music", Context.MODE_PRIVATE);
956 return prefs.getInt(name, def);
959 static void setIntPref(Context context, String name, int value) {
960 SharedPreferences prefs =
961 context.getSharedPreferences("com.android.music", Context.MODE_PRIVATE);
962 Editor ed = prefs.edit();
963 ed.putInt(name, value);
967 static void setRingtone(Context context, long id) {
968 ContentResolver resolver = context.getContentResolver();
969 // Set the flag in the database to mark this as a ringtone
970 Uri ringUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
972 ContentValues values = new ContentValues(2);
973 values.put(MediaStore.Audio.Media.IS_RINGTONE, "1");
974 values.put(MediaStore.Audio.Media.IS_ALARM, "1");
975 resolver.update(ringUri, values, null, null);
976 } catch (UnsupportedOperationException ex) {
977 // most likely the card just got unmounted
978 Log.e(TAG, "couldn't set ringtone flag for id " + id);
982 String[] cols = new String[] {
983 MediaStore.Audio.Media._ID,
984 MediaStore.Audio.Media.DATA,
985 MediaStore.Audio.Media.TITLE
988 String where = MediaStore.Audio.Media._ID + "=" + id;
989 Cursor cursor = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
990 cols, where , null, null);
992 if (cursor != null && cursor.getCount() == 1) {
993 // Set the system setting to make this the current ringtone
994 cursor.moveToFirst();
995 Settings.System.putString(resolver, Settings.System.RINGTONE, ringUri.toString());
996 String message = context.getString(R.string.ringtone_set, cursor.getString(2));
997 Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
1000 if (cursor != null) {