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;
20 import java.io.FileDescriptor;
21 import java.io.FileInputStream;
22 import java.io.FileNotFoundException;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.OutputStream;
27 import java.util.Arrays;
28 import java.util.Formatter;
29 import java.util.HashMap;
30 import java.util.Locale;
32 import android.app.Activity;
33 import android.app.ExpandableListActivity;
34 import android.content.ComponentName;
35 import android.content.ContentResolver;
36 import android.content.ContentUris;
37 import android.content.ContentValues;
38 import android.content.Context;
39 import android.content.Intent;
40 import android.content.ServiceConnection;
41 import android.content.SharedPreferences;
42 import android.content.SharedPreferences.Editor;
43 import android.content.res.Resources;
44 import android.database.Cursor;
45 import android.graphics.Bitmap;
46 import android.graphics.BitmapFactory;
47 import android.graphics.Canvas;
48 import android.graphics.ColorFilter;
49 import android.graphics.PixelFormat;
50 import android.graphics.drawable.BitmapDrawable;
51 import android.graphics.drawable.Drawable;
52 import android.media.MediaFile;
53 import android.media.MediaScanner;
54 import android.net.Uri;
55 import android.os.RemoteException;
56 import android.os.Environment;
57 import android.os.ParcelFileDescriptor;
58 import android.provider.MediaStore;
59 import android.provider.Settings;
60 import android.util.Log;
61 import android.view.SubMenu;
62 import android.view.View;
63 import android.view.Window;
64 import android.widget.TextView;
65 import android.widget.Toast;
67 public class MusicUtils {
69 private static final String TAG = "MusicUtils";
71 public interface Defs {
72 public final static int OPEN_URL = 0;
73 public final static int ADD_TO_PLAYLIST = 1;
74 public final static int USE_AS_RINGTONE = 2;
75 public final static int PLAYLIST_SELECTED = 3;
76 public final static int NEW_PLAYLIST = 4;
77 public final static int PLAY_SELECTION = 5;
78 public final static int GOTO_START = 6;
79 public final static int GOTO_PLAYBACK = 7;
80 public final static int PARTY_SHUFFLE = 8;
81 public final static int SHUFFLE_ALL = 9;
82 public final static int DELETE_ITEM = 10;
83 public final static int SCAN_DONE = 11;
84 public final static int QUEUE = 12;
85 public final static int CHILD_MENU_BASE = 13; // this should be the last item
88 public static String makeAlbumsLabel(Context context, int numalbums, int numsongs, boolean isUnknown) {
89 // There are two formats for the albums/songs information:
90 // "N Song(s)" - used for unknown artist/album
91 // "N Album(s)" - used for known albums
93 StringBuilder songs_albums = new StringBuilder();
95 Resources r = context.getResources();
98 songs_albums.append(context.getString(R.string.onesong));
100 String f = r.getQuantityText(R.plurals.Nsongs, numsongs).toString();
101 sFormatBuilder.setLength(0);
102 sFormatter.format(f, Integer.valueOf(numsongs));
103 songs_albums.append(sFormatBuilder);
106 String f = r.getQuantityText(R.plurals.Nalbums, numalbums).toString();
107 sFormatBuilder.setLength(0);
108 sFormatter.format(f, Integer.valueOf(numalbums));
109 songs_albums.append(sFormatBuilder);
110 songs_albums.append(context.getString(R.string.albumsongseparator));
112 return songs_albums.toString();
116 * This is now only used for the query screen
118 public static String makeAlbumsSongsLabel(Context context, int numalbums, int numsongs, boolean isUnknown) {
119 // There are several formats for the albums/songs information:
120 // "1 Song" - used if there is only 1 song
121 // "N Songs" - used for the "unknown artist" item
122 // "1 Album"/"N Songs"
123 // "N Album"/"M Songs"
124 // Depending on locale, these may need to be further subdivided
126 StringBuilder songs_albums = new StringBuilder();
129 songs_albums.append(context.getString(R.string.onesong));
131 Resources r = context.getResources();
133 String f = r.getQuantityText(R.plurals.Nalbums, numalbums).toString();
134 sFormatBuilder.setLength(0);
135 sFormatter.format(f, Integer.valueOf(numalbums));
136 songs_albums.append(sFormatBuilder);
137 songs_albums.append(context.getString(R.string.albumsongseparator));
139 String f = r.getQuantityText(R.plurals.Nsongs, numsongs).toString();
140 sFormatBuilder.setLength(0);
141 sFormatter.format(f, Integer.valueOf(numsongs));
142 songs_albums.append(sFormatBuilder);
144 return songs_albums.toString();
147 public static IMediaPlaybackService sService = null;
148 private static HashMap<Context, ServiceBinder> sConnectionMap = new HashMap<Context, ServiceBinder>();
150 public static boolean bindToService(Context context) {
151 return bindToService(context, null);
154 public static boolean bindToService(Context context, ServiceConnection callback) {
155 context.startService(new Intent(context, MediaPlaybackService.class));
156 ServiceBinder sb = new ServiceBinder(callback);
157 sConnectionMap.put(context, sb);
158 return context.bindService((new Intent()).setClass(context,
159 MediaPlaybackService.class), sb, 0);
162 public static void unbindFromService(Context context) {
163 ServiceBinder sb = (ServiceBinder) sConnectionMap.remove(context);
165 Log.e("MusicUtils", "Trying to unbind for unknown Context");
168 context.unbindService(sb);
169 if (sConnectionMap.isEmpty()) {
170 // presumably there is nobody interested in the service at this point,
171 // so don't hang on to the ServiceConnection
176 private static class ServiceBinder implements ServiceConnection {
177 ServiceConnection mCallback;
178 ServiceBinder(ServiceConnection callback) {
179 mCallback = callback;
182 public void onServiceConnected(ComponentName className, android.os.IBinder service) {
183 sService = IMediaPlaybackService.Stub.asInterface(service);
185 if (mCallback != null) {
186 mCallback.onServiceConnected(className, service);
190 public void onServiceDisconnected(ComponentName className) {
191 if (mCallback != null) {
192 mCallback.onServiceDisconnected(className);
198 public static int getCurrentAlbumId() {
199 if (sService != null) {
201 return sService.getAlbumId();
202 } catch (RemoteException ex) {
208 public static int getCurrentArtistId() {
209 if (MusicUtils.sService != null) {
211 return sService.getArtistId();
212 } catch (RemoteException ex) {
218 public static int getCurrentAudioId() {
219 if (MusicUtils.sService != null) {
221 return sService.getAudioId();
222 } catch (RemoteException ex) {
228 public static int getCurrentShuffleMode() {
229 int mode = MediaPlaybackService.SHUFFLE_NONE;
230 if (sService != null) {
232 mode = sService.getShuffleMode();
233 } catch (RemoteException ex) {
240 * Returns true if a file is currently opened for playback (regardless
241 * of whether it's playing or paused).
243 public static boolean isMusicLoaded() {
244 if (MusicUtils.sService != null) {
246 return sService.getPath() != null;
247 } catch (RemoteException ex) {
253 private final static int [] sEmptyList = new int[0];
255 public static int [] getSongListForCursor(Cursor cursor) {
256 if (cursor == null) {
259 int len = cursor.getCount();
260 int [] list = new int[len];
261 cursor.moveToFirst();
264 colidx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members.AUDIO_ID);
265 } catch (IllegalArgumentException ex) {
266 colidx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
268 for (int i = 0; i < len; i++) {
269 list[i] = cursor.getInt(colidx);
275 public static int [] getSongListForArtist(Context context, int id) {
276 final String[] ccols = new String[] { MediaStore.Audio.Media._ID };
277 String where = MediaStore.Audio.Media.ARTIST_ID + "=" + id + " AND " +
278 MediaStore.Audio.Media.IS_MUSIC + "=1";
279 Cursor cursor = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
281 MediaStore.Audio.Media.ALBUM_KEY + "," + MediaStore.Audio.Media.TRACK);
283 if (cursor != null) {
284 int [] list = getSongListForCursor(cursor);
291 public static int [] getSongListForAlbum(Context context, int id) {
292 final String[] ccols = new String[] { MediaStore.Audio.Media._ID };
293 String where = MediaStore.Audio.Media.ALBUM_ID + "=" + id + " AND " +
294 MediaStore.Audio.Media.IS_MUSIC + "=1";
295 Cursor cursor = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
296 ccols, where, null, MediaStore.Audio.Media.TRACK);
298 if (cursor != null) {
299 int [] list = getSongListForCursor(cursor);
306 public static int [] getSongListForPlaylist(Context context, long plid) {
307 final String[] ccols = new String[] { MediaStore.Audio.Playlists.Members.AUDIO_ID };
308 Cursor cursor = query(context, MediaStore.Audio.Playlists.Members.getContentUri("external", plid),
309 ccols, null, null, MediaStore.Audio.Playlists.Members.DEFAULT_SORT_ORDER);
311 if (cursor != null) {
312 int [] list = getSongListForCursor(cursor);
319 public static void playPlaylist(Context context, long plid) {
320 int [] list = getSongListForPlaylist(context, plid);
322 playAll(context, list, -1, false);
326 public static int [] getAllSongs(Context context) {
327 Cursor c = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
328 new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
331 if (c == null || c.getCount() == 0) {
334 int len = c.getCount();
335 int[] list = new int[len];
336 for (int i = 0; i < len; i++) {
338 list[i] = c.getInt(0);
350 * Fills out the given submenu with items for "new playlist" and
351 * any existing playlists. When the user selects an item, the
352 * application will receive PLAYLIST_SELECTED with the Uri of
353 * the selected playlist, NEW_PLAYLIST if a new playlist
354 * should be created, and QUEUE if the "current playlist" was
356 * @param context The context to use for creating the menu items
357 * @param sub The submenu to add the items to.
359 public static void makePlaylistMenu(Context context, SubMenu sub) {
360 String[] cols = new String[] {
361 MediaStore.Audio.Playlists._ID,
362 MediaStore.Audio.Playlists.NAME
364 ContentResolver resolver = context.getContentResolver();
365 if (resolver == null) {
366 System.out.println("resolver = null");
368 String whereclause = MediaStore.Audio.Playlists.NAME + " != ''";
369 Cursor cur = resolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
370 cols, whereclause, null,
371 MediaStore.Audio.Playlists.NAME);
373 sub.add(1, Defs.QUEUE, 0, R.string.queue);
374 sub.add(1, Defs.NEW_PLAYLIST, 0, R.string.new_playlist);
375 if (cur != null && cur.getCount() > 0) {
376 //sub.addSeparator(1, 0);
378 while (! cur.isAfterLast()) {
379 Intent intent = new Intent();
380 intent.putExtra("playlist", cur.getInt(0));
381 // if (cur.getInt(0) == mLastPlaylistSelected) {
382 // sub.add(0, MusicBaseActivity.PLAYLIST_SELECTED, cur.getString(1)).setIntent(intent);
384 sub.add(1, Defs.PLAYLIST_SELECTED, 0, cur.getString(1)).setIntent(intent);
395 public static void clearPlaylist(Context context, int plid) {
397 Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", plid);
398 context.getContentResolver().delete(uri, null, null);
402 public static void deleteTracks(Context context, int [] list) {
404 String [] cols = new String [] { MediaStore.Audio.Media._ID,
405 MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM_ID };
406 StringBuilder where = new StringBuilder();
407 where.append(MediaStore.Audio.Media._ID + " IN (");
408 for (int i = 0; i < list.length; i++) {
409 where.append(list[i]);
410 if (i < list.length - 1) {
415 Cursor c = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cols,
416 where.toString(), null, null);
420 // step 1: remove selected tracks from the current playlist, as well
421 // as from the album art cache
424 while (! c.isAfterLast()) {
425 // remove from current playlist
426 int id = c.getInt(0);
427 sService.removeTrack(id);
428 // remove from album art cache
429 int artIndex = c.getInt(2);
430 synchronized(sArtCache) {
431 sArtCache.remove(artIndex);
435 } catch (RemoteException ex) {
438 // step 2: remove selected tracks from the database
439 context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, where.toString(), null);
441 // step 3: remove files from card
443 while (! c.isAfterLast()) {
444 String name = c.getString(1);
445 File f = new File(name);
446 try { // File.delete can throw a security exception
448 // I'm not sure if we'd ever get here (deletion would
449 // have to fail, but no exception thrown)
450 Log.e("MusicUtils", "Failed to delete file " + name);
453 } catch (SecurityException ex) {
460 String message = context.getResources().getQuantityString(
461 R.plurals.NNNtracksdeleted, list.length, Integer.valueOf(list.length));
463 Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
464 // We deleted a number of tracks, which could affect any number of things
465 // in the media content domain, so update everything.
466 context.getContentResolver().notifyChange(Uri.parse("content://media"), null);
469 public static void addToCurrentPlaylist(Context context, int [] list) {
470 if (sService == null) {
474 sService.enqueue(list, MediaPlaybackService.LAST);
475 String message = context.getResources().getQuantityString(
476 R.plurals.NNNtrackstoplaylist, list.length, Integer.valueOf(list.length));
477 Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
478 } catch (RemoteException ex) {
482 public static void addToPlaylist(Context context, int [] ids, long playlistid) {
484 // this shouldn't happen (the menuitems shouldn't be visible
485 // unless the selected item represents something playable
486 Log.e("MusicBase", "ListSelection null");
488 int size = ids.length;
489 ContentValues values [] = new ContentValues[size];
490 ContentResolver resolver = context.getContentResolver();
491 // need to determine the number of items currently in the playlist,
492 // so the play_order field can be maintained.
493 String[] cols = new String[] {
496 Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
497 Cursor cur = resolver.query(uri, cols, null, null, null);
499 int base = cur.getInt(0);
502 for (int i = 0; i < size; i++) {
503 values[i] = new ContentValues();
504 values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, Integer.valueOf(base + i));
505 values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, ids[i]);
507 resolver.bulkInsert(uri, values);
508 String message = context.getResources().getQuantityString(
509 R.plurals.NNNtrackstoplaylist, size, Integer.valueOf(size));
510 Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
511 //mLastPlaylistSelected = playlistid;
515 public static Cursor query(Context context, Uri uri, String[] projection,
516 String selection, String[] selectionArgs, String sortOrder) {
518 ContentResolver resolver = context.getContentResolver();
519 if (resolver == null) {
522 return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
523 } catch (UnsupportedOperationException ex) {
529 public static boolean isMediaScannerScanning(Context context) {
530 boolean result = false;
531 Cursor cursor = query(context, MediaStore.getMediaScannerUri(),
532 new String [] { MediaStore.MEDIA_SCANNER_VOLUME }, null, null, null);
533 if (cursor != null) {
534 if (cursor.getCount() == 1) {
535 cursor.moveToFirst();
536 result = "external".equals(cursor.getString(0));
544 public static void setSpinnerState(Activity a) {
545 if (isMediaScannerScanning(a)) {
546 // start the progress spinner
547 a.getWindow().setFeatureInt(
548 Window.FEATURE_INDETERMINATE_PROGRESS,
549 Window.PROGRESS_INDETERMINATE_ON);
551 a.getWindow().setFeatureInt(
552 Window.FEATURE_INDETERMINATE_PROGRESS,
553 Window.PROGRESS_VISIBILITY_ON);
555 // stop the progress spinner
556 a.getWindow().setFeatureInt(
557 Window.FEATURE_INDETERMINATE_PROGRESS,
558 Window.PROGRESS_VISIBILITY_OFF);
562 public static void displayDatabaseError(Activity a) {
563 String status = Environment.getExternalStorageState();
564 int title = R.string.sdcard_error_title;
565 int message = R.string.sdcard_error_message;
567 if (status.equals(Environment.MEDIA_SHARED) ||
568 status.equals(Environment.MEDIA_UNMOUNTED)) {
569 title = R.string.sdcard_busy_title;
570 message = R.string.sdcard_busy_message;
571 } else if (status.equals(Environment.MEDIA_REMOVED)) {
572 title = R.string.sdcard_missing_title;
573 message = R.string.sdcard_missing_message;
574 } else if (status.equals(Environment.MEDIA_MOUNTED)){
575 // The card is mounted, but we didn't get a valid cursor.
576 // This probably means the mediascanner hasn't started scanning the
577 // card yet (there is a small window of time during boot where this
580 Intent intent = new Intent();
581 intent.setClass(a, ScanningProgress.class);
582 a.startActivityForResult(intent, Defs.SCAN_DONE);
584 Log.d(TAG, "sd card: " + status);
588 View v = a.findViewById(R.id.sd_message);
590 v.setVisibility(View.VISIBLE);
592 v = a.findViewById(R.id.sd_icon);
594 v.setVisibility(View.VISIBLE);
596 v = a.findViewById(android.R.id.list);
598 v.setVisibility(View.GONE);
600 TextView tv = (TextView) a.findViewById(R.id.sd_message);
604 public static void hideDatabaseError(Activity a) {
605 View v = a.findViewById(R.id.sd_message);
607 v.setVisibility(View.GONE);
609 v = a.findViewById(R.id.sd_icon);
611 v.setVisibility(View.GONE);
613 v = a.findViewById(android.R.id.list);
615 v.setVisibility(View.VISIBLE);
619 static protected Uri getContentURIForPath(String path) {
620 return Uri.fromFile(new File(path));
624 /* Try to use String.format() as little as possible, because it creates a
625 * new Formatter every time you call it, which is very inefficient.
626 * Reusing an existing Formatter more than tripled the speed of
628 * This Formatter/StringBuilder are also used by makeAlbumSongsLabel()
630 private static StringBuilder sFormatBuilder = new StringBuilder();
631 private static Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault());
632 private static final Object[] sTimeArgs = new Object[5];
634 public static String makeTimeString(Context context, long secs) {
635 String durationformat = context.getString(R.string.durationformat);
637 /* Provide multiple arguments so the format can be changed easily
638 * by modifying the xml.
640 sFormatBuilder.setLength(0);
642 final Object[] timeArgs = sTimeArgs;
643 timeArgs[0] = secs / 3600;
644 timeArgs[1] = secs / 60;
645 timeArgs[2] = (secs / 60) % 60;
647 timeArgs[4] = secs % 60;
649 return sFormatter.format(durationformat, timeArgs).toString();
652 public static void shuffleAll(Context context, Cursor cursor) {
653 playAll(context, cursor, 0, true);
656 public static void playAll(Context context, Cursor cursor) {
657 playAll(context, cursor, 0, false);
660 public static void playAll(Context context, Cursor cursor, int position) {
661 playAll(context, cursor, position, false);
664 public static void playAll(Context context, int [] list, int position) {
665 playAll(context, list, position, false);
668 private static void playAll(Context context, Cursor cursor, int position, boolean force_shuffle) {
670 int [] list = getSongListForCursor(cursor);
671 playAll(context, list, position, force_shuffle);
674 private static void playAll(Context context, int [] list, int position, boolean force_shuffle) {
675 if (list.length == 0 || sService == null) {
676 Log.d("MusicUtils", "attempt to play empty song list");
677 // Don't try to play empty playlists. Nothing good will come of it.
678 String message = context.getString(R.string.emptyplaylist, list.length);
679 Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
684 sService.setShuffleMode(MediaPlaybackService.SHUFFLE_NORMAL);
686 int curid = sService.getAudioId();
687 int curpos = sService.getQueuePosition();
688 if (position != -1 && curpos == position && curid == list[position]) {
689 // The selected file is the file that's currently playing;
690 // figure out if we need to restart with a new playlist,
691 // or just launch the playback activity.
692 int [] playlist = sService.getQueue();
693 if (Arrays.equals(list, playlist)) {
694 // we don't need to set a new list, but we should resume playback if needed
696 return; // the 'finally' block will still run
702 sService.open(list, force_shuffle ? -1 : position);
704 } catch (RemoteException ex) {
706 Intent intent = new Intent("com.android.music.PLAYBACK_VIEWER")
707 .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
708 context.startActivity(intent);
712 public static void clearQueue() {
714 sService.removeTracks(0, Integer.MAX_VALUE);
715 } catch (RemoteException ex) {
719 // A really simple BitmapDrawable-like class, that doesn't do
720 // scaling, dithering or filtering.
721 private static class FastBitmapDrawable extends Drawable {
722 private Bitmap mBitmap;
723 public FastBitmapDrawable(Bitmap b) {
727 public void draw(Canvas canvas) {
728 canvas.drawBitmap(mBitmap, 0, 0, null);
731 public int getOpacity() {
732 return PixelFormat.OPAQUE;
735 public void setAlpha(int alpha) {
738 public void setColorFilter(ColorFilter cf) {
742 private static int sArtId = -2;
743 private static byte [] mCachedArt;
744 private static Bitmap mCachedBit = null;
745 private static final BitmapFactory.Options sBitmapOptionsCache = new BitmapFactory.Options();
746 private static final BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options();
747 private static final Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
748 private static final HashMap<Integer, Drawable> sArtCache = new HashMap<Integer, Drawable>();
749 private static int sArtCacheId = -1;
753 // 565 is faster to decode and display
754 // and we don't want to dither here because the image will be scaled down later
755 sBitmapOptionsCache.inPreferredConfig = Bitmap.Config.RGB_565;
756 sBitmapOptionsCache.inDither = false;
758 sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
759 sBitmapOptions.inDither = false;
762 public static void initAlbumArtCache() {
764 int id = sService.getMediaMountedCount();
765 if (id != sArtCacheId) {
766 clearAlbumArtCache();
769 } catch (RemoteException e) {
774 public static void clearAlbumArtCache() {
775 synchronized(sArtCache) {
780 public static Drawable getCachedArtwork(Context context, int artIndex, BitmapDrawable defaultArtwork) {
782 synchronized(sArtCache) {
783 d = sArtCache.get(artIndex);
787 final Bitmap icon = defaultArtwork.getBitmap();
788 int w = icon.getWidth();
789 int h = icon.getHeight();
790 Bitmap b = MusicUtils.getArtworkQuick(context, artIndex, w, h);
792 d = new FastBitmapDrawable(b);
793 synchronized(sArtCache) {
794 // the cache may have changed since we checked
795 Drawable value = sArtCache.get(artIndex);
797 sArtCache.put(artIndex, d);
807 // Get album art for specified album. This method will not try to
808 // fall back to getting artwork directly from the file, nor will
809 // it attempt to repair the database.
810 private static Bitmap getArtworkQuick(Context context, int album_id, int w, int h) {
811 // NOTE: There is in fact a 1 pixel border on the right side in the ImageView
812 // used to display this drawable. Take it into account now, so we don't have to
815 ContentResolver res = context.getContentResolver();
816 Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
818 ParcelFileDescriptor fd = null;
820 fd = res.openFileDescriptor(uri, "r");
823 // Compute the closest power-of-two scale factor
824 // and pass that to sBitmapOptionsCache.inSampleSize, which will
825 // result in faster decoding and better quality
826 sBitmapOptionsCache.inJustDecodeBounds = true;
827 BitmapFactory.decodeFileDescriptor(
828 fd.getFileDescriptor(), null, sBitmapOptionsCache);
829 int nextWidth = sBitmapOptionsCache.outWidth >> 1;
830 int nextHeight = sBitmapOptionsCache.outHeight >> 1;
831 while (nextWidth>w && nextHeight>h) {
837 sBitmapOptionsCache.inSampleSize = sampleSize;
838 sBitmapOptionsCache.inJustDecodeBounds = false;
839 Bitmap b = BitmapFactory.decodeFileDescriptor(
840 fd.getFileDescriptor(), null, sBitmapOptionsCache);
843 // finally rescale to exactly the size we need
844 if (sBitmapOptionsCache.outWidth != w || sBitmapOptionsCache.outHeight != h) {
845 Bitmap tmp = Bitmap.createScaledBitmap(b, w, h, true);
846 // Bitmap.createScaledBitmap() can return the same bitmap
847 if (tmp != b) b.recycle();
853 } catch (FileNotFoundException e) {
858 } catch (IOException e) {
865 // Get album art for specified album. You should not pass in the album id
866 // for the "unknown" album here (use -1 instead)
867 public static Bitmap getArtwork(Context context, int album_id) {
870 // This is something that is not in the database, so get the album art directly
872 Bitmap bm = getArtworkFromFile(context, null, -1);
876 return getDefaultArtwork(context);
879 ContentResolver res = context.getContentResolver();
880 Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
882 InputStream in = null;
884 in = res.openInputStream(uri);
885 return BitmapFactory.decodeStream(in, null, sBitmapOptions);
886 } catch (FileNotFoundException ex) {
887 // The album art thumbnail does not actually exist. Maybe the user deleted it, or
888 // maybe it never existed to begin with.
889 Bitmap bm = getArtworkFromFile(context, null, album_id);
891 // Put the newly found artwork in the database.
892 // Note that this shouldn't be done for the "unknown" album,
893 // but if this method is called correctly, that won't happen.
895 // first write it somewhere
896 String file = Environment.getExternalStorageDirectory()
897 + "/albumthumbs/" + String.valueOf(System.currentTimeMillis());
898 if (ensureFileExists(file)) {
900 OutputStream outstream = new FileOutputStream(file);
901 if (bm.getConfig() == null) {
902 bm = bm.copy(Bitmap.Config.RGB_565, false);
904 return getDefaultArtwork(context);
907 boolean success = bm.compress(Bitmap.CompressFormat.JPEG, 75, outstream);
910 ContentValues values = new ContentValues();
911 values.put("album_id", album_id);
912 values.put("_data", file);
913 Uri newuri = res.insert(sArtworkUri, values);
914 if (newuri == null) {
915 // Failed to insert in to the database. The most likely
916 // cause of this is that the item already existed in the
917 // database, and the most likely cause of that is that
918 // the album was scanned before, but the user deleted the
919 // album art from the sd card.
920 // We can ignore that case here, since the media provider
921 // will regenerate the album art for those entries when
927 File f = new File(file);
930 } catch (FileNotFoundException e) {
931 Log.e(TAG, "error creating file", e);
932 } catch (IOException e) {
933 Log.e(TAG, "error creating file", e);
937 bm = getDefaultArtwork(context);
945 } catch (IOException ex) {
953 // copied from MediaProvider
954 private static boolean ensureFileExists(String path) {
955 File file = new File(path);
959 // we will not attempt to create the first directory in the path
960 // (for example, do not create /sdcard if the SD card is not mounted)
961 int secondSlash = path.indexOf('/', 1);
962 if (secondSlash < 1) return false;
963 String directoryPath = path.substring(0, secondSlash);
964 File directory = new File(directoryPath);
965 if (!directory.exists())
967 file.getParentFile().mkdirs();
969 return file.createNewFile();
970 } catch(IOException ioe) {
971 Log.d(TAG, "File creation failed for " + path);
977 // get album art for specified file
978 private static final String sExternalMediaUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString();
979 private static Bitmap getArtworkFromFile(Context context, Uri uri, int albumid) {
984 if (sArtId == albumid) {
985 //Log.i("@@@@@@ ", "reusing cached data", new Exception());
986 if (mCachedBit != null) {
991 // try reading embedded artwork
994 int curalbum = sService.getAlbumId();
995 if (curalbum == albumid || albumid < 0) {
996 path = sService.getPath();
998 uri = Uri.parse(path);
1001 } catch (RemoteException ex) {
1003 } catch (NullPointerException ex) {
1009 Cursor c = query(context,MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
1010 new String[] { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM },
1011 MediaStore.Audio.Media.ALBUM_ID + "=?", new String [] {String.valueOf(albumid)},
1015 if (!c.isAfterLast()) {
1016 int trackid = c.getInt(0);
1017 uri = ContentUris.withAppendedId(
1018 MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, trackid);
1020 if (c.getString(1).equals(MediaFile.UNKNOWN_STRING)) {
1028 MediaScanner scanner = new MediaScanner(context);
1029 ParcelFileDescriptor pfd = null;
1031 pfd = context.getContentResolver().openFileDescriptor(uri, "r");
1033 FileDescriptor fd = pfd.getFileDescriptor();
1034 art = scanner.extractAlbumArt(fd);
1036 } catch (IOException ex) {
1037 } catch (SecurityException ex) {
1043 } catch (IOException ex) {
1048 // if no embedded art exists, look for AlbumArt.jpg in same directory as the media file
1049 if (art == null && path != null) {
1050 if (path.startsWith(sExternalMediaUri)) {
1051 // get the real path
1052 Cursor c = query(context,Uri.parse(path),
1053 new String[] { MediaStore.Audio.Media.DATA},
1057 if (!c.isAfterLast()) {
1058 path = c.getString(0);
1063 int lastSlash = path.lastIndexOf('/');
1064 if (lastSlash > 0) {
1065 String artPath = path.substring(0, lastSlash + 1) + "AlbumArt.jpg";
1066 File file = new File(artPath);
1067 if (file.exists()) {
1068 art = new byte[(int)file.length()];
1069 FileInputStream stream = null;
1071 stream = new FileInputStream(file);
1073 } catch (IOException ex) {
1077 if (stream != null) {
1080 } catch (IOException ex) {
1084 // TODO: try getting album art from the web
1091 // get the size of the bitmap
1092 BitmapFactory.Options opts = new BitmapFactory.Options();
1093 opts.inJustDecodeBounds = true;
1094 opts.inSampleSize = 1;
1095 BitmapFactory.decodeByteArray(art, 0, art.length, opts);
1097 // request a reasonably sized output image
1098 // TODO: don't hardcode the size
1099 while (opts.outHeight > 320 || opts.outWidth > 320) {
1100 opts.outHeight /= 2;
1102 opts.inSampleSize *= 2;
1105 // get the image for real now
1106 opts.inJustDecodeBounds = false;
1107 bm = BitmapFactory.decodeByteArray(art, 0, art.length, opts);
1108 if (albumid != -1) {
1113 } catch (Exception e) {
1119 private static Bitmap getDefaultArtwork(Context context) {
1120 BitmapFactory.Options opts = new BitmapFactory.Options();
1121 opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
1122 return BitmapFactory.decodeStream(
1123 context.getResources().openRawResource(R.drawable.albumart_mp_unknown), null, opts);
1126 static int getIntPref(Context context, String name, int def) {
1127 SharedPreferences prefs =
1128 context.getSharedPreferences("com.android.music", Context.MODE_PRIVATE);
1129 return prefs.getInt(name, def);
1132 static void setIntPref(Context context, String name, int value) {
1133 SharedPreferences prefs =
1134 context.getSharedPreferences("com.android.music", Context.MODE_PRIVATE);
1135 Editor ed = prefs.edit();
1136 ed.putInt(name, value);
1140 static void setRingtone(Context context, long id) {
1141 ContentResolver resolver = context.getContentResolver();
1142 // Set the flag in the database to mark this as a ringtone
1143 Uri ringUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
1145 ContentValues values = new ContentValues(2);
1146 values.put(MediaStore.Audio.Media.IS_RINGTONE, "1");
1147 values.put(MediaStore.Audio.Media.IS_ALARM, "1");
1148 resolver.update(ringUri, values, null, null);
1149 } catch (UnsupportedOperationException ex) {
1150 // most likely the card just got unmounted
1151 Log.e(TAG, "couldn't set ringtone flag for id " + id);
1155 String[] cols = new String[] {
1156 MediaStore.Audio.Media._ID,
1157 MediaStore.Audio.Media.DATA,
1158 MediaStore.Audio.Media.TITLE
1161 String where = MediaStore.Audio.Media._ID + "=" + id;
1162 Cursor cursor = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
1163 cols, where , null, null);
1165 if (cursor != null && cursor.getCount() == 1) {
1166 // Set the system setting to make this the current ringtone
1167 cursor.moveToFirst();
1168 Settings.System.putString(resolver, Settings.System.RINGTONE, ringUri.toString());
1169 String message = context.getString(R.string.ringtone_set, cursor.getString(2));
1170 Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
1173 if (cursor != null) {