2 * Copyright (C) 2007 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.music;
19 import android.app.Activity;
20 import android.app.AlertDialog;
21 import android.app.SearchManager;
22 import android.content.BroadcastReceiver;
23 import android.content.ComponentName;
24 import android.content.ContentResolver;
25 import android.content.ContentUris;
26 import android.content.Context;
27 import android.content.DialogInterface;
28 import android.content.Intent;
29 import android.content.IntentFilter;
30 import android.content.ServiceConnection;
31 import android.content.res.Configuration;
32 import android.content.res.Resources;
33 import android.database.Cursor;
34 import android.graphics.Bitmap;
35 import android.media.AudioManager;
36 import android.media.MediaFile;
37 import android.net.Uri;
38 import android.os.Bundle;
39 import android.os.RemoteException;
40 import android.os.Handler;
41 import android.os.IBinder;
42 import android.os.Looper;
43 import android.os.Message;
44 import android.os.SystemClock;
45 import android.provider.MediaStore;
46 import android.text.Layout;
47 import android.text.TextUtils.TruncateAt;
48 import android.util.Log;
49 import android.view.KeyEvent;
50 import android.view.Menu;
51 import android.view.MenuItem;
52 import android.view.MotionEvent;
53 import android.view.SubMenu;
54 import android.view.View;
55 import android.view.ViewConfiguration;
56 import android.view.Window;
57 import android.widget.ImageButton;
58 import android.widget.ImageView;
59 import android.widget.ProgressBar;
60 import android.widget.SeekBar;
61 import android.widget.TextView;
62 import android.widget.Toast;
63 import android.widget.SeekBar.OnSeekBarChangeListener;
66 public class MediaPlaybackActivity extends Activity implements MusicUtils.Defs,
67 View.OnTouchListener, View.OnLongClickListener
69 private static final int USE_AS_RINGTONE = CHILD_MENU_BASE;
71 private boolean mOneShot = false;
72 private boolean mSeeking = false;
73 private boolean mDeviceHasNoDpad;
74 private long mStartSeekPos = 0;
75 private long mLastSeekEventTime;
76 private IMediaPlaybackService mService = null;
77 private RepeatingImageButton mPrevButton;
78 private ImageButton mPauseButton;
79 private RepeatingImageButton mNextButton;
80 private ImageButton mRepeatButton;
81 private ImageButton mShuffleButton;
82 private ImageButton mQueueButton;
83 private Worker mAlbumArtWorker;
84 private AlbumArtHandler mAlbumArtHandler;
86 private int mTouchSlop;
88 public MediaPlaybackActivity()
92 /** Called when the activity is first created. */
94 public void onCreate(Bundle icicle)
96 super.onCreate(icicle);
97 setVolumeControlStream(AudioManager.STREAM_MUSIC);
99 mAlbumArtWorker = new Worker("album art worker");
100 mAlbumArtHandler = new AlbumArtHandler(mAlbumArtWorker.getLooper());
102 requestWindowFeature(Window.FEATURE_NO_TITLE);
103 setContentView(R.layout.audio_player);
105 mCurrentTime = (TextView) findViewById(R.id.currenttime);
106 mTotalTime = (TextView) findViewById(R.id.totaltime);
107 mProgress = (ProgressBar) findViewById(android.R.id.progress);
108 mAlbum = (ImageView) findViewById(R.id.album);
109 mArtistName = (TextView) findViewById(R.id.artistname);
110 mAlbumName = (TextView) findViewById(R.id.albumname);
111 mTrackName = (TextView) findViewById(R.id.trackname);
113 View v = (View)mArtistName.getParent();
114 v.setOnTouchListener(this);
115 v.setOnLongClickListener(this);
117 v = (View)mAlbumName.getParent();
118 v.setOnTouchListener(this);
119 v.setOnLongClickListener(this);
121 v = (View)mTrackName.getParent();
122 v.setOnTouchListener(this);
123 v.setOnLongClickListener(this);
125 mPrevButton = (RepeatingImageButton) findViewById(R.id.prev);
126 mPrevButton.setOnClickListener(mPrevListener);
127 mPrevButton.setRepeatListener(mRewListener, 260);
128 mPauseButton = (ImageButton) findViewById(R.id.pause);
129 mPauseButton.requestFocus();
130 mPauseButton.setOnClickListener(mPauseListener);
131 mNextButton = (RepeatingImageButton) findViewById(R.id.next);
132 mNextButton.setOnClickListener(mNextListener);
133 mNextButton.setRepeatListener(mFfwdListener, 260);
136 mDeviceHasNoDpad = (getResources().getConfiguration().navigation !=
137 Configuration.NAVIGATION_DPAD);
139 mQueueButton = (ImageButton) findViewById(R.id.curplaylist);
140 mQueueButton.setOnClickListener(mQueueListener);
141 mShuffleButton = ((ImageButton) findViewById(R.id.shuffle));
142 mShuffleButton.setOnClickListener(mShuffleListener);
143 mRepeatButton = ((ImageButton) findViewById(R.id.repeat));
144 mRepeatButton.setOnClickListener(mRepeatListener);
146 if (mProgress instanceof SeekBar) {
147 SeekBar seeker = (SeekBar) mProgress;
148 seeker.setOnSeekBarChangeListener(mSeekListener);
150 mProgress.setMax(1000);
152 if (icicle != null) {
153 mOneShot = icicle.getBoolean("oneshot");
155 mOneShot = getIntent().getBooleanExtra("oneshot", false);
158 mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();
165 boolean mDraggingLabel = false;
167 TextView textViewForContainer(View v) {
168 View vv = v.findViewById(R.id.artistname);
169 if (vv != null) return (TextView) vv;
170 vv = v.findViewById(R.id.albumname);
171 if (vv != null) return (TextView) vv;
172 vv = v.findViewById(R.id.trackname);
173 if (vv != null) return (TextView) vv;
177 public boolean onTouch(View v, MotionEvent event) {
178 int action = event.getAction();
179 TextView tv = textViewForContainer(v);
183 if (action == MotionEvent.ACTION_DOWN) {
184 v.setBackgroundColor(0xff606060);
185 mInitialX = mLastX = (int) event.getX();
186 mDraggingLabel = false;
187 } else if (action == MotionEvent.ACTION_UP ||
188 action == MotionEvent.ACTION_CANCEL) {
189 v.setBackgroundColor(0);
190 if (mDraggingLabel) {
191 Message msg = mLabelScroller.obtainMessage(0, tv);
192 mLabelScroller.sendMessageDelayed(msg, 1000);
194 } else if (action == MotionEvent.ACTION_MOVE) {
195 if (mDraggingLabel) {
196 int scrollx = tv.getScrollX();
197 int x = (int) event.getX();
198 int delta = mLastX - x;
202 if (scrollx > mTextWidth) {
203 // scrolled the text completely off the view to the left
204 scrollx -= mTextWidth;
205 scrollx -= mViewWidth;
207 if (scrollx < -mViewWidth) {
208 // scrolled the text completely off the view to the right
209 scrollx += mViewWidth;
210 scrollx += mTextWidth;
212 tv.scrollTo(scrollx, 0);
216 int delta = mInitialX - (int) event.getX();
217 if (Math.abs(delta) > mTouchSlop) {
219 mLabelScroller.removeMessages(0, tv);
221 // Only turn ellipsizing off when it's not already off, because it
222 // causes the scroll position to be reset to 0.
223 if (tv.getEllipsize() != null) {
224 tv.setEllipsize(null);
226 Layout ll = tv.getLayout();
227 // layout might be null if the text just changed, or ellipsizing
228 // was just turned off
232 // get the non-ellipsized line width, to determine whether scrolling
233 // should even be allowed
234 mTextWidth = (int) tv.getLayout().getLineWidth(0);
235 mViewWidth = tv.getWidth();
236 if (mViewWidth > mTextWidth) {
237 tv.setEllipsize(TruncateAt.END);
241 mDraggingLabel = true;
242 tv.setHorizontalFadingEdgeEnabled(true);
250 Handler mLabelScroller = new Handler() {
252 public void handleMessage(Message msg) {
253 TextView tv = (TextView) msg.obj;
254 int x = tv.getScrollX();
258 tv.setEllipsize(TruncateAt.END);
260 Message newmsg = obtainMessage(0, tv);
261 mLabelScroller.sendMessageDelayed(newmsg, 15);
266 public boolean onLongClick(View view) {
268 CharSequence title = null;
277 artist = mService.getArtistName();
278 album = mService.getAlbumName();
279 song = mService.getTrackName();
280 audioid = mService.getAudioId();
281 } catch (RemoteException ex) {
285 if (MediaFile.UNKNOWN_STRING.equals(album) &&
286 MediaFile.UNKNOWN_STRING.equals(artist) &&
288 song.startsWith("recording")) {
297 Cursor c = MusicUtils.query(this,
298 ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, audioid),
299 new String[] {MediaStore.Audio.Media.IS_MUSIC}, null, null, null);
300 boolean ismusic = true;
302 if (c.moveToFirst()) {
303 ismusic = c.getInt(0) != 0;
311 boolean knownartist =
312 (artist != null) && !MediaFile.UNKNOWN_STRING.equals(artist);
315 (album != null) && !MediaFile.UNKNOWN_STRING.equals(album);
317 if (knownartist && view.equals(mArtistName.getParent())) {
320 mime = MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE;
321 } else if (knownalbum && view.equals(mAlbumName.getParent())) {
324 query = artist + " " + album;
328 mime = MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE;
329 } else if (view.equals(mTrackName.getParent()) || !knownartist || !knownalbum) {
330 if ((song == null) || MediaFile.UNKNOWN_STRING.equals(song)) {
331 // A popup of the form "Search for null/'' using ..." is pretty
332 // unhelpful, plus, we won't find any way to buy it anyway.
338 query = artist + " " + song;
342 mime = "audio/*"; // the specific type doesn't matter, so don't bother retrieving it
344 throw new RuntimeException("shouldn't be here");
346 title = getString(R.string.mediasearch, title);
348 Intent i = new Intent();
349 i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
350 i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH);
351 i.putExtra(SearchManager.QUERY, query);
353 i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist);
356 i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, album);
358 i.putExtra(MediaStore.EXTRA_MEDIA_TITLE, song);
359 i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, mime);
361 startActivity(Intent.createChooser(i, title));
365 private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
366 public void onStartTrackingTouch(SeekBar bar) {
367 mLastSeekEventTime = 0;
370 public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
371 if (!fromuser || (mService == null)) return;
372 long now = SystemClock.elapsedRealtime();
373 if ((now - mLastSeekEventTime) > 250) {
374 mLastSeekEventTime = now;
375 mPosOverride = mDuration * progress / 1000;
377 mService.seek(mPosOverride);
378 } catch (RemoteException ex) {
381 // trackball event, allow progress updates
388 public void onStopTrackingTouch(SeekBar bar) {
394 private View.OnClickListener mQueueListener = new View.OnClickListener() {
395 public void onClick(View v) {
397 new Intent(Intent.ACTION_EDIT)
398 .setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track")
399 .putExtra("playlist", "nowplaying")
404 private View.OnClickListener mShuffleListener = new View.OnClickListener() {
405 public void onClick(View v) {
410 private View.OnClickListener mRepeatListener = new View.OnClickListener() {
411 public void onClick(View v) {
416 private View.OnClickListener mPauseListener = new View.OnClickListener() {
417 public void onClick(View v) {
422 private View.OnClickListener mPrevListener = new View.OnClickListener() {
423 public void onClick(View v) {
424 if (mService == null) return;
426 if (mService.position() < 2000) {
432 } catch (RemoteException ex) {
437 private View.OnClickListener mNextListener = new View.OnClickListener() {
438 public void onClick(View v) {
439 if (mService == null) return;
442 } catch (RemoteException ex) {
447 private RepeatingImageButton.RepeatListener mRewListener =
448 new RepeatingImageButton.RepeatListener() {
449 public void onRepeat(View v, long howlong, int repcnt) {
450 scanBackward(repcnt, howlong);
454 private RepeatingImageButton.RepeatListener mFfwdListener =
455 new RepeatingImageButton.RepeatListener() {
456 public void onRepeat(View v, long howlong, int repcnt) {
457 scanForward(repcnt, howlong);
462 public void onStop() {
464 if (mService != null && mOneShot && getChangingConfigurations() == 0) {
467 } catch (RemoteException ex) {
470 mHandler.removeMessages(REFRESH);
471 unregisterReceiver(mStatusListener);
472 MusicUtils.unbindFromService(this);
478 public void onSaveInstanceState(Bundle outState) {
479 outState.putBoolean("oneshot", mOneShot);
480 super.onSaveInstanceState(outState);
484 public void onStart() {
488 if (false == MusicUtils.bindToService(this, osc)) {
489 // something went wrong
490 mHandler.sendEmptyMessage(QUIT);
493 IntentFilter f = new IntentFilter();
494 f.addAction(MediaPlaybackService.PLAYSTATE_CHANGED);
495 f.addAction(MediaPlaybackService.META_CHANGED);
496 f.addAction(MediaPlaybackService.PLAYBACK_COMPLETE);
497 registerReceiver(mStatusListener, new IntentFilter(f));
499 long next = refreshNow();
500 queueNextRefresh(next);
504 public void onNewIntent(Intent intent) {
506 mOneShot = intent.getBooleanExtra("oneshot", false);
510 public void onResume() {
513 setPauseButtonImage();
517 public void onDestroy()
519 mAlbumArtWorker.quit();
521 //System.out.println("***************** playback activity onDestroy\n");
525 public boolean onCreateOptionsMenu(Menu menu) {
526 super.onCreateOptionsMenu(menu);
527 // Don't show the menu items if we got launched by path/filedescriptor, or
528 // if we're in one shot mode. In most cases, these menu items are not
529 // useful in those modes, so for consistency we never show them in these
530 // modes, instead of tailoring them to the specific file being played.
531 if (MusicUtils.getCurrentAudioId() >= 0 && !mOneShot) {
532 menu.add(0, GOTO_START, 0, R.string.goto_start).setIcon(R.drawable.ic_menu_music_library);
533 menu.add(0, PARTY_SHUFFLE, 0, R.string.party_shuffle); // icon will be set in onPrepareOptionsMenu()
534 SubMenu sub = menu.addSubMenu(0, ADD_TO_PLAYLIST, 0,
535 R.string.add_to_playlist).setIcon(android.R.drawable.ic_menu_add);
536 MusicUtils.makePlaylistMenu(this, sub);
537 menu.add(0, USE_AS_RINGTONE, 0, R.string.ringtone_menu_short).setIcon(R.drawable.ic_menu_set_as_ringtone);
538 menu.add(0, DELETE_ITEM, 0, R.string.delete_item).setIcon(R.drawable.ic_menu_delete);
545 public boolean onPrepareOptionsMenu(Menu menu) {
546 MenuItem item = menu.findItem(PARTY_SHUFFLE);
548 int shuffle = MusicUtils.getCurrentShuffleMode();
549 if (shuffle == MediaPlaybackService.SHUFFLE_AUTO) {
550 item.setIcon(R.drawable.ic_menu_party_shuffle);
551 item.setTitle(R.string.party_shuffle_off);
553 item.setIcon(R.drawable.ic_menu_party_shuffle);
554 item.setTitle(R.string.party_shuffle);
561 public boolean onOptionsItemSelected(MenuItem item) {
564 switch (item.getItemId()) {
566 intent = new Intent();
567 intent.setClass(this, MusicBrowserActivity.class);
568 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
569 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
570 startActivity(intent);
572 case USE_AS_RINGTONE: {
573 // Set the system setting to make this the current ringtone
574 if (mService != null) {
575 MusicUtils.setRingtone(this, mService.getAudioId());
580 if (mService != null) {
581 int shuffle = mService.getShuffleMode();
582 if (shuffle == MediaPlaybackService.SHUFFLE_AUTO) {
583 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
585 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_AUTO);
588 setShuffleButtonImage();
592 intent = new Intent();
593 intent.setClass(this, CreatePlaylist.class);
594 startActivityForResult(intent, NEW_PLAYLIST);
598 case PLAYLIST_SELECTED: {
599 long [] list = new long[1];
600 list[0] = MusicUtils.getCurrentAudioId();
601 long playlist = item.getIntent().getLongExtra("playlist", 0);
602 MusicUtils.addToPlaylist(this, list, playlist);
607 if (mService != null) {
608 long [] list = new long[1];
609 list[0] = MusicUtils.getCurrentAudioId();
610 Bundle b = new Bundle();
611 b.putString("description", getString(R.string.delete_song_desc,
612 mService.getTrackName()));
613 b.putLongArray("items", list);
614 intent = new Intent();
615 intent.setClass(this, DeleteItems.class);
617 startActivityForResult(intent, -1);
622 } catch (RemoteException ex) {
624 return super.onOptionsItemSelected(item);
628 protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
629 if (resultCode != RESULT_OK) {
632 switch (requestCode) {
634 Uri uri = intent.getData();
636 long [] list = new long[1];
637 list[0] = MusicUtils.getCurrentAudioId();
638 int playlist = Integer.parseInt(uri.getLastPathSegment());
639 MusicUtils.addToPlaylist(this, list, playlist);
644 private final int keyboard[][] = {
667 KeyEvent.KEYCODE_DEL,
677 KeyEvent.KEYCODE_COMMA,
678 KeyEvent.KEYCODE_PERIOD,
679 KeyEvent.KEYCODE_ENTER
687 private boolean seekMethod1(int keyCode)
689 for(int x=0;x<10;x++) {
690 for(int y=0;y<3;y++) {
691 if(keyboard[y][x] == keyCode) {
694 if(x == lastX && y == lastY) dir = 0;
695 else if (y == 0 && lastY == 0 && x > lastX) dir = 1;
696 else if (y == 0 && lastY == 0 && x < lastX) dir = -1;
698 else if (y == 2 && lastY == 2 && x > lastX) dir = -1;
699 else if (y == 2 && lastY == 2 && x < lastX) dir = 1;
701 else if (y < lastY && x <= 4) dir = 1;
702 else if (y < lastY && x >= 5) dir = -1;
704 else if (y > lastY && x <= 4) dir = -1;
705 else if (y > lastY && x >= 5) dir = 1;
709 mService.seek(mService.position() + dir * 5);
710 } catch (RemoteException ex) {
722 private boolean seekMethod2(int keyCode)
724 if (mService == null) return false;
725 for(int i=0;i<10;i++) {
726 if(keyboard[0][i] == keyCode) {
727 int seekpercentage = 100*i/10;
729 mService.seek(mService.duration() * seekpercentage / 100);
730 } catch (RemoteException ex) {
740 public boolean onKeyUp(int keyCode, KeyEvent event) {
744 case KeyEvent.KEYCODE_DPAD_LEFT:
745 if (mDeviceHasNoDpad) {
748 if (mService != null) {
749 if (!mSeeking && mStartSeekPos >= 0) {
750 mPauseButton.requestFocus();
751 if (mStartSeekPos < 1000) {
757 scanBackward(-1, event.getEventTime() - event.getDownTime());
758 mPauseButton.requestFocus();
765 case KeyEvent.KEYCODE_DPAD_RIGHT:
766 if (mDeviceHasNoDpad) {
769 if (mService != null) {
770 if (!mSeeking && mStartSeekPos >= 0) {
771 mPauseButton.requestFocus();
774 scanForward(-1, event.getEventTime() - event.getDownTime());
775 mPauseButton.requestFocus();
783 } catch (RemoteException ex) {
785 return super.onKeyUp(keyCode, event);
789 public boolean onKeyDown(int keyCode, KeyEvent event)
792 int repcnt = event.getRepeatCount();
794 if((seekmethod==0)?seekMethod1(keyCode):seekMethod2(keyCode))
801 case KeyEvent.KEYCODE_Q: av.adjustParams(-0.05, 0.0, 0.0, 0.0, 0.0,-1.0); break;
802 case KeyEvent.KEYCODE_E: av.adjustParams( 0.05, 0.0, 0.0, 0.0, 0.0, 1.0); break;
804 case KeyEvent.KEYCODE_W: av.adjustParams( 0.0, 0.0,-1.0, 0.0, 0.0, 0.0); break;
805 case KeyEvent.KEYCODE_X: av.adjustParams( 0.0, 0.0, 1.0, 0.0, 0.0, 0.0); break;
806 case KeyEvent.KEYCODE_A: av.adjustParams( 0.0,-1.0, 0.0, 0.0, 0.0, 0.0); break;
807 case KeyEvent.KEYCODE_D: av.adjustParams( 0.0, 1.0, 0.0, 0.0, 0.0, 0.0); break;
809 case KeyEvent.KEYCODE_R: av.adjustParams( 0.0, 0.0, 0.0, 0.0, 0.0,-1.0); break;
810 case KeyEvent.KEYCODE_U: av.adjustParams( 0.0, 0.0, 0.0, 0.0, 0.0, 1.0); break;
812 case KeyEvent.KEYCODE_Y: av.adjustParams( 0.0, 0.0, 0.0, 0.0,-1.0, 0.0); break;
813 case KeyEvent.KEYCODE_N: av.adjustParams( 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); break;
814 case KeyEvent.KEYCODE_G: av.adjustParams( 0.0, 0.0, 0.0,-1.0, 0.0, 0.0); break;
815 case KeyEvent.KEYCODE_J: av.adjustParams( 0.0, 0.0, 0.0, 1.0, 0.0, 0.0); break;
819 case KeyEvent.KEYCODE_SLASH:
820 seekmethod = 1 - seekmethod;
823 case KeyEvent.KEYCODE_DPAD_LEFT:
824 if (mDeviceHasNoDpad) {
827 if (!mPrevButton.hasFocus()) {
828 mPrevButton.requestFocus();
830 scanBackward(repcnt, event.getEventTime() - event.getDownTime());
832 case KeyEvent.KEYCODE_DPAD_RIGHT:
833 if (mDeviceHasNoDpad) {
836 if (!mNextButton.hasFocus()) {
837 mNextButton.requestFocus();
839 scanForward(repcnt, event.getEventTime() - event.getDownTime());
842 case KeyEvent.KEYCODE_S:
846 case KeyEvent.KEYCODE_DPAD_CENTER:
847 case KeyEvent.KEYCODE_SPACE:
851 return super.onKeyDown(keyCode, event);
854 private void scanBackward(int repcnt, long delta) {
855 if(mService == null) return;
858 mStartSeekPos = mService.position();
859 mLastSeekEventTime = 0;
864 // seek at 10x speed for the first 5 seconds
867 // seek at 40x after that
868 delta = 50000 + (delta - 5000) * 40;
870 long newpos = mStartSeekPos - delta;
872 // move to previous track
874 long duration = mService.duration();
875 mStartSeekPos += duration;
878 if (((delta - mLastSeekEventTime) > 250) || repcnt < 0){
879 mService.seek(newpos);
880 mLastSeekEventTime = delta;
883 mPosOverride = newpos;
889 } catch (RemoteException ex) {
893 private void scanForward(int repcnt, long delta) {
894 if(mService == null) return;
897 mStartSeekPos = mService.position();
898 mLastSeekEventTime = 0;
903 // seek at 10x speed for the first 5 seconds
906 // seek at 40x after that
907 delta = 50000 + (delta - 5000) * 40;
909 long newpos = mStartSeekPos + delta;
910 long duration = mService.duration();
911 if (newpos >= duration) {
912 // move to next track
914 mStartSeekPos -= duration; // is OK to go negative
917 if (((delta - mLastSeekEventTime) > 250) || repcnt < 0){
918 mService.seek(newpos);
919 mLastSeekEventTime = delta;
922 mPosOverride = newpos;
928 } catch (RemoteException ex) {
932 private void doPauseResume() {
934 if(mService != null) {
935 if (mService.isPlaying()) {
941 setPauseButtonImage();
943 } catch (RemoteException ex) {
947 private void toggleShuffle() {
948 if (mService == null) {
952 int shuffle = mService.getShuffleMode();
953 if (shuffle == MediaPlaybackService.SHUFFLE_NONE) {
954 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NORMAL);
955 if (mService.getRepeatMode() == MediaPlaybackService.REPEAT_CURRENT) {
956 mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
957 setRepeatButtonImage();
959 showToast(R.string.shuffle_on_notif);
960 } else if (shuffle == MediaPlaybackService.SHUFFLE_NORMAL ||
961 shuffle == MediaPlaybackService.SHUFFLE_AUTO) {
962 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
963 showToast(R.string.shuffle_off_notif);
965 Log.e("MediaPlaybackActivity", "Invalid shuffle mode: " + shuffle);
967 setShuffleButtonImage();
968 } catch (RemoteException ex) {
972 private void cycleRepeat() {
973 if (mService == null) {
977 int mode = mService.getRepeatMode();
978 if (mode == MediaPlaybackService.REPEAT_NONE) {
979 mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
980 showToast(R.string.repeat_all_notif);
981 } else if (mode == MediaPlaybackService.REPEAT_ALL) {
982 mService.setRepeatMode(MediaPlaybackService.REPEAT_CURRENT);
983 if (mService.getShuffleMode() != MediaPlaybackService.SHUFFLE_NONE) {
984 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
985 setShuffleButtonImage();
987 showToast(R.string.repeat_current_notif);
989 mService.setRepeatMode(MediaPlaybackService.REPEAT_NONE);
990 showToast(R.string.repeat_off_notif);
992 setRepeatButtonImage();
993 } catch (RemoteException ex) {
998 private void showToast(int resid) {
999 if (mToast == null) {
1000 mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
1002 mToast.setText(resid);
1006 private void startPlayback() {
1008 if(mService == null)
1010 Intent intent = getIntent();
1011 String filename = "";
1012 Uri uri = intent.getData();
1013 if (uri != null && uri.toString().length() > 0) {
1014 // If this is a file:// URI, just use the path directly instead
1015 // of going through the open-from-filedescriptor codepath.
1016 String scheme = uri.getScheme();
1017 if ("file".equals(scheme)) {
1018 filename = uri.getPath();
1020 filename = uri.toString();
1023 if (! ContentResolver.SCHEME_CONTENT.equals(scheme) ||
1024 ! MediaStore.AUTHORITY.equals(uri.getAuthority())) {
1028 mService.openFile(filename, mOneShot);
1030 setIntent(new Intent());
1031 } catch (Exception ex) {
1032 Log.d("MediaPlaybackActivity", "couldn't start playback: " + ex);
1037 long next = refreshNow();
1038 queueNextRefresh(next);
1041 private ServiceConnection osc = new ServiceConnection() {
1042 public void onServiceConnected(ComponentName classname, IBinder obj) {
1043 mService = IMediaPlaybackService.Stub.asInterface(obj);
1046 // Assume something is playing when the service says it is,
1047 // but also if the audio ID is valid but the service is paused.
1048 if (mService.getAudioId() >= 0 || mService.isPlaying() ||
1049 mService.getPath() != null) {
1050 // something is playing now, we're done
1051 if (mOneShot || mService.getAudioId() < 0) {
1052 mRepeatButton.setVisibility(View.INVISIBLE);
1053 mShuffleButton.setVisibility(View.INVISIBLE);
1054 mQueueButton.setVisibility(View.INVISIBLE);
1056 mRepeatButton.setVisibility(View.VISIBLE);
1057 mShuffleButton.setVisibility(View.VISIBLE);
1058 mQueueButton.setVisibility(View.VISIBLE);
1059 setRepeatButtonImage();
1060 setShuffleButtonImage();
1062 setPauseButtonImage();
1065 } catch (RemoteException ex) {
1067 // Service is dead or not playing anything. If we got here as part
1068 // of a "play this file" Intent, exit. Otherwise go to the Music
1069 // app start screen.
1070 if (getIntent().getData() == null) {
1071 Intent intent = new Intent(Intent.ACTION_MAIN);
1072 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1073 intent.setClass(MediaPlaybackActivity.this, MusicBrowserActivity.class);
1074 startActivity(intent);
1078 public void onServiceDisconnected(ComponentName classname) {
1082 private void setRepeatButtonImage() {
1084 switch (mService.getRepeatMode()) {
1085 case MediaPlaybackService.REPEAT_ALL:
1086 mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_all_btn);
1088 case MediaPlaybackService.REPEAT_CURRENT:
1089 mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_once_btn);
1092 mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_off_btn);
1095 } catch (RemoteException ex) {
1099 private void setShuffleButtonImage() {
1101 switch (mService.getShuffleMode()) {
1102 case MediaPlaybackService.SHUFFLE_NONE:
1103 mShuffleButton.setImageResource(R.drawable.ic_mp_shuffle_off_btn);
1105 case MediaPlaybackService.SHUFFLE_AUTO:
1106 mShuffleButton.setImageResource(R.drawable.ic_mp_partyshuffle_on_btn);
1109 mShuffleButton.setImageResource(R.drawable.ic_mp_shuffle_on_btn);
1112 } catch (RemoteException ex) {
1116 private void setPauseButtonImage() {
1118 if (mService != null && mService.isPlaying()) {
1119 mPauseButton.setImageResource(android.R.drawable.ic_media_pause);
1121 mPauseButton.setImageResource(android.R.drawable.ic_media_play);
1123 } catch (RemoteException ex) {
1127 private ImageView mAlbum;
1128 private TextView mCurrentTime;
1129 private TextView mTotalTime;
1130 private TextView mArtistName;
1131 private TextView mAlbumName;
1132 private TextView mTrackName;
1133 private ProgressBar mProgress;
1134 private long mPosOverride = -1;
1135 private boolean mFromTouch = false;
1136 private long mDuration;
1137 private int seekmethod;
1138 private boolean paused;
1140 private static final int REFRESH = 1;
1141 private static final int QUIT = 2;
1142 private static final int GET_ALBUM_ART = 3;
1143 private static final int ALBUM_ART_DECODED = 4;
1145 private void queueNextRefresh(long delay) {
1147 Message msg = mHandler.obtainMessage(REFRESH);
1148 mHandler.removeMessages(REFRESH);
1149 mHandler.sendMessageDelayed(msg, delay);
1153 private long refreshNow() {
1154 if(mService == null)
1157 long pos = mPosOverride < 0 ? mService.position() : mPosOverride;
1158 long remaining = 1000 - (pos % 1000);
1159 if ((pos >= 0) && (mDuration > 0)) {
1160 mCurrentTime.setText(MusicUtils.makeTimeString(this, pos / 1000));
1162 if (mService.isPlaying()) {
1163 mCurrentTime.setVisibility(View.VISIBLE);
1165 // blink the counter
1166 int vis = mCurrentTime.getVisibility();
1167 mCurrentTime.setVisibility(vis == View.INVISIBLE ? View.VISIBLE : View.INVISIBLE);
1171 mProgress.setProgress((int) (1000 * pos / mDuration));
1173 mCurrentTime.setText("--:--");
1174 mProgress.setProgress(1000);
1176 // return the number of milliseconds until the next full second, so
1177 // the counter can be updated at just the right time
1179 } catch (RemoteException ex) {
1184 private final Handler mHandler = new Handler() {
1186 public void handleMessage(Message msg) {
1188 case ALBUM_ART_DECODED:
1189 mAlbum.setImageBitmap((Bitmap)msg.obj);
1190 mAlbum.getDrawable().setDither(true);
1194 long next = refreshNow();
1195 queueNextRefresh(next);
1199 // This can be moved back to onCreate once the bug that prevents
1200 // Dialogs from being started from onCreate/onResume is fixed.
1201 new AlertDialog.Builder(MediaPlaybackActivity.this)
1202 .setTitle(R.string.service_start_error_title)
1203 .setMessage(R.string.service_start_error_msg)
1204 .setPositiveButton(R.string.service_start_error_button,
1205 new DialogInterface.OnClickListener() {
1206 public void onClick(DialogInterface dialog, int whichButton) {
1210 .setCancelable(false)
1220 private BroadcastReceiver mStatusListener = new BroadcastReceiver() {
1222 public void onReceive(Context context, Intent intent) {
1223 String action = intent.getAction();
1224 if (action.equals(MediaPlaybackService.META_CHANGED)) {
1225 // redraw the artist/title info and
1226 // set new max for progress bar
1228 setPauseButtonImage();
1229 queueNextRefresh(1);
1230 } else if (action.equals(MediaPlaybackService.PLAYBACK_COMPLETE)) {
1234 setPauseButtonImage();
1236 } else if (action.equals(MediaPlaybackService.PLAYSTATE_CHANGED)) {
1237 setPauseButtonImage();
1242 private static class AlbumSongIdWrapper {
1243 public long albumid;
1245 AlbumSongIdWrapper(long aid, long sid) {
1251 private void updateTrackInfo() {
1252 if (mService == null) {
1256 String path = mService.getPath();
1262 long songid = mService.getAudioId();
1263 if (songid < 0 && path.toLowerCase().startsWith("http://")) {
1264 // Once we can get album art and meta data from MediaPlayer, we
1265 // can show that info again when streaming.
1266 ((View) mArtistName.getParent()).setVisibility(View.INVISIBLE);
1267 ((View) mAlbumName.getParent()).setVisibility(View.INVISIBLE);
1268 mAlbum.setVisibility(View.GONE);
1269 mTrackName.setText(path);
1270 mAlbumArtHandler.removeMessages(GET_ALBUM_ART);
1271 mAlbumArtHandler.obtainMessage(GET_ALBUM_ART, new AlbumSongIdWrapper(-1, -1)).sendToTarget();
1273 ((View) mArtistName.getParent()).setVisibility(View.VISIBLE);
1274 ((View) mAlbumName.getParent()).setVisibility(View.VISIBLE);
1275 String artistName = mService.getArtistName();
1276 if (MediaFile.UNKNOWN_STRING.equals(artistName)) {
1277 artistName = getString(R.string.unknown_artist_name);
1279 mArtistName.setText(artistName);
1280 String albumName = mService.getAlbumName();
1281 long albumid = mService.getAlbumId();
1282 if (MediaFile.UNKNOWN_STRING.equals(albumName)) {
1283 albumName = getString(R.string.unknown_album_name);
1286 mAlbumName.setText(albumName);
1287 mTrackName.setText(mService.getTrackName());
1288 mAlbumArtHandler.removeMessages(GET_ALBUM_ART);
1289 mAlbumArtHandler.obtainMessage(GET_ALBUM_ART, new AlbumSongIdWrapper(albumid, songid)).sendToTarget();
1290 mAlbum.setVisibility(View.VISIBLE);
1292 mDuration = mService.duration();
1293 mTotalTime.setText(MusicUtils.makeTimeString(this, mDuration / 1000));
1294 } catch (RemoteException ex) {
1299 public class AlbumArtHandler extends Handler {
1300 private long mAlbumId = -1;
1302 public AlbumArtHandler(Looper looper) {
1306 public void handleMessage(Message msg)
1308 long albumid = ((AlbumSongIdWrapper) msg.obj).albumid;
1309 long songid = ((AlbumSongIdWrapper) msg.obj).songid;
1310 if (msg.what == GET_ALBUM_ART && (mAlbumId != albumid || albumid < 0)) {
1311 // while decoding the new image, show the default album art
1312 Message numsg = mHandler.obtainMessage(ALBUM_ART_DECODED, null);
1313 mHandler.removeMessages(ALBUM_ART_DECODED);
1314 mHandler.sendMessageDelayed(numsg, 300);
1315 Bitmap bm = MusicUtils.getArtwork(MediaPlaybackActivity.this, songid, albumid);
1317 bm = MusicUtils.getArtwork(MediaPlaybackActivity.this, songid, -1);
1321 numsg = mHandler.obtainMessage(ALBUM_ART_DECODED, bm);
1322 mHandler.removeMessages(ALBUM_ART_DECODED);
1323 mHandler.sendMessage(numsg);
1330 private static class Worker implements Runnable {
1331 private final Object mLock = new Object();
1332 private Looper mLooper;
1335 * Creates a worker thread with the given name. The thread
1336 * then runs a {@link android.os.Looper}.
1337 * @param name A name for the new thread
1339 Worker(String name) {
1340 Thread t = new Thread(null, this, name);
1341 t.setPriority(Thread.MIN_PRIORITY);
1343 synchronized (mLock) {
1344 while (mLooper == null) {
1347 } catch (InterruptedException ex) {
1353 public Looper getLooper() {
1358 synchronized (mLock) {
1360 mLooper = Looper.myLooper();
1366 public void quit() {