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.KeyguardManager;
22 import android.app.SearchManager;
23 import android.content.BroadcastReceiver;
24 import android.content.ComponentName;
25 import android.content.ContentResolver;
26 import android.content.ContentUris;
27 import android.content.Context;
28 import android.content.DialogInterface;
29 import android.content.Intent;
30 import android.content.IntentFilter;
31 import android.content.ServiceConnection;
32 import android.content.res.Configuration;
33 import android.content.res.Resources;
34 import android.database.Cursor;
35 import android.graphics.Bitmap;
36 import android.media.AudioManager;
37 import android.media.MediaFile;
38 import android.net.Uri;
39 import android.os.Bundle;
40 import android.os.RemoteException;
41 import android.os.Handler;
42 import android.os.IBinder;
43 import android.os.Looper;
44 import android.os.Message;
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.view.WindowManager;
59 import android.widget.ImageButton;
60 import android.widget.ImageView;
61 import android.widget.ProgressBar;
62 import android.widget.SeekBar;
63 import android.widget.TextView;
64 import android.widget.Toast;
65 import android.widget.SeekBar.OnSeekBarChangeListener;
68 public class MediaPlaybackActivity extends Activity implements MusicUtils.Defs,
69 View.OnTouchListener, View.OnLongClickListener
71 private static final int USE_AS_RINGTONE = CHILD_MENU_BASE;
73 private boolean mOneShot = false;
74 private boolean mSeeking = false;
75 private boolean mDeviceHasDpad;
76 private long mStartSeekPos = 0;
77 private long mLastSeekEventTime;
78 private IMediaPlaybackService mService = null;
79 private RepeatingImageButton mPrevButton;
80 private ImageButton mPauseButton;
81 private RepeatingImageButton mNextButton;
82 private ImageButton mRepeatButton;
83 private ImageButton mShuffleButton;
84 private ImageButton mQueueButton;
85 private Worker mAlbumArtWorker;
86 private AlbumArtHandler mAlbumArtHandler;
88 private int mTouchSlop;
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 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
106 setContentView(R.layout.audio_player);
108 mCurrentTime = (TextView) findViewById(R.id.currenttime);
109 mTotalTime = (TextView) findViewById(R.id.totaltime);
110 mProgress = (ProgressBar) findViewById(android.R.id.progress);
111 mAlbum = (ImageView) findViewById(R.id.album);
112 mArtistName = (TextView) findViewById(R.id.artistname);
113 mAlbumName = (TextView) findViewById(R.id.albumname);
114 mTrackName = (TextView) findViewById(R.id.trackname);
116 View v = (View)mArtistName.getParent();
117 v.setOnTouchListener(this);
118 v.setOnLongClickListener(this);
120 v = (View)mAlbumName.getParent();
121 v.setOnTouchListener(this);
122 v.setOnLongClickListener(this);
124 v = (View)mTrackName.getParent();
125 v.setOnTouchListener(this);
126 v.setOnLongClickListener(this);
128 mPrevButton = (RepeatingImageButton) findViewById(R.id.prev);
129 mPrevButton.setOnClickListener(mPrevListener);
130 mPrevButton.setRepeatListener(mRewListener, 260);
131 mPauseButton = (ImageButton) findViewById(R.id.pause);
132 mPauseButton.requestFocus();
133 mPauseButton.setOnClickListener(mPauseListener);
134 mNextButton = (RepeatingImageButton) findViewById(R.id.next);
135 mNextButton.setOnClickListener(mNextListener);
136 mNextButton.setRepeatListener(mFfwdListener, 260);
139 mDeviceHasDpad = (getResources().getConfiguration().navigation ==
140 Configuration.NAVIGATION_DPAD);
142 mQueueButton = (ImageButton) findViewById(R.id.curplaylist);
143 mQueueButton.setOnClickListener(mQueueListener);
144 mShuffleButton = ((ImageButton) findViewById(R.id.shuffle));
145 mShuffleButton.setOnClickListener(mShuffleListener);
146 mRepeatButton = ((ImageButton) findViewById(R.id.repeat));
147 mRepeatButton.setOnClickListener(mRepeatListener);
149 if (mProgress instanceof SeekBar) {
150 SeekBar seeker = (SeekBar) mProgress;
151 seeker.setOnSeekBarChangeListener(mSeekListener);
153 mProgress.setMax(1000);
155 if (icicle != null) {
156 mOneShot = icicle.getBoolean("oneshot");
158 mOneShot = getIntent().getBooleanExtra("oneshot", false);
161 mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();
168 boolean mDraggingLabel = false;
170 TextView textViewForContainer(View v) {
171 View vv = v.findViewById(R.id.artistname);
172 if (vv != null) return (TextView) vv;
173 vv = v.findViewById(R.id.albumname);
174 if (vv != null) return (TextView) vv;
175 vv = v.findViewById(R.id.trackname);
176 if (vv != null) return (TextView) vv;
180 public boolean onTouch(View v, MotionEvent event) {
181 int action = event.getAction();
182 TextView tv = textViewForContainer(v);
186 if (action == MotionEvent.ACTION_DOWN) {
187 v.setBackgroundColor(0xff606060);
188 mInitialX = mLastX = (int) event.getX();
189 mDraggingLabel = false;
190 } else if (action == MotionEvent.ACTION_UP ||
191 action == MotionEvent.ACTION_CANCEL) {
192 v.setBackgroundColor(0);
193 if (mDraggingLabel) {
194 Message msg = mLabelScroller.obtainMessage(0, tv);
195 mLabelScroller.sendMessageDelayed(msg, 1000);
197 } else if (action == MotionEvent.ACTION_MOVE) {
198 if (mDraggingLabel) {
199 int scrollx = tv.getScrollX();
200 int x = (int) event.getX();
201 int delta = mLastX - x;
205 if (scrollx > mTextWidth) {
206 // scrolled the text completely off the view to the left
207 scrollx -= mTextWidth;
208 scrollx -= mViewWidth;
210 if (scrollx < -mViewWidth) {
211 // scrolled the text completely off the view to the right
212 scrollx += mViewWidth;
213 scrollx += mTextWidth;
215 tv.scrollTo(scrollx, 0);
219 int delta = mInitialX - (int) event.getX();
220 if (Math.abs(delta) > mTouchSlop) {
222 mLabelScroller.removeMessages(0, tv);
224 // Only turn ellipsizing off when it's not already off, because it
225 // causes the scroll position to be reset to 0.
226 if (tv.getEllipsize() != null) {
227 tv.setEllipsize(null);
229 Layout ll = tv.getLayout();
230 // layout might be null if the text just changed, or ellipsizing
231 // was just turned off
235 // get the non-ellipsized line width, to determine whether scrolling
236 // should even be allowed
237 mTextWidth = (int) tv.getLayout().getLineWidth(0);
238 mViewWidth = tv.getWidth();
239 if (mViewWidth > mTextWidth) {
240 tv.setEllipsize(TruncateAt.END);
244 mDraggingLabel = true;
245 tv.setHorizontalFadingEdgeEnabled(true);
253 Handler mLabelScroller = new Handler() {
255 public void handleMessage(Message msg) {
256 TextView tv = (TextView) msg.obj;
257 int x = tv.getScrollX();
261 tv.setEllipsize(TruncateAt.END);
263 Message newmsg = obtainMessage(0, tv);
264 mLabelScroller.sendMessageDelayed(newmsg, 15);
269 public boolean onLongClick(View view) {
271 CharSequence title = null;
280 artist = mService.getArtistName();
281 album = mService.getAlbumName();
282 song = mService.getTrackName();
283 audioid = mService.getAudioId();
284 } catch (RemoteException ex) {
288 if (MediaFile.UNKNOWN_STRING.equals(album) &&
289 MediaFile.UNKNOWN_STRING.equals(artist) &&
291 song.startsWith("recording")) {
300 Cursor c = MusicUtils.query(this,
301 ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, audioid),
302 new String[] {MediaStore.Audio.Media.IS_MUSIC}, null, null, null);
303 boolean ismusic = true;
305 if (c.moveToFirst()) {
306 ismusic = c.getInt(0) != 0;
314 boolean knownartist =
315 (artist != null) && !MediaFile.UNKNOWN_STRING.equals(artist);
318 (album != null) && !MediaFile.UNKNOWN_STRING.equals(album);
320 if (knownartist && view.equals(mArtistName.getParent())) {
323 mime = MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE;
324 } else if (knownalbum && view.equals(mAlbumName.getParent())) {
327 query = artist + " " + album;
331 mime = MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE;
332 } else if (view.equals(mTrackName.getParent()) || !knownartist || !knownalbum) {
333 if ((song == null) || MediaFile.UNKNOWN_STRING.equals(song)) {
334 // A popup of the form "Search for null/'' using ..." is pretty
335 // unhelpful, plus, we won't find any way to buy it anyway.
341 query = artist + " " + song;
345 mime = "audio/*"; // the specific type doesn't matter, so don't bother retrieving it
347 throw new RuntimeException("shouldn't be here");
349 title = getString(R.string.mediasearch, title);
351 Intent i = new Intent();
352 i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
353 i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH);
354 i.putExtra(SearchManager.QUERY, query);
356 i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist);
359 i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, album);
361 i.putExtra(MediaStore.EXTRA_MEDIA_TITLE, song);
362 i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, mime);
364 startActivity(Intent.createChooser(i, title));
368 private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
369 public void onStartTrackingTouch(SeekBar bar) {
370 mLastSeekEventTime = 0;
373 public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
374 if (!fromuser || (mService == null)) return;
375 long now = SystemClock.elapsedRealtime();
376 if ((now - mLastSeekEventTime) > 250) {
377 mLastSeekEventTime = now;
378 mPosOverride = mDuration * progress / 1000;
380 mService.seek(mPosOverride);
381 } catch (RemoteException ex) {
384 // trackball event, allow progress updates
391 public void onStopTrackingTouch(SeekBar bar) {
397 private View.OnClickListener mQueueListener = new View.OnClickListener() {
398 public void onClick(View v) {
400 new Intent(Intent.ACTION_EDIT)
401 .setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track")
402 .putExtra("playlist", "nowplaying")
407 private View.OnClickListener mShuffleListener = new View.OnClickListener() {
408 public void onClick(View v) {
413 private View.OnClickListener mRepeatListener = new View.OnClickListener() {
414 public void onClick(View v) {
419 private View.OnClickListener mPauseListener = new View.OnClickListener() {
420 public void onClick(View v) {
425 private View.OnClickListener mPrevListener = new View.OnClickListener() {
426 public void onClick(View v) {
427 if (mService == null) return;
429 if (mService.position() < 2000) {
435 } catch (RemoteException ex) {
440 private View.OnClickListener mNextListener = new View.OnClickListener() {
441 public void onClick(View v) {
442 if (mService == null) return;
445 } catch (RemoteException ex) {
450 private RepeatingImageButton.RepeatListener mRewListener =
451 new RepeatingImageButton.RepeatListener() {
452 public void onRepeat(View v, long howlong, int repcnt) {
453 scanBackward(repcnt, howlong);
457 private RepeatingImageButton.RepeatListener mFfwdListener =
458 new RepeatingImageButton.RepeatListener() {
459 public void onRepeat(View v, long howlong, int repcnt) {
460 scanForward(repcnt, howlong);
465 public void onStop() {
467 if (mService != null && mOneShot && getChangingConfigurations() == 0) {
470 } catch (RemoteException ex) {
473 mHandler.removeMessages(REFRESH);
474 unregisterReceiver(mStatusListener);
475 MusicUtils.unbindFromService(this);
481 public void onSaveInstanceState(Bundle outState) {
482 outState.putBoolean("oneshot", mOneShot);
483 super.onSaveInstanceState(outState);
487 public void onStart() {
491 if (false == MusicUtils.bindToService(this, osc)) {
492 // something went wrong
493 mHandler.sendEmptyMessage(QUIT);
496 IntentFilter f = new IntentFilter();
497 f.addAction(MediaPlaybackService.PLAYSTATE_CHANGED);
498 f.addAction(MediaPlaybackService.META_CHANGED);
499 f.addAction(MediaPlaybackService.PLAYBACK_COMPLETE);
500 registerReceiver(mStatusListener, new IntentFilter(f));
502 long next = refreshNow();
503 queueNextRefresh(next);
507 public void onNewIntent(Intent intent) {
509 mOneShot = intent.getBooleanExtra("oneshot", false);
513 public void onResume() {
516 setPauseButtonImage();
520 public void onDestroy()
522 mAlbumArtWorker.quit();
524 //System.out.println("***************** playback activity onDestroy\n");
528 public boolean onCreateOptionsMenu(Menu menu) {
529 super.onCreateOptionsMenu(menu);
530 // Don't show the menu items if we got launched by path/filedescriptor, or
531 // if we're in one shot mode. In most cases, these menu items are not
532 // useful in those modes, so for consistency we never show them in these
533 // modes, instead of tailoring them to the specific file being played.
534 if (MusicUtils.getCurrentAudioId() >= 0 && !mOneShot) {
535 menu.add(0, GOTO_START, 0, R.string.goto_start).setIcon(R.drawable.ic_menu_music_library);
536 menu.add(0, PARTY_SHUFFLE, 0, R.string.party_shuffle); // icon will be set in onPrepareOptionsMenu()
537 SubMenu sub = menu.addSubMenu(0, ADD_TO_PLAYLIST, 0,
538 R.string.add_to_playlist).setIcon(android.R.drawable.ic_menu_add);
539 MusicUtils.makePlaylistMenu(this, sub);
540 // these next two are in a separate group, so they can be shown/hidden as needed
541 // based on the keyguard state
542 menu.add(1, USE_AS_RINGTONE, 0, R.string.ringtone_menu_short)
543 .setIcon(R.drawable.ic_menu_set_as_ringtone);
544 menu.add(1, DELETE_ITEM, 0, R.string.delete_item)
545 .setIcon(R.drawable.ic_menu_delete);
552 public boolean onPrepareOptionsMenu(Menu menu) {
553 MenuItem item = menu.findItem(PARTY_SHUFFLE);
555 int shuffle = MusicUtils.getCurrentShuffleMode();
556 if (shuffle == MediaPlaybackService.SHUFFLE_AUTO) {
557 item.setIcon(R.drawable.ic_menu_party_shuffle);
558 item.setTitle(R.string.party_shuffle_off);
560 item.setIcon(R.drawable.ic_menu_party_shuffle);
561 item.setTitle(R.string.party_shuffle);
564 KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
565 menu.setGroupVisible(1, !km.inKeyguardRestrictedInputMode());
570 public boolean onOptionsItemSelected(MenuItem item) {
573 switch (item.getItemId()) {
575 intent = new Intent();
576 intent.setClass(this, MusicBrowserActivity.class);
577 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
578 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
579 startActivity(intent);
581 case USE_AS_RINGTONE: {
582 // Set the system setting to make this the current ringtone
583 if (mService != null) {
584 MusicUtils.setRingtone(this, mService.getAudioId());
589 if (mService != null) {
590 int shuffle = mService.getShuffleMode();
591 if (shuffle == MediaPlaybackService.SHUFFLE_AUTO) {
592 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
594 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_AUTO);
597 setShuffleButtonImage();
601 intent = new Intent();
602 intent.setClass(this, CreatePlaylist.class);
603 startActivityForResult(intent, NEW_PLAYLIST);
607 case PLAYLIST_SELECTED: {
608 long [] list = new long[1];
609 list[0] = MusicUtils.getCurrentAudioId();
610 long playlist = item.getIntent().getLongExtra("playlist", 0);
611 MusicUtils.addToPlaylist(this, list, playlist);
616 if (mService != null) {
617 long [] list = new long[1];
618 list[0] = MusicUtils.getCurrentAudioId();
619 Bundle b = new Bundle();
620 b.putString("description", getString(R.string.delete_song_desc,
621 mService.getTrackName()));
622 b.putLongArray("items", list);
623 intent = new Intent();
624 intent.setClass(this, DeleteItems.class);
626 startActivityForResult(intent, -1);
631 } catch (RemoteException ex) {
633 return super.onOptionsItemSelected(item);
637 protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
638 if (resultCode != RESULT_OK) {
641 switch (requestCode) {
643 Uri uri = intent.getData();
645 long [] list = new long[1];
646 list[0] = MusicUtils.getCurrentAudioId();
647 int playlist = Integer.parseInt(uri.getLastPathSegment());
648 MusicUtils.addToPlaylist(this, list, playlist);
653 private final int keyboard[][] = {
676 KeyEvent.KEYCODE_DEL,
686 KeyEvent.KEYCODE_COMMA,
687 KeyEvent.KEYCODE_PERIOD,
688 KeyEvent.KEYCODE_ENTER
696 private boolean seekMethod1(int keyCode)
698 for(int x=0;x<10;x++) {
699 for(int y=0;y<3;y++) {
700 if(keyboard[y][x] == keyCode) {
703 if(x == lastX && y == lastY) dir = 0;
704 else if (y == 0 && lastY == 0 && x > lastX) dir = 1;
705 else if (y == 0 && lastY == 0 && x < lastX) dir = -1;
707 else if (y == 2 && lastY == 2 && x > lastX) dir = -1;
708 else if (y == 2 && lastY == 2 && x < lastX) dir = 1;
710 else if (y < lastY && x <= 4) dir = 1;
711 else if (y < lastY && x >= 5) dir = -1;
713 else if (y > lastY && x <= 4) dir = -1;
714 else if (y > lastY && x >= 5) dir = 1;
718 mService.seek(mService.position() + dir * 5);
719 } catch (RemoteException ex) {
731 private boolean seekMethod2(int keyCode)
733 if (mService == null) return false;
734 for(int i=0;i<10;i++) {
735 if(keyboard[0][i] == keyCode) {
736 int seekpercentage = 100*i/10;
738 mService.seek(mService.duration() * seekpercentage / 100);
739 } catch (RemoteException ex) {
749 public boolean onKeyUp(int keyCode, KeyEvent event) {
753 case KeyEvent.KEYCODE_DPAD_LEFT:
754 if (!useDpadMusicControl()) {
757 if (mService != null) {
758 if (!mSeeking && mStartSeekPos >= 0) {
759 mPauseButton.requestFocus();
760 if (mStartSeekPos < 1000) {
766 scanBackward(-1, event.getEventTime() - event.getDownTime());
767 mPauseButton.requestFocus();
774 case KeyEvent.KEYCODE_DPAD_RIGHT:
775 if (!useDpadMusicControl()) {
778 if (mService != null) {
779 if (!mSeeking && mStartSeekPos >= 0) {
780 mPauseButton.requestFocus();
783 scanForward(-1, event.getEventTime() - event.getDownTime());
784 mPauseButton.requestFocus();
792 } catch (RemoteException ex) {
794 return super.onKeyUp(keyCode, event);
797 private boolean useDpadMusicControl() {
798 if (mDeviceHasDpad && (mPrevButton.isFocused() ||
799 mNextButton.isFocused() ||
800 mPauseButton.isFocused())) {
807 public boolean onKeyDown(int keyCode, KeyEvent event)
810 int repcnt = event.getRepeatCount();
812 if((seekmethod==0)?seekMethod1(keyCode):seekMethod2(keyCode))
819 case KeyEvent.KEYCODE_Q: av.adjustParams(-0.05, 0.0, 0.0, 0.0, 0.0,-1.0); break;
820 case KeyEvent.KEYCODE_E: av.adjustParams( 0.05, 0.0, 0.0, 0.0, 0.0, 1.0); break;
822 case KeyEvent.KEYCODE_W: av.adjustParams( 0.0, 0.0,-1.0, 0.0, 0.0, 0.0); break;
823 case KeyEvent.KEYCODE_X: av.adjustParams( 0.0, 0.0, 1.0, 0.0, 0.0, 0.0); break;
824 case KeyEvent.KEYCODE_A: av.adjustParams( 0.0,-1.0, 0.0, 0.0, 0.0, 0.0); break;
825 case KeyEvent.KEYCODE_D: av.adjustParams( 0.0, 1.0, 0.0, 0.0, 0.0, 0.0); break;
827 case KeyEvent.KEYCODE_R: av.adjustParams( 0.0, 0.0, 0.0, 0.0, 0.0,-1.0); break;
828 case KeyEvent.KEYCODE_U: av.adjustParams( 0.0, 0.0, 0.0, 0.0, 0.0, 1.0); break;
830 case KeyEvent.KEYCODE_Y: av.adjustParams( 0.0, 0.0, 0.0, 0.0,-1.0, 0.0); break;
831 case KeyEvent.KEYCODE_N: av.adjustParams( 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); break;
832 case KeyEvent.KEYCODE_G: av.adjustParams( 0.0, 0.0, 0.0,-1.0, 0.0, 0.0); break;
833 case KeyEvent.KEYCODE_J: av.adjustParams( 0.0, 0.0, 0.0, 1.0, 0.0, 0.0); break;
837 case KeyEvent.KEYCODE_SLASH:
838 seekmethod = 1 - seekmethod;
841 case KeyEvent.KEYCODE_DPAD_LEFT:
842 if (!useDpadMusicControl()) {
845 if (!mPrevButton.hasFocus()) {
846 mPrevButton.requestFocus();
848 scanBackward(repcnt, event.getEventTime() - event.getDownTime());
850 case KeyEvent.KEYCODE_DPAD_RIGHT:
851 if (!useDpadMusicControl()) {
854 if (!mNextButton.hasFocus()) {
855 mNextButton.requestFocus();
857 scanForward(repcnt, event.getEventTime() - event.getDownTime());
860 case KeyEvent.KEYCODE_S:
864 case KeyEvent.KEYCODE_DPAD_CENTER:
865 case KeyEvent.KEYCODE_SPACE:
869 return super.onKeyDown(keyCode, event);
872 private void scanBackward(int repcnt, long delta) {
873 if(mService == null) return;
876 mStartSeekPos = mService.position();
877 mLastSeekEventTime = 0;
882 // seek at 10x speed for the first 5 seconds
885 // seek at 40x after that
886 delta = 50000 + (delta - 5000) * 40;
888 long newpos = mStartSeekPos - delta;
890 // move to previous track
892 long duration = mService.duration();
893 mStartSeekPos += duration;
896 if (((delta - mLastSeekEventTime) > 250) || repcnt < 0){
897 mService.seek(newpos);
898 mLastSeekEventTime = delta;
901 mPosOverride = newpos;
907 } catch (RemoteException ex) {
911 private void scanForward(int repcnt, long delta) {
912 if(mService == null) return;
915 mStartSeekPos = mService.position();
916 mLastSeekEventTime = 0;
921 // seek at 10x speed for the first 5 seconds
924 // seek at 40x after that
925 delta = 50000 + (delta - 5000) * 40;
927 long newpos = mStartSeekPos + delta;
928 long duration = mService.duration();
929 if (newpos >= duration) {
930 // move to next track
932 mStartSeekPos -= duration; // is OK to go negative
935 if (((delta - mLastSeekEventTime) > 250) || repcnt < 0){
936 mService.seek(newpos);
937 mLastSeekEventTime = delta;
940 mPosOverride = newpos;
946 } catch (RemoteException ex) {
950 private void doPauseResume() {
952 if(mService != null) {
953 if (mService.isPlaying()) {
959 setPauseButtonImage();
961 } catch (RemoteException ex) {
965 private void toggleShuffle() {
966 if (mService == null) {
970 int shuffle = mService.getShuffleMode();
971 if (shuffle == MediaPlaybackService.SHUFFLE_NONE) {
972 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NORMAL);
973 if (mService.getRepeatMode() == MediaPlaybackService.REPEAT_CURRENT) {
974 mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
975 setRepeatButtonImage();
977 showToast(R.string.shuffle_on_notif);
978 } else if (shuffle == MediaPlaybackService.SHUFFLE_NORMAL ||
979 shuffle == MediaPlaybackService.SHUFFLE_AUTO) {
980 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
981 showToast(R.string.shuffle_off_notif);
983 Log.e("MediaPlaybackActivity", "Invalid shuffle mode: " + shuffle);
985 setShuffleButtonImage();
986 } catch (RemoteException ex) {
990 private void cycleRepeat() {
991 if (mService == null) {
995 int mode = mService.getRepeatMode();
996 if (mode == MediaPlaybackService.REPEAT_NONE) {
997 mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
998 showToast(R.string.repeat_all_notif);
999 } else if (mode == MediaPlaybackService.REPEAT_ALL) {
1000 mService.setRepeatMode(MediaPlaybackService.REPEAT_CURRENT);
1001 if (mService.getShuffleMode() != MediaPlaybackService.SHUFFLE_NONE) {
1002 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
1003 setShuffleButtonImage();
1005 showToast(R.string.repeat_current_notif);
1007 mService.setRepeatMode(MediaPlaybackService.REPEAT_NONE);
1008 showToast(R.string.repeat_off_notif);
1010 setRepeatButtonImage();
1011 } catch (RemoteException ex) {
1016 private void showToast(int resid) {
1017 if (mToast == null) {
1018 mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
1020 mToast.setText(resid);
1024 private void startPlayback() {
1026 if(mService == null)
1028 Intent intent = getIntent();
1029 String filename = "";
1030 Uri uri = intent.getData();
1031 if (uri != null && uri.toString().length() > 0) {
1032 // If this is a file:// URI, just use the path directly instead
1033 // of going through the open-from-filedescriptor codepath.
1034 String scheme = uri.getScheme();
1035 if ("file".equals(scheme)) {
1036 filename = uri.getPath();
1038 filename = uri.toString();
1041 if (! ContentResolver.SCHEME_CONTENT.equals(scheme) ||
1042 ! MediaStore.AUTHORITY.equals(uri.getAuthority())) {
1046 mService.openFile(filename, mOneShot);
1048 setIntent(new Intent());
1049 } catch (Exception ex) {
1050 Log.d("MediaPlaybackActivity", "couldn't start playback: " + ex);
1055 long next = refreshNow();
1056 queueNextRefresh(next);
1059 private ServiceConnection osc = new ServiceConnection() {
1060 public void onServiceConnected(ComponentName classname, IBinder obj) {
1061 mService = IMediaPlaybackService.Stub.asInterface(obj);
1064 // Assume something is playing when the service says it is,
1065 // but also if the audio ID is valid but the service is paused.
1066 if (mService.getAudioId() >= 0 || mService.isPlaying() ||
1067 mService.getPath() != null) {
1068 // something is playing now, we're done
1069 if (mOneShot || mService.getAudioId() < 0) {
1070 mRepeatButton.setVisibility(View.INVISIBLE);
1071 mShuffleButton.setVisibility(View.INVISIBLE);
1072 mQueueButton.setVisibility(View.INVISIBLE);
1074 mRepeatButton.setVisibility(View.VISIBLE);
1075 mShuffleButton.setVisibility(View.VISIBLE);
1076 mQueueButton.setVisibility(View.VISIBLE);
1077 setRepeatButtonImage();
1078 setShuffleButtonImage();
1080 setPauseButtonImage();
1083 } catch (RemoteException ex) {
1085 // Service is dead or not playing anything. If we got here as part
1086 // of a "play this file" Intent, exit. Otherwise go to the Music
1087 // app start screen.
1088 if (getIntent().getData() == null) {
1089 Intent intent = new Intent(Intent.ACTION_MAIN);
1090 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1091 intent.setClass(MediaPlaybackActivity.this, MusicBrowserActivity.class);
1092 startActivity(intent);
1096 public void onServiceDisconnected(ComponentName classname) {
1100 private void setRepeatButtonImage() {
1102 switch (mService.getRepeatMode()) {
1103 case MediaPlaybackService.REPEAT_ALL:
1104 mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_all_btn);
1106 case MediaPlaybackService.REPEAT_CURRENT:
1107 mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_once_btn);
1110 mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_off_btn);
1113 } catch (RemoteException ex) {
1117 private void setShuffleButtonImage() {
1119 switch (mService.getShuffleMode()) {
1120 case MediaPlaybackService.SHUFFLE_NONE:
1121 mShuffleButton.setImageResource(R.drawable.ic_mp_shuffle_off_btn);
1123 case MediaPlaybackService.SHUFFLE_AUTO:
1124 mShuffleButton.setImageResource(R.drawable.ic_mp_partyshuffle_on_btn);
1127 mShuffleButton.setImageResource(R.drawable.ic_mp_shuffle_on_btn);
1130 } catch (RemoteException ex) {
1134 private void setPauseButtonImage() {
1136 if (mService != null && mService.isPlaying()) {
1137 mPauseButton.setImageResource(android.R.drawable.ic_media_pause);
1139 mPauseButton.setImageResource(android.R.drawable.ic_media_play);
1141 } catch (RemoteException ex) {
1145 private ImageView mAlbum;
1146 private TextView mCurrentTime;
1147 private TextView mTotalTime;
1148 private TextView mArtistName;
1149 private TextView mAlbumName;
1150 private TextView mTrackName;
1151 private ProgressBar mProgress;
1152 private long mPosOverride = -1;
1153 private boolean mFromTouch = false;
1154 private long mDuration;
1155 private int seekmethod;
1156 private boolean paused;
1158 private static final int REFRESH = 1;
1159 private static final int QUIT = 2;
1160 private static final int GET_ALBUM_ART = 3;
1161 private static final int ALBUM_ART_DECODED = 4;
1163 private void queueNextRefresh(long delay) {
1165 Message msg = mHandler.obtainMessage(REFRESH);
1166 mHandler.removeMessages(REFRESH);
1167 mHandler.sendMessageDelayed(msg, delay);
1171 private long refreshNow() {
1172 if(mService == null)
1175 long pos = mPosOverride < 0 ? mService.position() : mPosOverride;
1176 long remaining = 1000 - (pos % 1000);
1177 if ((pos >= 0) && (mDuration > 0)) {
1178 mCurrentTime.setText(MusicUtils.makeTimeString(this, pos / 1000));
1180 if (mService.isPlaying()) {
1181 mCurrentTime.setVisibility(View.VISIBLE);
1183 // blink the counter
1184 int vis = mCurrentTime.getVisibility();
1185 mCurrentTime.setVisibility(vis == View.INVISIBLE ? View.VISIBLE : View.INVISIBLE);
1189 mProgress.setProgress((int) (1000 * pos / mDuration));
1191 mCurrentTime.setText("--:--");
1192 mProgress.setProgress(1000);
1194 // return the number of milliseconds until the next full second, so
1195 // the counter can be updated at just the right time
1197 } catch (RemoteException ex) {
1202 private final Handler mHandler = new Handler() {
1204 public void handleMessage(Message msg) {
1206 case ALBUM_ART_DECODED:
1207 mAlbum.setImageBitmap((Bitmap)msg.obj);
1208 mAlbum.getDrawable().setDither(true);
1212 long next = refreshNow();
1213 queueNextRefresh(next);
1217 // This can be moved back to onCreate once the bug that prevents
1218 // Dialogs from being started from onCreate/onResume is fixed.
1219 new AlertDialog.Builder(MediaPlaybackActivity.this)
1220 .setTitle(R.string.service_start_error_title)
1221 .setMessage(R.string.service_start_error_msg)
1222 .setPositiveButton(R.string.service_start_error_button,
1223 new DialogInterface.OnClickListener() {
1224 public void onClick(DialogInterface dialog, int whichButton) {
1228 .setCancelable(false)
1238 private BroadcastReceiver mStatusListener = new BroadcastReceiver() {
1240 public void onReceive(Context context, Intent intent) {
1241 String action = intent.getAction();
1242 if (action.equals(MediaPlaybackService.META_CHANGED)) {
1243 // redraw the artist/title info and
1244 // set new max for progress bar
1246 setPauseButtonImage();
1247 queueNextRefresh(1);
1248 } else if (action.equals(MediaPlaybackService.PLAYBACK_COMPLETE)) {
1252 setPauseButtonImage();
1254 } else if (action.equals(MediaPlaybackService.PLAYSTATE_CHANGED)) {
1255 setPauseButtonImage();
1260 private static class AlbumSongIdWrapper {
1261 public long albumid;
1263 AlbumSongIdWrapper(long aid, long sid) {
1269 private void updateTrackInfo() {
1270 if (mService == null) {
1274 String path = mService.getPath();
1280 long songid = mService.getAudioId();
1281 if (songid < 0 && path.toLowerCase().startsWith("http://")) {
1282 // Once we can get album art and meta data from MediaPlayer, we
1283 // can show that info again when streaming.
1284 ((View) mArtistName.getParent()).setVisibility(View.INVISIBLE);
1285 ((View) mAlbumName.getParent()).setVisibility(View.INVISIBLE);
1286 mAlbum.setVisibility(View.GONE);
1287 mTrackName.setText(path);
1288 mAlbumArtHandler.removeMessages(GET_ALBUM_ART);
1289 mAlbumArtHandler.obtainMessage(GET_ALBUM_ART, new AlbumSongIdWrapper(-1, -1)).sendToTarget();
1291 ((View) mArtistName.getParent()).setVisibility(View.VISIBLE);
1292 ((View) mAlbumName.getParent()).setVisibility(View.VISIBLE);
1293 String artistName = mService.getArtistName();
1294 if (MediaFile.UNKNOWN_STRING.equals(artistName)) {
1295 artistName = getString(R.string.unknown_artist_name);
1297 mArtistName.setText(artistName);
1298 String albumName = mService.getAlbumName();
1299 long albumid = mService.getAlbumId();
1300 if (MediaFile.UNKNOWN_STRING.equals(albumName)) {
1301 albumName = getString(R.string.unknown_album_name);
1304 mAlbumName.setText(albumName);
1305 mTrackName.setText(mService.getTrackName());
1306 mAlbumArtHandler.removeMessages(GET_ALBUM_ART);
1307 mAlbumArtHandler.obtainMessage(GET_ALBUM_ART, new AlbumSongIdWrapper(albumid, songid)).sendToTarget();
1308 mAlbum.setVisibility(View.VISIBLE);
1310 mDuration = mService.duration();
1311 mTotalTime.setText(MusicUtils.makeTimeString(this, mDuration / 1000));
1312 } catch (RemoteException ex) {
1317 public class AlbumArtHandler extends Handler {
1318 private long mAlbumId = -1;
1320 public AlbumArtHandler(Looper looper) {
1324 public void handleMessage(Message msg)
1326 long albumid = ((AlbumSongIdWrapper) msg.obj).albumid;
1327 long songid = ((AlbumSongIdWrapper) msg.obj).songid;
1328 if (msg.what == GET_ALBUM_ART && (mAlbumId != albumid || albumid < 0)) {
1329 // while decoding the new image, show the default album art
1330 Message numsg = mHandler.obtainMessage(ALBUM_ART_DECODED, null);
1331 mHandler.removeMessages(ALBUM_ART_DECODED);
1332 mHandler.sendMessageDelayed(numsg, 300);
1333 Bitmap bm = MusicUtils.getArtwork(MediaPlaybackActivity.this, songid, albumid);
1335 bm = MusicUtils.getArtwork(MediaPlaybackActivity.this, songid, -1);
1339 numsg = mHandler.obtainMessage(ALBUM_ART_DECODED, bm);
1340 mHandler.removeMessages(ALBUM_ART_DECODED);
1341 mHandler.sendMessage(numsg);
1348 private static class Worker implements Runnable {
1349 private final Object mLock = new Object();
1350 private Looper mLooper;
1353 * Creates a worker thread with the given name. The thread
1354 * then runs a {@link android.os.Looper}.
1355 * @param name A name for the new thread
1357 Worker(String name) {
1358 Thread t = new Thread(null, this, name);
1359 t.setPriority(Thread.MIN_PRIORITY);
1361 synchronized (mLock) {
1362 while (mLooper == null) {
1365 } catch (InterruptedException ex) {
1371 public Looper getLooper() {
1376 synchronized (mLock) {
1378 mLooper = Looper.myLooper();
1384 public void quit() {