MusicPicker.java revision c234eed2feb83baa478c6fde1c537227b92ce674
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 17package com.android.music; 18 19import android.app.ListActivity; 20import android.content.AsyncQueryHandler; 21import android.content.ContentUris; 22import android.content.Context; 23import android.content.Intent; 24import android.database.CharArrayBuffer; 25import android.database.Cursor; 26import android.media.AudioManager; 27import android.media.MediaPlayer; 28import android.media.RingtoneManager; 29import android.net.Uri; 30import android.os.Bundle; 31import android.os.Parcelable; 32import android.provider.MediaStore; 33import android.util.Log; 34import android.view.Menu; 35import android.view.MenuItem; 36import android.view.View; 37import android.view.ViewGroup; 38import android.view.Window; 39import android.view.animation.AnimationUtils; 40import android.widget.ImageView; 41import android.widget.ListView; 42import android.widget.RadioButton; 43import android.widget.SectionIndexer; 44import android.widget.SimpleCursorAdapter; 45import android.widget.TextView; 46 47import java.io.IOException; 48import java.text.Collator; 49import java.util.Formatter; 50import java.util.Locale; 51 52/** 53 * Activity allowing the user to select a music track on the device, and 54 * return it to its caller. The music picker user interface is fairly 55 * extensive, providing information about each track like the music 56 * application (title, author, album, duration), as well as the ability to 57 * previous tracks and sort them in different orders. 58 * 59 * <p>This class also illustrates how you can load data from a content 60 * provider asynchronously, providing a good UI while doing so, perform 61 * indexing of the content for use inside of a {@link FastScrollView}, and 62 * perform filtering of the data as the user presses keys. 63 */ 64public class MusicPicker extends ListActivity 65 implements View.OnClickListener, MediaPlayer.OnCompletionListener, 66 MusicUtils.Defs { 67 static final boolean DBG = false; 68 static final String TAG = "MusicPicker"; 69 70 /** Holds the previous state of the list, to restore after the async 71 * query has completed. */ 72 static final String LIST_STATE_KEY = "liststate"; 73 /** Remember whether the list last had focus for restoring its state. */ 74 static final String FOCUS_KEY = "focused"; 75 /** Remember the last ordering mode for restoring state. */ 76 static final String SORT_MODE_KEY = "sortMode"; 77 78 /** Arbitrary number, doesn't matter since we only do one query type. */ 79 static final int MY_QUERY_TOKEN = 42; 80 81 /** Menu item to sort the music list by track title. */ 82 static final int TRACK_MENU = Menu.FIRST; 83 /** Menu item to sort the music list by album title. */ 84 static final int ALBUM_MENU = Menu.FIRST+1; 85 /** Menu item to sort the music list by artist name. */ 86 static final int ARTIST_MENU = Menu.FIRST+2; 87 88 /** These are the columns in the music cursor that we are interested in. */ 89 static final String[] CURSOR_COLS = new String[] { 90 MediaStore.Audio.Media._ID, 91 MediaStore.Audio.Media.TITLE, 92 MediaStore.Audio.Media.TITLE_KEY, 93 MediaStore.Audio.Media.DATA, 94 MediaStore.Audio.Media.ALBUM, 95 MediaStore.Audio.Media.ARTIST, 96 MediaStore.Audio.Media.ARTIST_ID, 97 MediaStore.Audio.Media.DURATION, 98 MediaStore.Audio.Media.TRACK 99 }; 100 101 /** Formatting optimization to avoid creating many temporary objects. */ 102 static StringBuilder sFormatBuilder = new StringBuilder(); 103 /** Formatting optimization to avoid creating many temporary objects. */ 104 static Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault()); 105 /** Formatting optimization to avoid creating many temporary objects. */ 106 static final Object[] sTimeArgs = new Object[5]; 107 108 /** Uri to the directory of all music being displayed. */ 109 Uri mBaseUri; 110 111 /** This is the adapter used to display all of the tracks. */ 112 TrackListAdapter mAdapter; 113 /** Our instance of QueryHandler used to perform async background queries. */ 114 QueryHandler mQueryHandler; 115 116 /** Used to keep track of the last scroll state of the list. */ 117 Parcelable mListState = null; 118 /** Used to keep track of whether the list last had focus. */ 119 boolean mListHasFocus; 120 121 /** The current cursor on the music that is being displayed. */ 122 Cursor mCursor; 123 /** The actual sort order the user has selected. */ 124 int mSortMode = -1; 125 /** SQL order by string describing the currently selected sort order. */ 126 String mSortOrder; 127 128 /** Container of the in-screen progress indicator, to be able to hide it 129 * when done loading the initial cursor. */ 130 View mProgressContainer; 131 /** Container of the list view hierarchy, to be able to show it when done 132 * loading the initial cursor. */ 133 View mListContainer; 134 /** Set to true when the list view has been shown for the first time. */ 135 boolean mListShown; 136 137 /** View holding the okay button. */ 138 View mOkayButton; 139 /** View holding the cancel button. */ 140 View mCancelButton; 141 142 /** Which track row ID the user has last selected. */ 143 long mSelectedId = -1; 144 /** Completel Uri that the user has last selected. */ 145 Uri mSelectedUri; 146 147 /** If >= 0, we are currently playing a track for preview, and this is its 148 * row ID. */ 149 long mPlayingId = -1; 150 151 /** This is used for playing previews of the music files. */ 152 MediaPlayer mMediaPlayer; 153 154 /** 155 * A special implementation of SimpleCursorAdapter that knows how to bind 156 * our cursor data to our list item structure, and takes care of other 157 * advanced features such as indexing and filtering. 158 */ 159 class TrackListAdapter extends SimpleCursorAdapter 160 implements SectionIndexer { 161 final ListView mListView; 162 163 private final StringBuilder mBuilder = new StringBuilder(); 164 private final String mUnknownArtist; 165 private final String mUnknownAlbum; 166 167 private int mIdIdx; 168 private int mTitleIdx; 169 private int mArtistIdx; 170 private int mAlbumIdx; 171 private int mDurationIdx; 172 173 private boolean mLoading = true; 174 private int mIndexerSortMode; 175 private MusicAlphabetIndexer mIndexer; 176 177 class ViewHolder { 178 TextView line1; 179 TextView line2; 180 TextView duration; 181 RadioButton radio; 182 ImageView play_indicator; 183 CharArrayBuffer buffer1; 184 char [] buffer2; 185 } 186 187 TrackListAdapter(Context context, ListView listView, int layout, 188 String[] from, int[] to) { 189 super(context, layout, null, from, to); 190 mListView = listView; 191 mUnknownArtist = context.getString(R.string.unknown_artist_name); 192 mUnknownAlbum = context.getString(R.string.unknown_album_name); 193 } 194 195 /** 196 * The mLoading flag is set while we are performing a background 197 * query, to avoid displaying the "No music" empty view during 198 * this time. 199 */ 200 public void setLoading(boolean loading) { 201 mLoading = loading; 202 } 203 204 @Override 205 public boolean isEmpty() { 206 if (mLoading) { 207 // We don't want the empty state to show when loading. 208 return false; 209 } else { 210 return super.isEmpty(); 211 } 212 } 213 214 @Override 215 public View newView(Context context, Cursor cursor, ViewGroup parent) { 216 View v = super.newView(context, cursor, parent); 217 ViewHolder vh = new ViewHolder(); 218 vh.line1 = (TextView) v.findViewById(R.id.line1); 219 vh.line2 = (TextView) v.findViewById(R.id.line2); 220 vh.duration = (TextView) v.findViewById(R.id.duration); 221 vh.radio = (RadioButton) v.findViewById(R.id.radio); 222 vh.play_indicator = (ImageView) v.findViewById(R.id.play_indicator); 223 vh.buffer1 = new CharArrayBuffer(100); 224 vh.buffer2 = new char[200]; 225 v.setTag(vh); 226 return v; 227 } 228 229 @Override 230 public void bindView(View view, Context context, Cursor cursor) { 231 ViewHolder vh = (ViewHolder) view.getTag(); 232 233 cursor.copyStringToBuffer(mTitleIdx, vh.buffer1); 234 vh.line1.setText(vh.buffer1.data, 0, vh.buffer1.sizeCopied); 235 236 int secs = cursor.getInt(mDurationIdx) / 1000; 237 if (secs == 0) { 238 vh.duration.setText(""); 239 } else { 240 vh.duration.setText(MusicUtils.makeTimeString(context, secs)); 241 } 242 243 final StringBuilder builder = mBuilder; 244 builder.delete(0, builder.length()); 245 246 String name = cursor.getString(mAlbumIdx); 247 if (name == null || name.equals("<unknown>")) { 248 builder.append(mUnknownAlbum); 249 } else { 250 builder.append(name); 251 } 252 builder.append('\n'); 253 name = cursor.getString(mArtistIdx); 254 if (name == null || name.equals("<unknown>")) { 255 builder.append(mUnknownArtist); 256 } else { 257 builder.append(name); 258 } 259 int len = builder.length(); 260 if (vh.buffer2.length < len) { 261 vh.buffer2 = new char[len]; 262 } 263 builder.getChars(0, len, vh.buffer2, 0); 264 vh.line2.setText(vh.buffer2, 0, len); 265 266 // Update the checkbox of the item, based on which the user last 267 // selected. Note that doing it this way means we must have the 268 // list view update all of its items when the selected item 269 // changes. 270 final long id = cursor.getLong(mIdIdx); 271 vh.radio.setChecked(id == mSelectedId); 272 if (DBG) Log.v(TAG, "Binding id=" + id + " sel=" + mSelectedId 273 + " playing=" + mPlayingId + " cursor=" + cursor); 274 275 // Likewise, display the "now playing" icon if this item is 276 // currently being previewed for the user. 277 ImageView iv = vh.play_indicator; 278 if (id == mPlayingId) { 279 iv.setImageResource(R.drawable.indicator_ic_mp_playing_list); 280 iv.setVisibility(View.VISIBLE); 281 } else { 282 iv.setVisibility(View.GONE); 283 } 284 } 285 286 /** 287 * This method is called whenever we receive a new cursor due to 288 * an async query, and must take care of plugging the new one in 289 * to the adapter. 290 */ 291 @Override 292 public void changeCursor(Cursor cursor) { 293 super.changeCursor(cursor); 294 if (DBG) Log.v(TAG, "Setting cursor to: " + cursor 295 + " from: " + MusicPicker.this.mCursor); 296 297 MusicPicker.this.mCursor = cursor; 298 299 if (cursor != null) { 300 // Retrieve indices of the various columns we are interested in. 301 mIdIdx = cursor.getColumnIndex(MediaStore.Audio.Media._ID); 302 mTitleIdx = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE); 303 mArtistIdx = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST); 304 mAlbumIdx = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM); 305 mDurationIdx = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION); 306 307 // If the sort mode has changed, or we haven't yet created an 308 // indexer one, then create a new one that is indexing the 309 // appropriate column based on the sort mode. 310 if (mIndexerSortMode != mSortMode || mIndexer == null) { 311 mIndexerSortMode = mSortMode; 312 int idx = mTitleIdx; 313 switch (mIndexerSortMode) { 314 case ARTIST_MENU: 315 idx = mArtistIdx; 316 break; 317 case ALBUM_MENU: 318 idx = mAlbumIdx; 319 break; 320 } 321 mIndexer = new MusicAlphabetIndexer(cursor, idx, 322 getResources().getString(R.string.fast_scroll_alphabet)); 323 324 // If we have a valid indexer, but the cursor has changed since 325 // its last use, then point it to the current cursor. 326 } else { 327 mIndexer.setCursor(cursor); 328 } 329 } 330 331 // Ensure that the list is shown (and initial progress indicator 332 // hidden) in case this is the first cursor we have gotten. 333 makeListShown(); 334 } 335 336 /** 337 * This method is called from a background thread by the list view 338 * when the user has typed a letter that should result in a filtering 339 * of the displayed items. It returns a Cursor, when will then be 340 * handed to changeCursor. 341 */ 342 @Override 343 public Cursor runQueryOnBackgroundThread(CharSequence constraint) { 344 if (DBG) Log.v(TAG, "Getting new cursor..."); 345 return doQuery(true, constraint.toString()); 346 } 347 348 public int getPositionForSection(int section) { 349 Cursor cursor = getCursor(); 350 if (cursor == null) { 351 // No cursor, the section doesn't exist so just return 0 352 return 0; 353 } 354 355 return mIndexer.getPositionForSection(section); 356 } 357 358 public int getSectionForPosition(int position) { 359 return 0; 360 } 361 362 public Object[] getSections() { 363 if (mIndexer != null) { 364 return mIndexer.getSections(); 365 } 366 return null; 367 } 368 } 369 370 /** 371 * This is our specialization of AsyncQueryHandler applies new cursors 372 * to our state as they become available. 373 */ 374 private final class QueryHandler extends AsyncQueryHandler { 375 public QueryHandler(Context context) { 376 super(context.getContentResolver()); 377 } 378 379 @Override 380 protected void onQueryComplete(int token, Object cookie, Cursor cursor) { 381 if (!isFinishing()) { 382 // Update the adapter: we are no longer loading, and have 383 // a new cursor for it. 384 mAdapter.setLoading(false); 385 mAdapter.changeCursor(cursor); 386 setProgressBarIndeterminateVisibility(false); 387 388 // Now that the cursor is populated again, it's possible to restore the list state 389 if (mListState != null) { 390 getListView().onRestoreInstanceState(mListState); 391 if (mListHasFocus) { 392 getListView().requestFocus(); 393 } 394 mListHasFocus = false; 395 mListState = null; 396 } 397 } else { 398 cursor.close(); 399 } 400 } 401 } 402 403 /** Called when the activity is first created. */ 404 @Override 405 public void onCreate(Bundle icicle) { 406 super.onCreate(icicle); 407 408 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); 409 410 int sortMode = TRACK_MENU; 411 if (icicle == null) { 412 mSelectedUri = getIntent().getParcelableExtra( 413 RingtoneManager.EXTRA_RINGTONE_EXISTING_URI); 414 } else { 415 mSelectedUri = (Uri)icicle.getParcelable( 416 RingtoneManager.EXTRA_RINGTONE_EXISTING_URI); 417 // Retrieve list state. This will be applied after the 418 // QueryHandler has run 419 mListState = icicle.getParcelable(LIST_STATE_KEY); 420 mListHasFocus = icicle.getBoolean(FOCUS_KEY); 421 sortMode = icicle.getInt(SORT_MODE_KEY, sortMode); 422 } 423 if (Intent.ACTION_GET_CONTENT.equals(getIntent().getAction())) { 424 mBaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 425 } else { 426 mBaseUri = getIntent().getData(); 427 if (mBaseUri == null) { 428 Log.w("MusicPicker", "No data URI given to PICK action"); 429 finish(); 430 return; 431 } 432 } 433 434 setContentView(R.layout.music_picker); 435 436 mSortOrder = MediaStore.Audio.Media.TITLE_KEY; 437 438 final ListView listView = getListView(); 439 440 listView.setItemsCanFocus(false); 441 442 mAdapter = new TrackListAdapter(this, listView, 443 R.layout.music_picker_item, new String[] {}, 444 new int[] {}); 445 446 setListAdapter(mAdapter); 447 448 listView.setTextFilterEnabled(true); 449 450 // We manually save/restore the listview state 451 listView.setSaveEnabled(false); 452 453 mQueryHandler = new QueryHandler(this); 454 455 mProgressContainer = findViewById(R.id.progressContainer); 456 mListContainer = findViewById(R.id.listContainer); 457 458 mOkayButton = findViewById(R.id.okayButton); 459 mOkayButton.setOnClickListener(this); 460 mCancelButton = findViewById(R.id.cancelButton); 461 mCancelButton.setOnClickListener(this); 462 463 // If there is a currently selected Uri, then try to determine who 464 // it is. 465 if (mSelectedUri != null) { 466 Uri.Builder builder = mSelectedUri.buildUpon(); 467 String path = mSelectedUri.getEncodedPath(); 468 int idx = path.lastIndexOf('/'); 469 if (idx >= 0) { 470 path = path.substring(0, idx); 471 } 472 builder.encodedPath(path); 473 Uri baseSelectedUri = builder.build(); 474 if (DBG) Log.v(TAG, "Selected Uri: " + mSelectedUri); 475 if (DBG) Log.v(TAG, "Selected base Uri: " + baseSelectedUri); 476 if (DBG) Log.v(TAG, "Base Uri: " + mBaseUri); 477 if (baseSelectedUri.equals(mBaseUri)) { 478 // If the base Uri of the selected Uri is the same as our 479 // content's base Uri, then use the selection! 480 mSelectedId = ContentUris.parseId(mSelectedUri); 481 } 482 } 483 484 setSortMode(sortMode); 485 } 486 487 @Override public void onRestart() { 488 super.onRestart(); 489 doQuery(false, null); 490 } 491 492 @Override public boolean onOptionsItemSelected(MenuItem item) { 493 if (setSortMode(item.getItemId())) { 494 return true; 495 } 496 return super.onOptionsItemSelected(item); 497 } 498 499 @Override public boolean onCreateOptionsMenu(Menu menu) { 500 super.onCreateOptionsMenu(menu); 501 menu.add(Menu.NONE, TRACK_MENU, Menu.NONE, R.string.sort_by_track); 502 menu.add(Menu.NONE, ALBUM_MENU, Menu.NONE, R.string.sort_by_album); 503 menu.add(Menu.NONE, ARTIST_MENU, Menu.NONE, R.string.sort_by_artist); 504 return true; 505 } 506 507 @Override protected void onSaveInstanceState(Bundle icicle) { 508 super.onSaveInstanceState(icicle); 509 // Save list state in the bundle so we can restore it after the 510 // QueryHandler has run 511 icicle.putParcelable(LIST_STATE_KEY, getListView().onSaveInstanceState()); 512 icicle.putBoolean(FOCUS_KEY, getListView().hasFocus()); 513 icicle.putInt(SORT_MODE_KEY, mSortMode); 514 } 515 516 @Override public void onPause() { 517 super.onPause(); 518 stopMediaPlayer(); 519 } 520 521 @Override public void onStop() { 522 super.onStop(); 523 524 // We don't want the list to display the empty state, since when we 525 // resume it will still be there and show up while the new query is 526 // happening. After the async query finishes in response to onResume() 527 // setLoading(false) will be called. 528 mAdapter.setLoading(true); 529 mAdapter.changeCursor(null); 530 } 531 532 /** 533 * Changes the current sort order, building the appropriate query string 534 * for the selected order. 535 */ 536 boolean setSortMode(int sortMode) { 537 if (sortMode != mSortMode) { 538 switch (sortMode) { 539 case TRACK_MENU: 540 mSortMode = sortMode; 541 mSortOrder = MediaStore.Audio.Media.TITLE_KEY; 542 doQuery(false, null); 543 return true; 544 case ALBUM_MENU: 545 mSortMode = sortMode; 546 mSortOrder = MediaStore.Audio.Media.ALBUM_KEY + " ASC, " 547 + MediaStore.Audio.Media.TRACK + " ASC, " 548 + MediaStore.Audio.Media.TITLE_KEY + " ASC"; 549 doQuery(false, null); 550 return true; 551 case ARTIST_MENU: 552 mSortMode = sortMode; 553 mSortOrder = MediaStore.Audio.Media.ARTIST_KEY + " ASC, " 554 + MediaStore.Audio.Media.ALBUM_KEY + " ASC, " 555 + MediaStore.Audio.Media.TRACK + " ASC, " 556 + MediaStore.Audio.Media.TITLE_KEY + " ASC"; 557 doQuery(false, null); 558 return true; 559 } 560 561 } 562 return false; 563 } 564 565 /** 566 * The first time this is called, we hide the large progress indicator 567 * and show the list view, doing fade animations between them. 568 */ 569 void makeListShown() { 570 if (!mListShown) { 571 mListShown = true; 572 mProgressContainer.startAnimation(AnimationUtils.loadAnimation( 573 this, android.R.anim.fade_out)); 574 mProgressContainer.setVisibility(View.GONE); 575 mListContainer.startAnimation(AnimationUtils.loadAnimation( 576 this, android.R.anim.fade_in)); 577 mListContainer.setVisibility(View.VISIBLE); 578 } 579 } 580 581 /** 582 * Common method for performing a query of the music database, called for 583 * both top-level queries and filtering. 584 * 585 * @param sync If true, this query should be done synchronously and the 586 * resulting cursor returned. If false, it will be done asynchronously and 587 * null returned. 588 * @param filterstring If non-null, this is a filter to apply to the query. 589 */ 590 Cursor doQuery(boolean sync, String filterstring) { 591 // Cancel any pending queries 592 mQueryHandler.cancelOperation(MY_QUERY_TOKEN); 593 594 StringBuilder where = new StringBuilder(); 595 where.append(MediaStore.Audio.Media.TITLE + " != ''"); 596 597 // Add in the filtering constraints 598 String [] keywords = null; 599 if (filterstring != null) { 600 String [] searchWords = filterstring.split(" "); 601 keywords = new String[searchWords.length]; 602 Collator col = Collator.getInstance(); 603 col.setStrength(Collator.PRIMARY); 604 for (int i = 0; i < searchWords.length; i++) { 605 String key = MediaStore.Audio.keyFor(searchWords[i]); 606 key = key.replace("\\", "\\\\"); 607 key = key.replace("%", "\\%"); 608 key = key.replace("_", "\\_"); 609 keywords[i] = '%' + key + '%'; 610 } 611 for (int i = 0; i < searchWords.length; i++) { 612 where.append(" AND "); 613 where.append(MediaStore.Audio.Media.ARTIST_KEY + "||"); 614 where.append(MediaStore.Audio.Media.ALBUM_KEY + "||"); 615 where.append(MediaStore.Audio.Media.TITLE_KEY + " LIKE ? ESCAPE '\\'"); 616 } 617 } 618 619 // We want to show all audio files, even recordings. Enforcing the 620 // following condition would hide recordings. 621 //where.append(" AND " + MediaStore.Audio.Media.IS_MUSIC + "=1"); 622 623 if (sync) { 624 try { 625 return getContentResolver().query(mBaseUri, CURSOR_COLS, 626 where.toString(), keywords, mSortOrder); 627 } catch (UnsupportedOperationException ex) { 628 } 629 } else { 630 mAdapter.setLoading(true); 631 setProgressBarIndeterminateVisibility(true); 632 mQueryHandler.startQuery(MY_QUERY_TOKEN, null, mBaseUri, CURSOR_COLS, 633 where.toString(), keywords, mSortOrder); 634 } 635 return null; 636 } 637 638 @Override protected void onListItemClick(ListView l, View v, int position, 639 long id) { 640 mCursor.moveToPosition(position); 641 if (DBG) Log.v(TAG, "Click on " + position + " (id=" + id 642 + ", cursid=" 643 + mCursor.getLong(mCursor.getColumnIndex(MediaStore.Audio.Media._ID)) 644 + ") in cursor " + mCursor 645 + " adapter=" + l.getAdapter()); 646 setSelected(mCursor); 647 } 648 649 void setSelected(Cursor c) { 650 Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 651 long newId = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Audio.Media._ID)); 652 mSelectedUri = ContentUris.withAppendedId(uri, newId); 653 654 mSelectedId = newId; 655 if (newId != mPlayingId || mMediaPlayer == null) { 656 stopMediaPlayer(); 657 mMediaPlayer = new MediaPlayer(); 658 try { 659 mMediaPlayer.setDataSource(this, mSelectedUri); 660 mMediaPlayer.setOnCompletionListener(this); 661 mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING); 662 mMediaPlayer.prepare(); 663 mMediaPlayer.start(); 664 mPlayingId = newId; 665 getListView().invalidateViews(); 666 } catch (IOException e) { 667 Log.w("MusicPicker", "Unable to play track", e); 668 } 669 } else if (mMediaPlayer != null) { 670 stopMediaPlayer(); 671 getListView().invalidateViews(); 672 } 673 } 674 675 public void onCompletion(MediaPlayer mp) { 676 if (mMediaPlayer == mp) { 677 mp.stop(); 678 mp.release(); 679 mMediaPlayer = null; 680 mPlayingId = -1; 681 getListView().invalidateViews(); 682 } 683 } 684 685 void stopMediaPlayer() { 686 if (mMediaPlayer != null) { 687 mMediaPlayer.stop(); 688 mMediaPlayer.release(); 689 mMediaPlayer = null; 690 mPlayingId = -1; 691 } 692 } 693 694 public void onClick(View v) { 695 switch (v.getId()) { 696 case R.id.okayButton: 697 if (mSelectedId >= 0) { 698 setResult(RESULT_OK, new Intent().setData(mSelectedUri)); 699 finish(); 700 } 701 break; 702 703 case R.id.cancelButton: 704 finish(); 705 break; 706 } 707 } 708} 709