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 com.android.music.MusicUtils.ServiceToken;
21 import android.app.Activity;
22 import android.app.AlertDialog;
23 import android.app.KeyguardManager;
24 import android.app.SearchManager;
25 import android.content.BroadcastReceiver;
26 import android.content.ComponentName;
27 import android.content.ContentResolver;
28 import android.content.ContentUris;
29 import android.content.Context;
30 import android.content.DialogInterface;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.ServiceConnection;
34 import android.content.res.Configuration;
35 import android.database.Cursor;
36 import android.graphics.Bitmap;
37 import android.media.AudioManager;
38 import android.net.Uri;
39 import android.os.Bundle;
40 import android.os.Handler;
41 import android.os.IBinder;
42 import android.os.Looper;
43 import android.os.Message;
44 import android.os.RemoteException;
45 import android.os.SystemClock;
46 import android.provider.MediaStore;
47 import android.text.Layout;
48 import android.text.TextUtils.TruncateAt;
49 import android.util.Log;
50 import android.view.KeyEvent;
51 import android.view.Menu;
52 import android.view.MenuItem;
53 import android.view.MotionEvent;
54 import android.view.SubMenu;
55 import android.view.View;
56 import android.view.ViewConfiguration;
57 import android.view.Window;
58 import android.widget.ImageButton;
59 import android.widget.ImageView;
60 import android.widget.ProgressBar;
61 import android.widget.SeekBar;
62 import android.widget.TextView;
63 import android.widget.Toast;
64 import android.widget.SeekBar.OnSeekBarChangeListener;
67 public class MediaPlaybackActivity extends Activity implements MusicUtils.Defs,
68 View.OnTouchListener, View.OnLongClickListener
70 private static final int USE_AS_RINGTONE = CHILD_MENU_BASE;
72 private boolean mOneShot = false;
73 private boolean mSeeking = false;
74 private boolean mDeviceHasDpad;
75 private long mStartSeekPos = 0;
76 private long mLastSeekEventTime;
77 private IMediaPlaybackService mService = null;
78 private RepeatingImageButton mPrevButton;
79 private ImageButton mPauseButton;
80 private RepeatingImageButton mNextButton;
81 private ImageButton mRepeatButton;
82 private ImageButton mShuffleButton;
83 private ImageButton mQueueButton;
84 private Worker mAlbumArtWorker;
85 private AlbumArtHandler mAlbumArtHandler;
87 private int mTouchSlop;
88 private ServiceToken mToken;
90 public MediaPlaybackActivity()
94 /** Called when the activity is first created. */
96 public void onCreate(Bundle icicle)
98 super.onCreate(icicle);
99 setVolumeControlStream(AudioManager.STREAM_MUSIC);
101 mAlbumArtWorker = new Worker("album art worker");
102 mAlbumArtHandler = new AlbumArtHandler(mAlbumArtWorker.getLooper());
104 requestWindowFeature(Window.FEATURE_NO_TITLE);
105 setContentView(R.layout.audio_player);
107 mCurrentTime = (TextView) findViewById(R.id.currenttime);
108 mTotalTime = (TextView) findViewById(R.id.totaltime);
109 mProgress = (ProgressBar) findViewById(android.R.id.progress);
110 mAlbum = (ImageView) findViewById(R.id.album);
111 mArtistName = (TextView) findViewById(R.id.artistname);
112 mAlbumName = (TextView) findViewById(R.id.albumname);
113 mTrackName = (TextView) findViewById(R.id.trackname);
115 View v = (View)mArtistName.getParent();
116 v.setOnTouchListener(this);
117 v.setOnLongClickListener(this);
119 v = (View)mAlbumName.getParent();
120 v.setOnTouchListener(this);
121 v.setOnLongClickListener(this);
123 v = (View)mTrackName.getParent();
124 v.setOnTouchListener(this);
125 v.setOnLongClickListener(this);
127 mPrevButton = (RepeatingImageButton) findViewById(R.id.prev);
128 mPrevButton.setOnClickListener(mPrevListener);
129 mPrevButton.setRepeatListener(mRewListener, 260);
130 mPauseButton = (ImageButton) findViewById(R.id.pause);
131 mPauseButton.requestFocus();
132 mPauseButton.setOnClickListener(mPauseListener);
133 mNextButton = (RepeatingImageButton) findViewById(R.id.next);
134 mNextButton.setOnClickListener(mNextListener);
135 mNextButton.setRepeatListener(mFfwdListener, 260);
138 mDeviceHasDpad = (getResources().getConfiguration().navigation ==
139 Configuration.NAVIGATION_DPAD);
141 mQueueButton = (ImageButton) findViewById(R.id.curplaylist);
142 mQueueButton.setOnClickListener(mQueueListener);
143 mShuffleButton = ((ImageButton) findViewById(R.id.shuffle));
144 mShuffleButton.setOnClickListener(mShuffleListener);
145 mRepeatButton = ((ImageButton) findViewById(R.id.repeat));
146 mRepeatButton.setOnClickListener(mRepeatListener);
148 if (mProgress instanceof SeekBar) {
149 SeekBar seeker = (SeekBar) mProgress;
150 seeker.setOnSeekBarChangeListener(mSeekListener);
152 mProgress.setMax(1000);
154 if (icicle != null) {
155 mOneShot = icicle.getBoolean("oneshot");
157 mOneShot = getIntent().getBooleanExtra("oneshot", false);
160 mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();
167 boolean mDraggingLabel = false;
169 TextView textViewForContainer(View v) {
170 View vv = v.findViewById(R.id.artistname);
171 if (vv != null) return (TextView) vv;
172 vv = v.findViewById(R.id.albumname);
173 if (vv != null) return (TextView) vv;
174 vv = v.findViewById(R.id.trackname);
175 if (vv != null) return (TextView) vv;
179 public boolean onTouch(View v, MotionEvent event) {
180 int action = event.getAction();
181 TextView tv = textViewForContainer(v);
185 if (action == MotionEvent.ACTION_DOWN) {
186 v.setBackgroundColor(0xff606060);
187 mInitialX = mLastX = (int) event.getX();
188 mDraggingLabel = false;
189 } else if (action == MotionEvent.ACTION_UP ||
190 action == MotionEvent.ACTION_CANCEL) {
191 v.setBackgroundColor(0);
192 if (mDraggingLabel) {
193 Message msg = mLabelScroller.obtainMessage(0, tv);
194 mLabelScroller.sendMessageDelayed(msg, 1000);
196 } else if (action == MotionEvent.ACTION_MOVE) {
197 if (mDraggingLabel) {
198 int scrollx = tv.getScrollX();
199 int x = (int) event.getX();
200 int delta = mLastX - x;
204 if (scrollx > mTextWidth) {
205 // scrolled the text completely off the view to the left
206 scrollx -= mTextWidth;
207 scrollx -= mViewWidth;
209 if (scrollx < -mViewWidth) {
210 // scrolled the text completely off the view to the right
211 scrollx += mViewWidth;
212 scrollx += mTextWidth;
214 tv.scrollTo(scrollx, 0);
218 int delta = mInitialX - (int) event.getX();
219 if (Math.abs(delta) > mTouchSlop) {
221 mLabelScroller.removeMessages(0, tv);
223 // Only turn ellipsizing off when it's not already off, because it
224 // causes the scroll position to be reset to 0.
225 if (tv.getEllipsize() != null) {
226 tv.setEllipsize(null);
228 Layout ll = tv.getLayout();
229 // layout might be null if the text just changed, or ellipsizing
230 // was just turned off
234 // get the non-ellipsized line width, to determine whether scrolling
235 // should even be allowed
236 mTextWidth = (int) tv.getLayout().getLineWidth(0);
237 mViewWidth = tv.getWidth();
238 if (mViewWidth > mTextWidth) {
239 tv.setEllipsize(TruncateAt.END);
243 mDraggingLabel = true;
244 tv.setHorizontalFadingEdgeEnabled(true);
252 Handler mLabelScroller = new Handler() {
254 public void handleMessage(Message msg) {
255 TextView tv = (TextView) msg.obj;
256 int x = tv.getScrollX();
260 tv.setEllipsize(TruncateAt.END);
262 Message newmsg = obtainMessage(0, tv);
263 mLabelScroller.sendMessageDelayed(newmsg, 15);
268 public boolean onLongClick(View view) {
270 CharSequence title = null;
279 artist = mService.getArtistName();
280 album = mService.getAlbumName();
281 song = mService.getTrackName();
282 audioid = mService.getAudioId();
283 } catch (RemoteException ex) {
285 } catch (NullPointerException ex) {
286 // we might not actually have the service yet
290 if (MediaStore.UNKNOWN_STRING.equals(album) &&
291 MediaStore.UNKNOWN_STRING.equals(artist) &&
293 song.startsWith("recording")) {
302 Cursor c = MusicUtils.query(this,
303 ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, audioid),
304 new String[] {MediaStore.Audio.Media.IS_MUSIC}, null, null, null);
305 boolean ismusic = true;
307 if (c.moveToFirst()) {
308 ismusic = c.getInt(0) != 0;
316 boolean knownartist =
317 (artist != null) && !MediaStore.UNKNOWN_STRING.equals(artist);
320 (album != null) && !MediaStore.UNKNOWN_STRING.equals(album);
322 if (knownartist && view.equals(mArtistName.getParent())) {
325 mime = MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE;
326 } else if (knownalbum && view.equals(mAlbumName.getParent())) {
329 query = artist + " " + album;
333 mime = MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE;
334 } else if (view.equals(mTrackName.getParent()) || !knownartist || !knownalbum) {
335 if ((song == null) || MediaStore.UNKNOWN_STRING.equals(song)) {
336 // A popup of the form "Search for null/'' using ..." is pretty
337 // unhelpful, plus, we won't find any way to buy it anyway.
343 query = artist + " " + song;
347 mime = "audio/*"; // the specific type doesn't matter, so don't bother retrieving it
349 throw new RuntimeException("shouldn't be here");
351 title = getString(R.string.mediasearch, title);
353 Intent i = new Intent();
354 i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
355 i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH);
356 i.putExtra(SearchManager.QUERY, query);
358 i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist);
361 i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, album);
363 i.putExtra(MediaStore.EXTRA_MEDIA_TITLE, song);
364 i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, mime);
366 startActivity(Intent.createChooser(i, title));
370 private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
371 public void onStartTrackingTouch(SeekBar bar) {
372 mLastSeekEventTime = 0;
375 public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
376 if (!fromuser || (mService == null)) return;
377 long now = SystemClock.elapsedRealtime();
378 if ((now - mLastSeekEventTime) > 250) {
379 mLastSeekEventTime = now;
380 mPosOverride = mDuration * progress / 1000;
382 mService.seek(mPosOverride);
383 } catch (RemoteException ex) {
386 // trackball event, allow progress updates
393 public void onStopTrackingTouch(SeekBar bar) {
399 private View.OnClickListener mQueueListener = new View.OnClickListener() {
400 public void onClick(View v) {
402 new Intent(Intent.ACTION_EDIT)
403 .setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track")
404 .putExtra("playlist", "nowplaying")
409 private View.OnClickListener mShuffleListener = new View.OnClickListener() {
410 public void onClick(View v) {
415 private View.OnClickListener mRepeatListener = new View.OnClickListener() {
416 public void onClick(View v) {
421 private View.OnClickListener mPauseListener = new View.OnClickListener() {
422 public void onClick(View v) {
427 private View.OnClickListener mPrevListener = new View.OnClickListener() {
428 public void onClick(View v) {
429 if (mService == null) return;
431 if (mService.position() < 2000) {
437 } catch (RemoteException ex) {
442 private View.OnClickListener mNextListener = new View.OnClickListener() {
443 public void onClick(View v) {
444 if (mService == null) return;
447 } catch (RemoteException ex) {
452 private RepeatingImageButton.RepeatListener mRewListener =
453 new RepeatingImageButton.RepeatListener() {
454 public void onRepeat(View v, long howlong, int repcnt) {
455 scanBackward(repcnt, howlong);
459 private RepeatingImageButton.RepeatListener mFfwdListener =
460 new RepeatingImageButton.RepeatListener() {
461 public void onRepeat(View v, long howlong, int repcnt) {
462 scanForward(repcnt, howlong);
467 public void onStop() {
469 if (mService != null && mOneShot && getChangingConfigurations() == 0) {
472 } catch (RemoteException ex) {
475 mHandler.removeMessages(REFRESH);
476 unregisterReceiver(mStatusListener);
477 MusicUtils.unbindFromService(mToken);
483 public void onSaveInstanceState(Bundle outState) {
484 outState.putBoolean("oneshot", mOneShot);
485 super.onSaveInstanceState(outState);
489 public void onStart() {
493 mToken = MusicUtils.bindToService(this, osc);
494 if (mToken == null) {
495 // something went wrong
496 mHandler.sendEmptyMessage(QUIT);
499 IntentFilter f = new IntentFilter();
500 f.addAction(MediaPlaybackService.PLAYSTATE_CHANGED);
501 f.addAction(MediaPlaybackService.META_CHANGED);
502 f.addAction(MediaPlaybackService.PLAYBACK_COMPLETE);
503 registerReceiver(mStatusListener, new IntentFilter(f));
505 long next = refreshNow();
506 queueNextRefresh(next);
510 public void onNewIntent(Intent intent) {
512 mOneShot = intent.getBooleanExtra("oneshot", false);
516 public void onResume() {
519 setPauseButtonImage();
523 public void onDestroy()
525 mAlbumArtWorker.quit();
527 //System.out.println("***************** playback activity onDestroy\n");
531 public boolean onCreateOptionsMenu(Menu menu) {
532 super.onCreateOptionsMenu(menu);
533 // Don't show the menu items if we got launched by path/filedescriptor, or
534 // if we're in one shot mode. In most cases, these menu items are not
535 // useful in those modes, so for consistency we never show them in these
536 // modes, instead of tailoring them to the specific file being played.
537 if (MusicUtils.getCurrentAudioId() >= 0 && !mOneShot) {
538 menu.add(0, GOTO_START, 0, R.string.goto_start).setIcon(R.drawable.ic_menu_music_library);
539 menu.add(0, PARTY_SHUFFLE, 0, R.string.party_shuffle); // icon will be set in onPrepareOptionsMenu()
540 SubMenu sub = menu.addSubMenu(0, ADD_TO_PLAYLIST, 0,
541 R.string.add_to_playlist).setIcon(android.R.drawable.ic_menu_add);
542 // these next two are in a separate group, so they can be shown/hidden as needed
543 // based on the keyguard state
544 menu.add(1, USE_AS_RINGTONE, 0, R.string.ringtone_menu_short)
545 .setIcon(R.drawable.ic_menu_set_as_ringtone);
546 menu.add(1, DELETE_ITEM, 0, R.string.delete_item)
547 .setIcon(R.drawable.ic_menu_delete);
554 public boolean onPrepareOptionsMenu(Menu menu) {
555 MenuItem item = menu.findItem(PARTY_SHUFFLE);
557 int shuffle = MusicUtils.getCurrentShuffleMode();
558 if (shuffle == MediaPlaybackService.SHUFFLE_AUTO) {
559 item.setIcon(R.drawable.ic_menu_party_shuffle);
560 item.setTitle(R.string.party_shuffle_off);
562 item.setIcon(R.drawable.ic_menu_party_shuffle);
563 item.setTitle(R.string.party_shuffle);
567 item = menu.findItem(ADD_TO_PLAYLIST);
569 SubMenu sub = item.getSubMenu();
570 MusicUtils.makePlaylistMenu(this, sub);
573 KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
574 menu.setGroupVisible(1, !km.inKeyguardRestrictedInputMode());
580 public boolean onOptionsItemSelected(MenuItem item) {
583 switch (item.getItemId()) {
585 intent = new Intent();
586 intent.setClass(this, MusicBrowserActivity.class);
587 startActivity(intent);
590 case USE_AS_RINGTONE: {
591 // Set the system setting to make this the current ringtone
592 if (mService != null) {
593 MusicUtils.setRingtone(this, mService.getAudioId());
598 MusicUtils.togglePartyShuffle();
599 setShuffleButtonImage();
603 intent = new Intent();
604 intent.setClass(this, CreatePlaylist.class);
605 startActivityForResult(intent, NEW_PLAYLIST);
609 case PLAYLIST_SELECTED: {
610 long [] list = new long[1];
611 list[0] = MusicUtils.getCurrentAudioId();
612 long playlist = item.getIntent().getLongExtra("playlist", 0);
613 MusicUtils.addToPlaylist(this, list, playlist);
618 if (mService != null) {
619 long [] list = new long[1];
620 list[0] = MusicUtils.getCurrentAudioId();
621 Bundle b = new Bundle();
622 b.putString("description", getString(R.string.delete_song_desc,
623 mService.getTrackName()));
624 b.putLongArray("items", list);
625 intent = new Intent();
626 intent.setClass(this, DeleteItems.class);
628 startActivityForResult(intent, -1);
633 } catch (RemoteException ex) {
635 return super.onOptionsItemSelected(item);
639 protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
640 if (resultCode != RESULT_OK) {
643 switch (requestCode) {
645 Uri uri = intent.getData();
647 long [] list = new long[1];
648 list[0] = MusicUtils.getCurrentAudioId();
649 int playlist = Integer.parseInt(uri.getLastPathSegment());
650 MusicUtils.addToPlaylist(this, list, playlist);
655 private final int keyboard[][] = {
678 KeyEvent.KEYCODE_DEL,
688 KeyEvent.KEYCODE_COMMA,
689 KeyEvent.KEYCODE_PERIOD,
690 KeyEvent.KEYCODE_ENTER
698 private boolean seekMethod1(int keyCode)
700 if (mService == null) return false;
701 for(int x=0;x<10;x++) {
702 for(int y=0;y<3;y++) {
703 if(keyboard[y][x] == keyCode) {
706 if(x == lastX && y == lastY) dir = 0;
707 else if (y == 0 && lastY == 0 && x > lastX) dir = 1;
708 else if (y == 0 && lastY == 0 && x < lastX) dir = -1;
710 else if (y == 2 && lastY == 2 && x > lastX) dir = -1;
711 else if (y == 2 && lastY == 2 && x < lastX) dir = 1;
713 else if (y < lastY && x <= 4) dir = 1;
714 else if (y < lastY && x >= 5) dir = -1;
716 else if (y > lastY && x <= 4) dir = -1;
717 else if (y > lastY && x >= 5) dir = 1;
721 mService.seek(mService.position() + dir * 5);
722 } catch (RemoteException ex) {
734 private boolean seekMethod2(int keyCode)
736 if (mService == null) return false;
737 for(int i=0;i<10;i++) {
738 if(keyboard[0][i] == keyCode) {
739 int seekpercentage = 100*i/10;
741 mService.seek(mService.duration() * seekpercentage / 100);
742 } catch (RemoteException ex) {
752 public boolean onKeyUp(int keyCode, KeyEvent event) {
756 case KeyEvent.KEYCODE_DPAD_LEFT:
757 if (!useDpadMusicControl()) {
760 if (mService != null) {
761 if (!mSeeking && mStartSeekPos >= 0) {
762 mPauseButton.requestFocus();
763 if (mStartSeekPos < 1000) {
769 scanBackward(-1, event.getEventTime() - event.getDownTime());
770 mPauseButton.requestFocus();
777 case KeyEvent.KEYCODE_DPAD_RIGHT:
778 if (!useDpadMusicControl()) {
781 if (mService != null) {
782 if (!mSeeking && mStartSeekPos >= 0) {
783 mPauseButton.requestFocus();
786 scanForward(-1, event.getEventTime() - event.getDownTime());
787 mPauseButton.requestFocus();
795 } catch (RemoteException ex) {
797 return super.onKeyUp(keyCode, event);
800 private boolean useDpadMusicControl() {
801 if (mDeviceHasDpad && (mPrevButton.isFocused() ||
802 mNextButton.isFocused() ||
803 mPauseButton.isFocused())) {
810 public boolean onKeyDown(int keyCode, KeyEvent event)
813 int repcnt = event.getRepeatCount();
815 if((seekmethod==0)?seekMethod1(keyCode):seekMethod2(keyCode))
822 case KeyEvent.KEYCODE_Q: av.adjustParams(-0.05, 0.0, 0.0, 0.0, 0.0,-1.0); break;
823 case KeyEvent.KEYCODE_E: av.adjustParams( 0.05, 0.0, 0.0, 0.0, 0.0, 1.0); break;
825 case KeyEvent.KEYCODE_W: av.adjustParams( 0.0, 0.0,-1.0, 0.0, 0.0, 0.0); break;
826 case KeyEvent.KEYCODE_X: av.adjustParams( 0.0, 0.0, 1.0, 0.0, 0.0, 0.0); break;
827 case KeyEvent.KEYCODE_A: av.adjustParams( 0.0,-1.0, 0.0, 0.0, 0.0, 0.0); break;
828 case KeyEvent.KEYCODE_D: av.adjustParams( 0.0, 1.0, 0.0, 0.0, 0.0, 0.0); break;
830 case KeyEvent.KEYCODE_R: av.adjustParams( 0.0, 0.0, 0.0, 0.0, 0.0,-1.0); break;
831 case KeyEvent.KEYCODE_U: av.adjustParams( 0.0, 0.0, 0.0, 0.0, 0.0, 1.0); break;
833 case KeyEvent.KEYCODE_Y: av.adjustParams( 0.0, 0.0, 0.0, 0.0,-1.0, 0.0); break;
834 case KeyEvent.KEYCODE_N: av.adjustParams( 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); break;
835 case KeyEvent.KEYCODE_G: av.adjustParams( 0.0, 0.0, 0.0,-1.0, 0.0, 0.0); break;
836 case KeyEvent.KEYCODE_J: av.adjustParams( 0.0, 0.0, 0.0, 1.0, 0.0, 0.0); break;
840 case KeyEvent.KEYCODE_SLASH:
841 seekmethod = 1 - seekmethod;
844 case KeyEvent.KEYCODE_DPAD_LEFT:
845 if (!useDpadMusicControl()) {
848 if (!mPrevButton.hasFocus()) {
849 mPrevButton.requestFocus();
851 scanBackward(repcnt, event.getEventTime() - event.getDownTime());
853 case KeyEvent.KEYCODE_DPAD_RIGHT:
854 if (!useDpadMusicControl()) {
857 if (!mNextButton.hasFocus()) {
858 mNextButton.requestFocus();
860 scanForward(repcnt, event.getEventTime() - event.getDownTime());
863 case KeyEvent.KEYCODE_S:
867 case KeyEvent.KEYCODE_DPAD_CENTER:
868 case KeyEvent.KEYCODE_SPACE:
872 return super.onKeyDown(keyCode, event);
875 private void scanBackward(int repcnt, long delta) {
876 if(mService == null) return;
879 mStartSeekPos = mService.position();
880 mLastSeekEventTime = 0;
885 // seek at 10x speed for the first 5 seconds
888 // seek at 40x after that
889 delta = 50000 + (delta - 5000) * 40;
891 long newpos = mStartSeekPos - delta;
893 // move to previous track
895 long duration = mService.duration();
896 mStartSeekPos += duration;
899 if (((delta - mLastSeekEventTime) > 250) || repcnt < 0){
900 mService.seek(newpos);
901 mLastSeekEventTime = delta;
904 mPosOverride = newpos;
910 } catch (RemoteException ex) {
914 private void scanForward(int repcnt, long delta) {
915 if(mService == null) return;
918 mStartSeekPos = mService.position();
919 mLastSeekEventTime = 0;
924 // seek at 10x speed for the first 5 seconds
927 // seek at 40x after that
928 delta = 50000 + (delta - 5000) * 40;
930 long newpos = mStartSeekPos + delta;
931 long duration = mService.duration();
932 if (newpos >= duration) {
933 // move to next track
935 mStartSeekPos -= duration; // is OK to go negative
938 if (((delta - mLastSeekEventTime) > 250) || repcnt < 0){
939 mService.seek(newpos);
940 mLastSeekEventTime = delta;
943 mPosOverride = newpos;
949 } catch (RemoteException ex) {
953 private void doPauseResume() {
955 if(mService != null) {
956 if (mService.isPlaying()) {
962 setPauseButtonImage();
964 } catch (RemoteException ex) {
968 private void toggleShuffle() {
969 if (mService == null) {
973 int shuffle = mService.getShuffleMode();
974 if (shuffle == MediaPlaybackService.SHUFFLE_NONE) {
975 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NORMAL);
976 if (mService.getRepeatMode() == MediaPlaybackService.REPEAT_CURRENT) {
977 mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
978 setRepeatButtonImage();
980 showToast(R.string.shuffle_on_notif);
981 } else if (shuffle == MediaPlaybackService.SHUFFLE_NORMAL ||
982 shuffle == MediaPlaybackService.SHUFFLE_AUTO) {
983 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
984 showToast(R.string.shuffle_off_notif);
986 Log.e("MediaPlaybackActivity", "Invalid shuffle mode: " + shuffle);
988 setShuffleButtonImage();
989 } catch (RemoteException ex) {
993 private void cycleRepeat() {
994 if (mService == null) {
998 int mode = mService.getRepeatMode();
999 if (mode == MediaPlaybackService.REPEAT_NONE) {
1000 mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
1001 showToast(R.string.repeat_all_notif);
1002 } else if (mode == MediaPlaybackService.REPEAT_ALL) {
1003 mService.setRepeatMode(MediaPlaybackService.REPEAT_CURRENT);
1004 if (mService.getShuffleMode() != MediaPlaybackService.SHUFFLE_NONE) {
1005 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
1006 setShuffleButtonImage();
1008 showToast(R.string.repeat_current_notif);
1010 mService.setRepeatMode(MediaPlaybackService.REPEAT_NONE);
1011 showToast(R.string.repeat_off_notif);
1013 setRepeatButtonImage();
1014 } catch (RemoteException ex) {
1019 private void showToast(int resid) {
1020 if (mToast == null) {
1021 mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
1023 mToast.setText(resid);
1027 private void startPlayback() {
1029 if(mService == null)
1031 Intent intent = getIntent();
1032 String filename = "";
1033 Uri uri = intent.getData();
1034 if (uri != null && uri.toString().length() > 0) {
1035 // If this is a file:// URI, just use the path directly instead
1036 // of going through the open-from-filedescriptor codepath.
1037 String scheme = uri.getScheme();
1038 if ("file".equals(scheme)) {
1039 filename = uri.getPath();
1041 filename = uri.toString();
1044 if (! ContentResolver.SCHEME_CONTENT.equals(scheme) ||
1045 ! MediaStore.AUTHORITY.equals(uri.getAuthority())) {
1049 mService.openFile(filename, mOneShot);
1051 setIntent(new Intent());
1052 } catch (Exception ex) {
1053 Log.d("MediaPlaybackActivity", "couldn't start playback: " + ex);
1058 long next = refreshNow();
1059 queueNextRefresh(next);
1062 private ServiceConnection osc = new ServiceConnection() {
1063 public void onServiceConnected(ComponentName classname, IBinder obj) {
1064 mService = IMediaPlaybackService.Stub.asInterface(obj);
1067 // Assume something is playing when the service says it is,
1068 // but also if the audio ID is valid but the service is paused.
1069 if (mService.getAudioId() >= 0 || mService.isPlaying() ||
1070 mService.getPath() != null) {
1071 // something is playing now, we're done
1072 if (mOneShot || mService.getAudioId() < 0) {
1073 mRepeatButton.setVisibility(View.INVISIBLE);
1074 mShuffleButton.setVisibility(View.INVISIBLE);
1075 mQueueButton.setVisibility(View.INVISIBLE);
1077 mRepeatButton.setVisibility(View.VISIBLE);
1078 mShuffleButton.setVisibility(View.VISIBLE);
1079 mQueueButton.setVisibility(View.VISIBLE);
1080 setRepeatButtonImage();
1081 setShuffleButtonImage();
1083 setPauseButtonImage();
1086 } catch (RemoteException ex) {
1088 // Service is dead or not playing anything. If we got here as part
1089 // of a "play this file" Intent, exit. Otherwise go to the Music
1090 // app start screen.
1091 if (getIntent().getData() == null) {
1092 Intent intent = new Intent(Intent.ACTION_MAIN);
1093 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1094 intent.setClass(MediaPlaybackActivity.this, MusicBrowserActivity.class);
1095 startActivity(intent);
1099 public void onServiceDisconnected(ComponentName classname) {
1103 private void setRepeatButtonImage() {
1105 switch (mService.getRepeatMode()) {
1106 case MediaPlaybackService.REPEAT_ALL:
1107 mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_all_btn);
1109 case MediaPlaybackService.REPEAT_CURRENT:
1110 mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_once_btn);
1113 mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_off_btn);
1116 } catch (RemoteException ex) {
1120 private void setShuffleButtonImage() {
1122 switch (mService.getShuffleMode()) {
1123 case MediaPlaybackService.SHUFFLE_NONE:
1124 mShuffleButton.setImageResource(R.drawable.ic_mp_shuffle_off_btn);
1126 case MediaPlaybackService.SHUFFLE_AUTO:
1127 mShuffleButton.setImageResource(R.drawable.ic_mp_partyshuffle_on_btn);
1130 mShuffleButton.setImageResource(R.drawable.ic_mp_shuffle_on_btn);
1133 } catch (RemoteException ex) {
1137 private void setPauseButtonImage() {
1139 if (mService != null && mService.isPlaying()) {
1140 mPauseButton.setImageResource(android.R.drawable.ic_media_pause);
1142 mPauseButton.setImageResource(android.R.drawable.ic_media_play);
1144 } catch (RemoteException ex) {
1148 private ImageView mAlbum;
1149 private TextView mCurrentTime;
1150 private TextView mTotalTime;
1151 private TextView mArtistName;
1152 private TextView mAlbumName;
1153 private TextView mTrackName;
1154 private ProgressBar mProgress;
1155 private long mPosOverride = -1;
1156 private boolean mFromTouch = false;
1157 private long mDuration;
1158 private int seekmethod;
1159 private boolean paused;
1161 private static final int REFRESH = 1;
1162 private static final int QUIT = 2;
1163 private static final int GET_ALBUM_ART = 3;
1164 private static final int ALBUM_ART_DECODED = 4;
1166 private void queueNextRefresh(long delay) {
1168 Message msg = mHandler.obtainMessage(REFRESH);
1169 mHandler.removeMessages(REFRESH);
1170 mHandler.sendMessageDelayed(msg, delay);
1174 private long refreshNow() {
1175 if(mService == null)
1178 long pos = mPosOverride < 0 ? mService.position() : mPosOverride;
1179 long remaining = 1000 - (pos % 1000);
1180 if ((pos >= 0) && (mDuration > 0)) {
1181 mCurrentTime.setText(MusicUtils.makeTimeString(this, pos / 1000));
1183 if (mService.isPlaying()) {
1184 mCurrentTime.setVisibility(View.VISIBLE);
1186 // blink the counter
1187 int vis = mCurrentTime.getVisibility();
1188 mCurrentTime.setVisibility(vis == View.INVISIBLE ? View.VISIBLE : View.INVISIBLE);
1192 mProgress.setProgress((int) (1000 * pos / mDuration));
1194 mCurrentTime.setText("--:--");
1195 mProgress.setProgress(1000);
1197 // return the number of milliseconds until the next full second, so
1198 // the counter can be updated at just the right time
1200 } catch (RemoteException ex) {
1205 private final Handler mHandler = new Handler() {
1207 public void handleMessage(Message msg) {
1209 case ALBUM_ART_DECODED:
1210 mAlbum.setImageBitmap((Bitmap)msg.obj);
1211 mAlbum.getDrawable().setDither(true);
1215 long next = refreshNow();
1216 queueNextRefresh(next);
1220 // This can be moved back to onCreate once the bug that prevents
1221 // Dialogs from being started from onCreate/onResume is fixed.
1222 new AlertDialog.Builder(MediaPlaybackActivity.this)
1223 .setTitle(R.string.service_start_error_title)
1224 .setMessage(R.string.service_start_error_msg)
1225 .setPositiveButton(R.string.service_start_error_button,
1226 new DialogInterface.OnClickListener() {
1227 public void onClick(DialogInterface dialog, int whichButton) {
1231 .setCancelable(false)
1241 private BroadcastReceiver mStatusListener = new BroadcastReceiver() {
1243 public void onReceive(Context context, Intent intent) {
1244 String action = intent.getAction();
1245 if (action.equals(MediaPlaybackService.META_CHANGED)) {
1246 // redraw the artist/title info and
1247 // set new max for progress bar
1249 setPauseButtonImage();
1250 queueNextRefresh(1);
1251 } else if (action.equals(MediaPlaybackService.PLAYBACK_COMPLETE)) {
1255 setPauseButtonImage();
1257 } else if (action.equals(MediaPlaybackService.PLAYSTATE_CHANGED)) {
1258 setPauseButtonImage();
1263 private static class AlbumSongIdWrapper {
1264 public long albumid;
1266 AlbumSongIdWrapper(long aid, long sid) {
1272 private void updateTrackInfo() {
1273 if (mService == null) {
1277 String path = mService.getPath();
1283 long songid = mService.getAudioId();
1284 if (songid < 0 && path.toLowerCase().startsWith("http://")) {
1285 // Once we can get album art and meta data from MediaPlayer, we
1286 // can show that info again when streaming.
1287 ((View) mArtistName.getParent()).setVisibility(View.INVISIBLE);
1288 ((View) mAlbumName.getParent()).setVisibility(View.INVISIBLE);
1289 mAlbum.setVisibility(View.GONE);
1290 mTrackName.setText(path);
1291 mAlbumArtHandler.removeMessages(GET_ALBUM_ART);
1292 mAlbumArtHandler.obtainMessage(GET_ALBUM_ART, new AlbumSongIdWrapper(-1, -1)).sendToTarget();
1294 ((View) mArtistName.getParent()).setVisibility(View.VISIBLE);
1295 ((View) mAlbumName.getParent()).setVisibility(View.VISIBLE);
1296 String artistName = mService.getArtistName();
1297 if (MediaStore.UNKNOWN_STRING.equals(artistName)) {
1298 artistName = getString(R.string.unknown_artist_name);
1300 mArtistName.setText(artistName);
1301 String albumName = mService.getAlbumName();
1302 long albumid = mService.getAlbumId();
1303 if (MediaStore.UNKNOWN_STRING.equals(albumName)) {
1304 albumName = getString(R.string.unknown_album_name);
1307 mAlbumName.setText(albumName);
1308 mTrackName.setText(mService.getTrackName());
1309 mAlbumArtHandler.removeMessages(GET_ALBUM_ART);
1310 mAlbumArtHandler.obtainMessage(GET_ALBUM_ART, new AlbumSongIdWrapper(albumid, songid)).sendToTarget();
1311 mAlbum.setVisibility(View.VISIBLE);
1313 mDuration = mService.duration();
1314 mTotalTime.setText(MusicUtils.makeTimeString(this, mDuration / 1000));
1315 } catch (RemoteException ex) {
1320 public class AlbumArtHandler extends Handler {
1321 private long mAlbumId = -1;
1323 public AlbumArtHandler(Looper looper) {
1327 public void handleMessage(Message msg)
1329 long albumid = ((AlbumSongIdWrapper) msg.obj).albumid;
1330 long songid = ((AlbumSongIdWrapper) msg.obj).songid;
1331 if (msg.what == GET_ALBUM_ART && (mAlbumId != albumid || albumid < 0)) {
1332 // while decoding the new image, show the default album art
1333 Message numsg = mHandler.obtainMessage(ALBUM_ART_DECODED, null);
1334 mHandler.removeMessages(ALBUM_ART_DECODED);
1335 mHandler.sendMessageDelayed(numsg, 300);
1336 Bitmap bm = MusicUtils.getArtwork(MediaPlaybackActivity.this, songid, albumid);
1338 bm = MusicUtils.getArtwork(MediaPlaybackActivity.this, songid, -1);
1342 numsg = mHandler.obtainMessage(ALBUM_ART_DECODED, bm);
1343 mHandler.removeMessages(ALBUM_ART_DECODED);
1344 mHandler.sendMessage(numsg);
1351 private static class Worker implements Runnable {
1352 private final Object mLock = new Object();
1353 private Looper mLooper;
1356 * Creates a worker thread with the given name. The thread
1357 * then runs a {@link android.os.Looper}.
1358 * @param name A name for the new thread
1360 Worker(String name) {
1361 Thread t = new Thread(null, this, name);
1362 t.setPriority(Thread.MIN_PRIORITY);
1364 synchronized (mLock) {
1365 while (mLooper == null) {
1368 } catch (InterruptedException ex) {
1374 public Looper getLooper() {
1379 synchronized (mLock) {
1381 mLooper = Looper.myLooper();
1387 public void quit() {