OSDN Git Service

am c36be694: Import new translations
[android-x86/packages-apps-Music.git] / src / com / android / music / MusicUtils.java
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.android.music;
18
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;
50
51 import java.io.File;
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;
60
61 public class MusicUtils {
62
63     private static final String TAG = "MusicUtils";
64
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
80     }
81
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
86         
87         StringBuilder songs_albums = new StringBuilder();
88
89         Resources r = context.getResources();
90         if (isUnknown) {
91             if (numsongs == 1) {
92                 songs_albums.append(context.getString(R.string.onesong));
93             } else {
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);
98             }
99         } else {
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));
105         }
106         return songs_albums.toString();
107     }
108
109     /**
110      * This is now only used for the query screen
111      */
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
119         
120         StringBuilder songs_albums = new StringBuilder();
121
122         if (numsongs == 1) {
123             songs_albums.append(context.getString(R.string.onesong));
124         } else {
125             Resources r = context.getResources();
126             if (! isUnknown) {
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));
132             }
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);
137         }
138         return songs_albums.toString();
139     }
140     
141     public static IMediaPlaybackService sService = null;
142     private static HashMap<Context, ServiceBinder> sConnectionMap = new HashMap<Context, ServiceBinder>();
143
144     public static boolean bindToService(Context context) {
145         return bindToService(context, null);
146     }
147
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);
154     }
155     
156     public static void unbindFromService(Context context) {
157         ServiceBinder sb = (ServiceBinder) sConnectionMap.remove(context);
158         if (sb == null) {
159             Log.e("MusicUtils", "Trying to unbind for unknown Context");
160             return;
161         }
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
166             sService = null;
167         }
168     }
169
170     private static class ServiceBinder implements ServiceConnection {
171         ServiceConnection mCallback;
172         ServiceBinder(ServiceConnection callback) {
173             mCallback = callback;
174         }
175         
176         public void onServiceConnected(ComponentName className, android.os.IBinder service) {
177             sService = IMediaPlaybackService.Stub.asInterface(service);
178             initAlbumArtCache();
179             if (mCallback != null) {
180                 mCallback.onServiceConnected(className, service);
181             }
182         }
183         
184         public void onServiceDisconnected(ComponentName className) {
185             if (mCallback != null) {
186                 mCallback.onServiceDisconnected(className);
187             }
188             sService = null;
189         }
190     }
191     
192     public static long getCurrentAlbumId() {
193         if (sService != null) {
194             try {
195                 return sService.getAlbumId();
196             } catch (RemoteException ex) {
197             }
198         }
199         return -1;
200     }
201
202     public static long getCurrentArtistId() {
203         if (MusicUtils.sService != null) {
204             try {
205                 return sService.getArtistId();
206             } catch (RemoteException ex) {
207             }
208         }
209         return -1;
210     }
211
212     public static long getCurrentAudioId() {
213         if (MusicUtils.sService != null) {
214             try {
215                 return sService.getAudioId();
216             } catch (RemoteException ex) {
217             }
218         }
219         return -1;
220     }
221     
222     public static int getCurrentShuffleMode() {
223         int mode = MediaPlaybackService.SHUFFLE_NONE;
224         if (sService != null) {
225             try {
226                 mode = sService.getShuffleMode();
227             } catch (RemoteException ex) {
228             }
229         }
230         return mode;
231     }
232     
233     /*
234      * Returns true if a file is currently opened for playback (regardless
235      * of whether it's playing or paused).
236      */
237     public static boolean isMusicLoaded() {
238         if (MusicUtils.sService != null) {
239             try {
240                 return sService.getPath() != null;
241             } catch (RemoteException ex) {
242             }
243         }
244         return false;
245     }
246
247     private final static long [] sEmptyList = new long[0];
248     
249     public static long [] getSongListForCursor(Cursor cursor) {
250         if (cursor == null) {
251             return sEmptyList;
252         }
253         int len = cursor.getCount();
254         long [] list = new long[len];
255         cursor.moveToFirst();
256         int colidx = -1;
257         try {
258             colidx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members.AUDIO_ID);
259         } catch (IllegalArgumentException ex) {
260             colidx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
261         }
262         for (int i = 0; i < len; i++) {
263             list[i] = cursor.getLong(colidx);
264             cursor.moveToNext();
265         }
266         return list;
267     }
268
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,
274                 ccols, where, null,
275                 MediaStore.Audio.Media.ALBUM_KEY + ","  + MediaStore.Audio.Media.TRACK);
276         
277         if (cursor != null) {
278             long [] list = getSongListForCursor(cursor);
279             cursor.close();
280             return list;
281         }
282         return sEmptyList;
283     }
284
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);
291
292         if (cursor != null) {
293             long [] list = getSongListForCursor(cursor);
294             cursor.close();
295             return list;
296         }
297         return sEmptyList;
298     }
299
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);
304         
305         if (cursor != null) {
306             long [] list = getSongListForCursor(cursor);
307             cursor.close();
308             return list;
309         }
310         return sEmptyList;
311     }
312     
313     public static void playPlaylist(Context context, long plid) {
314         long [] list = getSongListForPlaylist(context, plid);
315         if (list != null) {
316             playAll(context, list, -1, false);
317         }
318     }
319
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",
323                 null, null);
324         try {
325             if (c == null || c.getCount() == 0) {
326                 return null;
327             }
328             int len = c.getCount();
329             long [] list = new long[len];
330             for (int i = 0; i < len; i++) {
331                 c.moveToNext();
332                 list[i] = c.getLong(0);
333             }
334
335             return list;
336         } finally {
337             if (c != null) {
338                 c.close();
339             }
340         }
341     }
342
343     /**
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
349      * selected.
350      * @param context The context to use for creating the menu items
351      * @param sub The submenu to add the items to.
352      */
353     public static void makePlaylistMenu(Context context, SubMenu sub) {
354         String[] cols = new String[] {
355                 MediaStore.Audio.Playlists._ID,
356                 MediaStore.Audio.Playlists.NAME
357         };
358         ContentResolver resolver = context.getContentResolver();
359         if (resolver == null) {
360             System.out.println("resolver = null");
361         } else {
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);
366             sub.clear();
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);
371                 cur.moveToFirst();
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);
377 //                    } else {
378                         sub.add(1, Defs.PLAYLIST_SELECTED, 0, cur.getString(1)).setIntent(intent);
379 //                    }
380                     cur.moveToNext();
381                 }
382             }
383             if (cur != null) {
384                 cur.close();
385             }
386         }
387     }
388
389     public static void clearPlaylist(Context context, int plid) {
390         
391         Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", plid);
392         context.getContentResolver().delete(uri, null, null);
393         return;
394     }
395     
396     public static void deleteTracks(Context context, long [] list) {
397         
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) {
405                 where.append(",");
406             }
407         }
408         where.append(")");
409         Cursor c = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cols,
410                 where.toString(), null, null);
411
412         if (c != null) {
413
414             // step 1: remove selected tracks from the current playlist, as well
415             // as from the album art cache
416             try {
417                 c.moveToFirst();
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);
426                     }
427                     c.moveToNext();
428                 }
429             } catch (RemoteException ex) {
430             }
431
432             // step 2: remove selected tracks from the database
433             context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, where.toString(), null);
434
435             // step 3: remove files from card
436             c.moveToFirst();
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
441                     if (!f.delete()) {
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);
445                     }
446                     c.moveToNext();
447                 } catch (SecurityException ex) {
448                     c.moveToNext();
449                 }
450             }
451             c.close();
452         }
453
454         String message = context.getResources().getQuantityString(
455                 R.plurals.NNNtracksdeleted, list.length, Integer.valueOf(list.length));
456         
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);
461     }
462     
463     public static void addToCurrentPlaylist(Context context, long [] list) {
464         if (sService == null) {
465             return;
466         }
467         try {
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) {
473         }
474     }
475     
476     public static void addToPlaylist(Context context, long [] ids, long playlistid) {
477         if (ids == null) {
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");
481         } else {
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[] {
488                     "count(*)"
489             };
490             Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
491             Cursor cur = resolver.query(uri, cols, null, null, null);
492             cur.moveToFirst();
493             int base = cur.getInt(0);
494             cur.close();
495
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]);
500             }
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;
506         }
507     }
508
509     public static Cursor query(Context context, Uri uri, String[] projection,
510             String selection, String[] selectionArgs, String sortOrder) {
511         try {
512             ContentResolver resolver = context.getContentResolver();
513             if (resolver == null) {
514                 return null;
515             }
516             return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
517          } catch (UnsupportedOperationException ex) {
518             return null;
519         }
520         
521     }
522     
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));
531             }
532             cursor.close(); 
533         } 
534
535         return result;
536     }
537     
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);
544
545             a.getWindow().setFeatureInt(
546                     Window.FEATURE_INDETERMINATE_PROGRESS,
547                     Window.PROGRESS_VISIBILITY_ON);
548         } else {
549             // stop the progress spinner
550             a.getWindow().setFeatureInt(
551                     Window.FEATURE_INDETERMINATE_PROGRESS,
552                     Window.PROGRESS_VISIBILITY_OFF);
553         }
554     }
555     
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;
560         
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
572             // will happen).
573             a.setTitle("");
574             Intent intent = new Intent();
575             intent.setClass(a, ScanningProgress.class);
576             a.startActivityForResult(intent, Defs.SCAN_DONE);
577         } else {
578             Log.d(TAG, "sd card: " + status);
579         }
580
581         a.setTitle(title);
582         View v = a.findViewById(R.id.sd_message);
583         if (v != null) {
584             v.setVisibility(View.VISIBLE);
585         }
586         v = a.findViewById(R.id.sd_icon);
587         if (v != null) {
588             v.setVisibility(View.VISIBLE);
589         }
590         v = a.findViewById(android.R.id.list);
591         if (v != null) {
592             v.setVisibility(View.GONE);
593         }
594         TextView tv = (TextView) a.findViewById(R.id.sd_message);
595         tv.setText(message);
596     }
597     
598     public static void hideDatabaseError(Activity a) {
599         View v = a.findViewById(R.id.sd_message);
600         if (v != null) {
601             v.setVisibility(View.GONE);
602         }
603         v = a.findViewById(R.id.sd_icon);
604         if (v != null) {
605             v.setVisibility(View.GONE);
606         }
607         v = a.findViewById(android.R.id.list);
608         if (v != null) {
609             v.setVisibility(View.VISIBLE);
610         }
611     }
612
613     static protected Uri getContentURIForPath(String path) {
614         return Uri.fromFile(new File(path));
615     }
616
617     
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
621      *  makeTimeString().
622      *  This Formatter/StringBuilder are also used by makeAlbumSongsLabel()
623      */
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];
627
628     public static String makeTimeString(Context context, long secs) {
629         String durationformat = context.getString(R.string.durationformat);
630         
631         /* Provide multiple arguments so the format can be changed easily
632          * by modifying the xml.
633          */
634         sFormatBuilder.setLength(0);
635
636         final Object[] timeArgs = sTimeArgs;
637         timeArgs[0] = secs / 3600;
638         timeArgs[1] = secs / 60;
639         timeArgs[2] = (secs / 60) % 60;
640         timeArgs[3] = secs;
641         timeArgs[4] = secs % 60;
642
643         return sFormatter.format(durationformat, timeArgs).toString();
644     }
645     
646     public static void shuffleAll(Context context, Cursor cursor) {
647         playAll(context, cursor, 0, true);
648     }
649
650     public static void playAll(Context context, Cursor cursor) {
651         playAll(context, cursor, 0, false);
652     }
653     
654     public static void playAll(Context context, Cursor cursor, int position) {
655         playAll(context, cursor, position, false);
656     }
657     
658     public static void playAll(Context context, long [] list, int position) {
659         playAll(context, list, position, false);
660     }
661     
662     private static void playAll(Context context, Cursor cursor, int position, boolean force_shuffle) {
663     
664         long [] list = getSongListForCursor(cursor);
665         playAll(context, list, position, force_shuffle);
666     }
667     
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();
674             return;
675         }
676         try {
677             if (force_shuffle) {
678                 sService.setShuffleMode(MediaPlaybackService.SHUFFLE_NORMAL);
679             }
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
689                     sService.play();
690                     return; // the 'finally' block will still run
691                 }
692             }
693             if (position < 0) {
694                 position = 0;
695             }
696             sService.open(list, force_shuffle ? -1 : position);
697             sService.play();
698         } catch (RemoteException ex) {
699         } finally {
700             Intent intent = new Intent("com.android.music.PLAYBACK_VIEWER")
701                 .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
702             context.startActivity(intent);
703         }
704     }
705     
706     public static void clearQueue() {
707         try {
708             sService.removeTracks(0, Integer.MAX_VALUE);
709         } catch (RemoteException ex) {
710         }
711     }
712     
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) {
718             mBitmap = b;
719         }
720         @Override
721         public void draw(Canvas canvas) {
722             canvas.drawBitmap(mBitmap, 0, 0, null);
723         }
724         @Override
725         public int getOpacity() {
726             return PixelFormat.OPAQUE;
727         }
728         @Override
729         public void setAlpha(int alpha) {
730         }
731         @Override
732         public void setColorFilter(ColorFilter cf) {
733         }
734     }
735     
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;
743     
744     static {
745         // for the cache, 
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;
750
751         sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
752         sBitmapOptions.inDither = false;
753     }
754
755     public static void initAlbumArtCache() {
756         try {
757             int id = sService.getMediaMountedCount();
758             if (id != sArtCacheId) {
759                 clearAlbumArtCache();
760                 sArtCacheId = id; 
761             }
762         } catch (RemoteException e) {
763             e.printStackTrace();
764         }
765     }
766
767     public static void clearAlbumArtCache() {
768         synchronized(sArtCache) {
769             sArtCache.clear();
770         }
771     }
772     
773     public static Drawable getCachedArtwork(Context context, long artIndex, BitmapDrawable defaultArtwork) {
774         Drawable d = null;
775         synchronized(sArtCache) {
776             d = sArtCache.get(artIndex);
777         }
778         if (d == null) {
779             d = defaultArtwork;
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);
784             if (b != null) {
785                 d = new FastBitmapDrawable(b);
786                 synchronized(sArtCache) {
787                     // the cache may have changed since we checked
788                     Drawable value = sArtCache.get(artIndex);
789                     if (value == null) {
790                         sArtCache.put(artIndex, d);
791                     } else {
792                         d = value;
793                     }
794                 }
795             }
796         }
797         return d;
798     }
799
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
806         // scale later.
807         w -= 1;
808         ContentResolver res = context.getContentResolver();
809         Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
810         if (uri != null) {
811             ParcelFileDescriptor fd = null;
812             try {
813                 fd = res.openFileDescriptor(uri, "r");
814                 int sampleSize = 1;
815                 
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) {
825                     sampleSize <<= 1;
826                     nextWidth >>= 1;
827                     nextHeight >>= 1;
828                 }
829
830                 sBitmapOptionsCache.inSampleSize = sampleSize;
831                 sBitmapOptionsCache.inJustDecodeBounds = false;
832                 Bitmap b = BitmapFactory.decodeFileDescriptor(
833                         fd.getFileDescriptor(), null, sBitmapOptionsCache);
834
835                 if (b != null) {
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();
841                         b = tmp;
842                     }
843                 }
844                 
845                 return b;
846             } catch (FileNotFoundException e) {
847             } finally {
848                 try {
849                     if (fd != null)
850                         fd.close();
851                 } catch (IOException e) {
852                 }
853             }
854         }
855         return null;
856     }
857     
858     /** Get album art for specified album. You should not pass in the album id
859      * for the "unknown" album here (use -1 instead)
860      */
861     public static Bitmap getArtwork(Context context, long song_id, long album_id) {
862
863         if (album_id < 0) {
864             // This is something that is not in the database, so get the album art directly
865             // from the file.
866             if (song_id >= 0) {
867                 Bitmap bm = getArtworkFromFile(context, song_id, -1);
868                 if (bm != null) {
869                     return bm;
870                 }
871             }
872             return getDefaultArtwork(context);
873         }
874
875         ContentResolver res = context.getContentResolver();
876         Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
877         if (uri != null) {
878             InputStream in = null;
879             try {
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);
886                 if (bm != null) {
887                     if (bm.getConfig() == null) {
888                         bm = bm.copy(Bitmap.Config.RGB_565, false);
889                         if (bm == null) {
890                             return getDefaultArtwork(context);
891                         }
892                     }
893                 } else {
894                     bm = getDefaultArtwork(context);
895                 }
896                 return bm;
897             } finally {
898                 try {
899                     if (in != null) {
900                         in.close();
901                     }
902                 } catch (IOException ex) {
903                 }
904             }
905         }
906         
907         return null;
908     }
909     
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) {
913         Bitmap bm = null;
914         byte [] art = null;
915         String path = null;
916
917         if (albumid < 0 && songid < 0) {
918             throw new IllegalArgumentException("Must specify an album or a song id");
919         }
920
921         try {
922             if (albumid < 0) {
923                 Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart");
924                 ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
925                 if (pfd != null) {
926                     FileDescriptor fd = pfd.getFileDescriptor();
927                     bm = BitmapFactory.decodeFileDescriptor(fd);
928                 }
929             } else {
930                 Uri uri = ContentUris.withAppendedId(sArtworkUri, albumid);
931                 ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
932                 if (pfd != null) {
933                     FileDescriptor fd = pfd.getFileDescriptor();
934                     bm = BitmapFactory.decodeFileDescriptor(fd);
935                 }
936             }
937         } catch (FileNotFoundException ex) {
938             //
939         }
940         if (bm != null) {
941             mCachedBit = bm;
942         }
943         return bm;
944     }
945     
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);
951     }
952     
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);
957     }
958     
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);
964         ed.commit();
965     }
966
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);
971         try {
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);
979             return;
980         }
981
982         String[] cols = new String[] {
983                 MediaStore.Audio.Media._ID,
984                 MediaStore.Audio.Media.DATA,
985                 MediaStore.Audio.Media.TITLE
986         };
987
988         String where = MediaStore.Audio.Media._ID + "=" + id;
989         Cursor cursor = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
990                 cols, where , null, null);
991         try {
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();
998             }
999         } finally {
1000             if (cursor != null) {
1001                 cursor.close();
1002             }
1003         }
1004     }
1005 }