OSDN Git Service

Merge change 24529 into eclair
[android-x86/packages-apps-Music.git] / src / com / android / music / MediaPlaybackActivity.java
1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.android.music;
18
19 import android.app.Activity;
20 import android.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;
64
65
66 public class MediaPlaybackActivity extends Activity implements MusicUtils.Defs,
67     View.OnTouchListener, View.OnLongClickListener
68 {
69     private static final int USE_AS_RINGTONE = CHILD_MENU_BASE;
70     
71     private boolean mOneShot = false;
72     private boolean mSeeking = false;
73     private boolean mDeviceHasDpad;
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;
85     private Toast mToast;
86     private int mTouchSlop;
87
88     public MediaPlaybackActivity()
89     {
90     }
91
92     /** Called when the activity is first created. */
93     @Override
94     public void onCreate(Bundle icicle)
95     {
96         super.onCreate(icicle);
97         setVolumeControlStream(AudioManager.STREAM_MUSIC);
98
99         mAlbumArtWorker = new Worker("album art worker");
100         mAlbumArtHandler = new AlbumArtHandler(mAlbumArtWorker.getLooper());
101
102         requestWindowFeature(Window.FEATURE_NO_TITLE);
103         setContentView(R.layout.audio_player);
104
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);
112
113         View v = (View)mArtistName.getParent(); 
114         v.setOnTouchListener(this);
115         v.setOnLongClickListener(this);
116
117         v = (View)mAlbumName.getParent();
118         v.setOnTouchListener(this);
119         v.setOnLongClickListener(this);
120
121         v = (View)mTrackName.getParent();
122         v.setOnTouchListener(this);
123         v.setOnLongClickListener(this);
124         
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);
134         seekmethod = 1;
135
136         mDeviceHasDpad = (getResources().getConfiguration().navigation ==
137             Configuration.NAVIGATION_DPAD);
138         
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);
145         
146         if (mProgress instanceof SeekBar) {
147             SeekBar seeker = (SeekBar) mProgress;
148             seeker.setOnSeekBarChangeListener(mSeekListener);
149         }
150         mProgress.setMax(1000);
151         
152         if (icicle != null) {
153             mOneShot = icicle.getBoolean("oneshot");
154         } else {
155             mOneShot = getIntent().getBooleanExtra("oneshot", false);
156         }
157
158         mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();
159     }
160     
161     int mInitialX = -1;
162     int mLastX = -1;
163     int mTextWidth = 0;
164     int mViewWidth = 0;
165     boolean mDraggingLabel = false;
166     
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;
174         return null;
175     }
176     
177     public boolean onTouch(View v, MotionEvent event) {
178         int action = event.getAction();
179         TextView tv = textViewForContainer(v);
180         if (tv == null) {
181             return false;
182         }
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);
193             }
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;
199                 if (delta != 0) {
200                     mLastX = x;
201                     scrollx += delta;
202                     if (scrollx > mTextWidth) {
203                         // scrolled the text completely off the view to the left
204                         scrollx -= mTextWidth;
205                         scrollx -= mViewWidth;
206                     }
207                     if (scrollx < -mViewWidth) {
208                         // scrolled the text completely off the view to the right
209                         scrollx += mViewWidth;
210                         scrollx += mTextWidth;
211                     }
212                     tv.scrollTo(scrollx, 0);
213                 }
214                 return true;
215             }
216             int delta = mInitialX - (int) event.getX();
217             if (Math.abs(delta) > mTouchSlop) {
218                 // start moving
219                 mLabelScroller.removeMessages(0, tv);
220                 
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);
225                 }
226                 Layout ll = tv.getLayout();
227                 // layout might be null if the text just changed, or ellipsizing
228                 // was just turned off
229                 if (ll == null) {
230                     return false;
231                 }
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);
238                     v.cancelLongPress();
239                     return false;
240                 }
241                 mDraggingLabel = true;
242                 tv.setHorizontalFadingEdgeEnabled(true);
243                 v.cancelLongPress();
244                 return true;
245             }
246         }
247         return false; 
248     }
249
250     Handler mLabelScroller = new Handler() {
251         @Override
252         public void handleMessage(Message msg) {
253             TextView tv = (TextView) msg.obj;
254             int x = tv.getScrollX();
255             x = x * 3 / 4;
256             tv.scrollTo(x, 0);
257             if (x == 0) {
258                 tv.setEllipsize(TruncateAt.END);
259             } else {
260                 Message newmsg = obtainMessage(0, tv);
261                 mLabelScroller.sendMessageDelayed(newmsg, 15);
262             }
263         }
264     };
265     
266     public boolean onLongClick(View view) {
267
268         CharSequence title = null;
269         String mime = null;
270         String query = null;
271         String artist;
272         String album;
273         String song;
274         long audioid;
275         
276         try {
277             artist = mService.getArtistName();
278             album = mService.getAlbumName();
279             song = mService.getTrackName();
280             audioid = mService.getAudioId();
281         } catch (RemoteException ex) {
282             return true;
283         }
284
285         if (MediaFile.UNKNOWN_STRING.equals(album) &&
286                 MediaFile.UNKNOWN_STRING.equals(artist) &&
287                 song != null &&
288                 song.startsWith("recording")) {
289             // not music
290             return false;
291         }
292
293         if (audioid < 0) {
294             return false;
295         }
296
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;
301         if (c != null) {
302             if (c.moveToFirst()) {
303                 ismusic = c.getInt(0) != 0;
304             }
305             c.close();
306         }
307         if (!ismusic) {
308             return false;
309         }
310
311         boolean knownartist =
312             (artist != null) && !MediaFile.UNKNOWN_STRING.equals(artist);
313
314         boolean knownalbum =
315             (album != null) && !MediaFile.UNKNOWN_STRING.equals(album);
316         
317         if (knownartist && view.equals(mArtistName.getParent())) {
318             title = artist;
319             query = artist;
320             mime = MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE;
321         } else if (knownalbum && view.equals(mAlbumName.getParent())) {
322             title = album;
323             if (knownartist) {
324                 query = artist + " " + album;
325             } else {
326                 query = album;
327             }
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.
333                 return true;
334             }
335
336             title = song;
337             if (knownartist) {
338                 query = artist + " " + song;
339             } else {
340                 query = song;
341             }
342             mime = "audio/*"; // the specific type doesn't matter, so don't bother retrieving it
343         } else {
344             throw new RuntimeException("shouldn't be here");
345         }
346         title = getString(R.string.mediasearch, title);
347
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);
352         if(knownartist) {
353             i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist);
354         }
355         if(knownalbum) {
356             i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, album);
357         }
358         i.putExtra(MediaStore.EXTRA_MEDIA_TITLE, song);
359         i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, mime);
360
361         startActivity(Intent.createChooser(i, title));
362         return true;
363     }
364
365     private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
366         public void onStartTrackingTouch(SeekBar bar) {
367             mLastSeekEventTime = 0;
368             mFromTouch = true;
369         }
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;
376                 try {
377                     mService.seek(mPosOverride);
378                 } catch (RemoteException ex) {
379                 }
380
381                 // trackball event, allow progress updates
382                 if (!mFromTouch) {
383                     refreshNow();
384                     mPosOverride = -1;
385                 }
386             }
387         }
388         public void onStopTrackingTouch(SeekBar bar) {
389             mPosOverride = -1;
390             mFromTouch = false;
391         }
392     };
393     
394     private View.OnClickListener mQueueListener = new View.OnClickListener() {
395         public void onClick(View v) {
396             startActivity(
397                     new Intent(Intent.ACTION_EDIT)
398                     .setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track")
399                     .putExtra("playlist", "nowplaying")
400             );
401         }
402     };
403     
404     private View.OnClickListener mShuffleListener = new View.OnClickListener() {
405         public void onClick(View v) {
406             toggleShuffle();
407         }
408     };
409
410     private View.OnClickListener mRepeatListener = new View.OnClickListener() {
411         public void onClick(View v) {
412             cycleRepeat();
413         }
414     };
415
416     private View.OnClickListener mPauseListener = new View.OnClickListener() {
417         public void onClick(View v) {
418             doPauseResume();
419         }
420     };
421
422     private View.OnClickListener mPrevListener = new View.OnClickListener() {
423         public void onClick(View v) {
424             if (mService == null) return;
425             try {
426                 if (mService.position() < 2000) {
427                     mService.prev();
428                 } else {
429                     mService.seek(0);
430                     mService.play();
431                 }
432             } catch (RemoteException ex) {
433             }
434         }
435     };
436
437     private View.OnClickListener mNextListener = new View.OnClickListener() {
438         public void onClick(View v) {
439             if (mService == null) return;
440             try {
441                 mService.next();
442             } catch (RemoteException ex) {
443             }
444         }
445     };
446
447     private RepeatingImageButton.RepeatListener mRewListener =
448         new RepeatingImageButton.RepeatListener() {
449         public void onRepeat(View v, long howlong, int repcnt) {
450             scanBackward(repcnt, howlong);
451         }
452     };
453     
454     private RepeatingImageButton.RepeatListener mFfwdListener =
455         new RepeatingImageButton.RepeatListener() {
456         public void onRepeat(View v, long howlong, int repcnt) {
457             scanForward(repcnt, howlong);
458         }
459     };
460    
461     @Override
462     public void onStop() {
463         paused = true;
464         if (mService != null && mOneShot && getChangingConfigurations() == 0) {
465             try {
466                 mService.stop();
467             } catch (RemoteException ex) {
468             }
469         }
470         mHandler.removeMessages(REFRESH);
471         unregisterReceiver(mStatusListener);
472         MusicUtils.unbindFromService(this);
473         mService = null;
474         super.onStop();
475     }
476
477     @Override
478     public void onSaveInstanceState(Bundle outState) {
479         outState.putBoolean("oneshot", mOneShot);
480         super.onSaveInstanceState(outState);
481     }
482     
483     @Override
484     public void onStart() {
485         super.onStart();
486         paused = false;
487
488         if (false == MusicUtils.bindToService(this, osc)) {
489             // something went wrong
490             mHandler.sendEmptyMessage(QUIT);
491         }
492         
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));
498         updateTrackInfo();
499         long next = refreshNow();
500         queueNextRefresh(next);
501     }
502     
503     @Override
504     public void onNewIntent(Intent intent) {
505         setIntent(intent);
506         mOneShot = intent.getBooleanExtra("oneshot", false);
507     }
508     
509     @Override
510     public void onResume() {
511         super.onResume();
512         updateTrackInfo();
513         setPauseButtonImage();
514     }
515     
516     @Override
517     public void onDestroy()
518     {
519         mAlbumArtWorker.quit();
520         super.onDestroy();
521         //System.out.println("***************** playback activity onDestroy\n");
522     }
523
524     @Override
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);
539             return true;
540         }
541         return false;
542     }
543
544     @Override
545     public boolean onPrepareOptionsMenu(Menu menu) {
546         MenuItem item = menu.findItem(PARTY_SHUFFLE);
547         if (item != null) {
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);
552             } else {
553                 item.setIcon(R.drawable.ic_menu_party_shuffle);
554                 item.setTitle(R.string.party_shuffle);
555             }
556         }
557         return true;
558     }
559
560     @Override
561     public boolean onOptionsItemSelected(MenuItem item) {
562         Intent intent;
563         try {
564             switch (item.getItemId()) {
565                 case GOTO_START:
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);
571                     break;
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());
576                     }
577                     return true;
578                 }
579                 case PARTY_SHUFFLE:
580                     if (mService != null) {
581                         int shuffle = mService.getShuffleMode();
582                         if (shuffle == MediaPlaybackService.SHUFFLE_AUTO) {
583                             mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
584                         } else {
585                             mService.setShuffleMode(MediaPlaybackService.SHUFFLE_AUTO);
586                         }
587                     }
588                     setShuffleButtonImage();
589                     break;
590                     
591                 case NEW_PLAYLIST: {
592                     intent = new Intent();
593                     intent.setClass(this, CreatePlaylist.class);
594                     startActivityForResult(intent, NEW_PLAYLIST);
595                     return true;
596                 }
597
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);
603                     return true;
604                 }
605                 
606                 case DELETE_ITEM: {
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);
616                         intent.putExtras(b);
617                         startActivityForResult(intent, -1);
618                     }
619                     return true;
620                 }
621             }
622         } catch (RemoteException ex) {
623         }
624         return super.onOptionsItemSelected(item);
625     }
626     
627     @Override
628     protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
629         if (resultCode != RESULT_OK) {
630             return;
631         }
632         switch (requestCode) {
633             case NEW_PLAYLIST:
634                 Uri uri = intent.getData();
635                 if (uri != null) {
636                     long [] list = new long[1];
637                     list[0] = MusicUtils.getCurrentAudioId();
638                     int playlist = Integer.parseInt(uri.getLastPathSegment());
639                     MusicUtils.addToPlaylist(this, list, playlist);
640                 }
641                 break;
642         }
643     }
644     private final int keyboard[][] = {
645         {
646             KeyEvent.KEYCODE_Q,
647             KeyEvent.KEYCODE_W,
648             KeyEvent.KEYCODE_E,
649             KeyEvent.KEYCODE_R,
650             KeyEvent.KEYCODE_T,
651             KeyEvent.KEYCODE_Y,
652             KeyEvent.KEYCODE_U,
653             KeyEvent.KEYCODE_I,
654             KeyEvent.KEYCODE_O,
655             KeyEvent.KEYCODE_P,
656         },
657         {
658             KeyEvent.KEYCODE_A,
659             KeyEvent.KEYCODE_S,
660             KeyEvent.KEYCODE_D,
661             KeyEvent.KEYCODE_F,
662             KeyEvent.KEYCODE_G,
663             KeyEvent.KEYCODE_H,
664             KeyEvent.KEYCODE_J,
665             KeyEvent.KEYCODE_K,
666             KeyEvent.KEYCODE_L,
667             KeyEvent.KEYCODE_DEL,
668         },
669         {
670             KeyEvent.KEYCODE_Z,
671             KeyEvent.KEYCODE_X,
672             KeyEvent.KEYCODE_C,
673             KeyEvent.KEYCODE_V,
674             KeyEvent.KEYCODE_B,
675             KeyEvent.KEYCODE_N,
676             KeyEvent.KEYCODE_M,
677             KeyEvent.KEYCODE_COMMA,
678             KeyEvent.KEYCODE_PERIOD,
679             KeyEvent.KEYCODE_ENTER
680         }
681
682     };
683
684     private int lastX;
685     private int lastY;
686
687     private boolean seekMethod1(int keyCode)
688     {
689         for(int x=0;x<10;x++) {
690             for(int y=0;y<3;y++) {
691                 if(keyboard[y][x] == keyCode) {
692                     int dir = 0;
693                     // top row
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;
697                     // bottom row
698                     else if (y == 2 && lastY == 2 && x > lastX) dir = -1;
699                     else if (y == 2 && lastY == 2 && x < lastX) dir = 1;
700                     // moving up
701                     else if (y < lastY && x <= 4) dir = 1; 
702                     else if (y < lastY && x >= 5) dir = -1; 
703                     // moving down
704                     else if (y > lastY && x <= 4) dir = -1; 
705                     else if (y > lastY && x >= 5) dir = 1; 
706                     lastX = x;
707                     lastY = y;
708                     try {
709                         mService.seek(mService.position() + dir * 5);
710                     } catch (RemoteException ex) {
711                     }
712                     refreshNow();
713                     return true;
714                 }
715             }
716         }
717         lastX = -1;
718         lastY = -1;
719         return false;
720     }
721
722     private boolean seekMethod2(int keyCode)
723     {
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;
728                 try {
729                     mService.seek(mService.duration() * seekpercentage / 100);
730                 } catch (RemoteException ex) {
731                 }
732                 refreshNow();
733                 return true;
734             }
735         }
736         return false;
737     }
738
739     @Override
740     public boolean onKeyUp(int keyCode, KeyEvent event) {
741         try {
742             switch(keyCode)
743             {
744                 case KeyEvent.KEYCODE_DPAD_LEFT:
745                     if (!useDpadMusicControl()) {
746                         break;
747                     }
748                     if (mService != null) {
749                         if (!mSeeking && mStartSeekPos >= 0) {
750                             mPauseButton.requestFocus();
751                             if (mStartSeekPos < 1000) {
752                                 mService.prev();
753                             } else {
754                                 mService.seek(0);
755                             }
756                         } else {
757                             scanBackward(-1, event.getEventTime() - event.getDownTime());
758                             mPauseButton.requestFocus();
759                             mStartSeekPos = -1;
760                         }
761                     }
762                     mSeeking = false;
763                     mPosOverride = -1;
764                     return true;
765                 case KeyEvent.KEYCODE_DPAD_RIGHT:
766                     if (!useDpadMusicControl()) {
767                         break;
768                     }
769                     if (mService != null) {
770                         if (!mSeeking && mStartSeekPos >= 0) {
771                             mPauseButton.requestFocus();
772                             mService.next();
773                         } else {
774                             scanForward(-1, event.getEventTime() - event.getDownTime());
775                             mPauseButton.requestFocus();
776                             mStartSeekPos = -1;
777                         }
778                     }
779                     mSeeking = false;
780                     mPosOverride = -1;
781                     return true;
782             }
783         } catch (RemoteException ex) {
784         }
785         return super.onKeyUp(keyCode, event);
786     }
787
788     private boolean useDpadMusicControl() {
789         if (mDeviceHasDpad && (mPrevButton.isFocused() ||
790                 mNextButton.isFocused() ||
791                 mPauseButton.isFocused())) {
792             return true;
793         }
794         return false;
795     }
796
797     @Override
798     public boolean onKeyDown(int keyCode, KeyEvent event)
799     {
800         int direction = -1;
801         int repcnt = event.getRepeatCount();
802
803         if((seekmethod==0)?seekMethod1(keyCode):seekMethod2(keyCode))
804             return true;
805
806         switch(keyCode)
807         {
808 /*
809             // image scale
810             case KeyEvent.KEYCODE_Q: av.adjustParams(-0.05, 0.0, 0.0, 0.0, 0.0,-1.0); break;
811             case KeyEvent.KEYCODE_E: av.adjustParams( 0.05, 0.0, 0.0, 0.0, 0.0, 1.0); break;
812             // image translate
813             case KeyEvent.KEYCODE_W: av.adjustParams(    0.0, 0.0,-1.0, 0.0, 0.0, 0.0); break;
814             case KeyEvent.KEYCODE_X: av.adjustParams(    0.0, 0.0, 1.0, 0.0, 0.0, 0.0); break;
815             case KeyEvent.KEYCODE_A: av.adjustParams(    0.0,-1.0, 0.0, 0.0, 0.0, 0.0); break;
816             case KeyEvent.KEYCODE_D: av.adjustParams(    0.0, 1.0, 0.0, 0.0, 0.0, 0.0); break;
817             // camera rotation
818             case KeyEvent.KEYCODE_R: av.adjustParams(    0.0, 0.0, 0.0, 0.0, 0.0,-1.0); break;
819             case KeyEvent.KEYCODE_U: av.adjustParams(    0.0, 0.0, 0.0, 0.0, 0.0, 1.0); break;
820             // camera translate
821             case KeyEvent.KEYCODE_Y: av.adjustParams(    0.0, 0.0, 0.0, 0.0,-1.0, 0.0); break;
822             case KeyEvent.KEYCODE_N: av.adjustParams(    0.0, 0.0, 0.0, 0.0, 1.0, 0.0); break;
823             case KeyEvent.KEYCODE_G: av.adjustParams(    0.0, 0.0, 0.0,-1.0, 0.0, 0.0); break;
824             case KeyEvent.KEYCODE_J: av.adjustParams(    0.0, 0.0, 0.0, 1.0, 0.0, 0.0); break;
825
826 */
827
828             case KeyEvent.KEYCODE_SLASH:
829                 seekmethod = 1 - seekmethod;
830                 return true;
831
832             case KeyEvent.KEYCODE_DPAD_LEFT:
833                 if (!useDpadMusicControl()) {
834                     break;
835                 }
836                 if (!mPrevButton.hasFocus()) {
837                     mPrevButton.requestFocus();
838                 }
839                 scanBackward(repcnt, event.getEventTime() - event.getDownTime());
840                 return true;
841             case KeyEvent.KEYCODE_DPAD_RIGHT:
842                 if (!useDpadMusicControl()) {
843                     break;
844                 }
845                 if (!mNextButton.hasFocus()) {
846                     mNextButton.requestFocus();
847                 }
848                 scanForward(repcnt, event.getEventTime() - event.getDownTime());
849                 return true;
850
851             case KeyEvent.KEYCODE_S:
852                 toggleShuffle();
853                 return true;
854
855             case KeyEvent.KEYCODE_DPAD_CENTER:
856             case KeyEvent.KEYCODE_SPACE:
857                 doPauseResume();
858                 return true;
859         }
860         return super.onKeyDown(keyCode, event);
861     }
862     
863     private void scanBackward(int repcnt, long delta) {
864         if(mService == null) return;
865         try {
866             if(repcnt == 0) {
867                 mStartSeekPos = mService.position();
868                 mLastSeekEventTime = 0;
869                 mSeeking = false;
870             } else {
871                 mSeeking = true;
872                 if (delta < 5000) {
873                     // seek at 10x speed for the first 5 seconds
874                     delta = delta * 10; 
875                 } else {
876                     // seek at 40x after that
877                     delta = 50000 + (delta - 5000) * 40;
878                 }
879                 long newpos = mStartSeekPos - delta;
880                 if (newpos < 0) {
881                     // move to previous track
882                     mService.prev();
883                     long duration = mService.duration();
884                     mStartSeekPos += duration;
885                     newpos += duration;
886                 }
887                 if (((delta - mLastSeekEventTime) > 250) || repcnt < 0){
888                     mService.seek(newpos);
889                     mLastSeekEventTime = delta;
890                 }
891                 if (repcnt >= 0) {
892                     mPosOverride = newpos;
893                 } else {
894                     mPosOverride = -1;
895                 }
896                 refreshNow();
897             }
898         } catch (RemoteException ex) {
899         }
900     }
901
902     private void scanForward(int repcnt, long delta) {
903         if(mService == null) return;
904         try {
905             if(repcnt == 0) {
906                 mStartSeekPos = mService.position();
907                 mLastSeekEventTime = 0;
908                 mSeeking = false;
909             } else {
910                 mSeeking = true;
911                 if (delta < 5000) {
912                     // seek at 10x speed for the first 5 seconds
913                     delta = delta * 10; 
914                 } else {
915                     // seek at 40x after that
916                     delta = 50000 + (delta - 5000) * 40;
917                 }
918                 long newpos = mStartSeekPos + delta;
919                 long duration = mService.duration();
920                 if (newpos >= duration) {
921                     // move to next track
922                     mService.next();
923                     mStartSeekPos -= duration; // is OK to go negative
924                     newpos -= duration;
925                 }
926                 if (((delta - mLastSeekEventTime) > 250) || repcnt < 0){
927                     mService.seek(newpos);
928                     mLastSeekEventTime = delta;
929                 }
930                 if (repcnt >= 0) {
931                     mPosOverride = newpos;
932                 } else {
933                     mPosOverride = -1;
934                 }
935                 refreshNow();
936             }
937         } catch (RemoteException ex) {
938         }
939     }
940     
941     private void doPauseResume() {
942         try {
943             if(mService != null) {
944                 if (mService.isPlaying()) {
945                     mService.pause();
946                 } else {
947                     mService.play();
948                 }
949                 refreshNow();
950                 setPauseButtonImage();
951             }
952         } catch (RemoteException ex) {
953         }
954     }
955     
956     private void toggleShuffle() {
957         if (mService == null) {
958             return;
959         }
960         try {
961             int shuffle = mService.getShuffleMode();
962             if (shuffle == MediaPlaybackService.SHUFFLE_NONE) {
963                 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NORMAL);
964                 if (mService.getRepeatMode() == MediaPlaybackService.REPEAT_CURRENT) {
965                     mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
966                     setRepeatButtonImage();
967                 }
968                 showToast(R.string.shuffle_on_notif);
969             } else if (shuffle == MediaPlaybackService.SHUFFLE_NORMAL ||
970                     shuffle == MediaPlaybackService.SHUFFLE_AUTO) {
971                 mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
972                 showToast(R.string.shuffle_off_notif);
973             } else {
974                 Log.e("MediaPlaybackActivity", "Invalid shuffle mode: " + shuffle);
975             }
976             setShuffleButtonImage();
977         } catch (RemoteException ex) {
978         }
979     }
980     
981     private void cycleRepeat() {
982         if (mService == null) {
983             return;
984         }
985         try {
986             int mode = mService.getRepeatMode();
987             if (mode == MediaPlaybackService.REPEAT_NONE) {
988                 mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
989                 showToast(R.string.repeat_all_notif);
990             } else if (mode == MediaPlaybackService.REPEAT_ALL) {
991                 mService.setRepeatMode(MediaPlaybackService.REPEAT_CURRENT);
992                 if (mService.getShuffleMode() != MediaPlaybackService.SHUFFLE_NONE) {
993                     mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
994                     setShuffleButtonImage();
995                 }
996                 showToast(R.string.repeat_current_notif);
997             } else {
998                 mService.setRepeatMode(MediaPlaybackService.REPEAT_NONE);
999                 showToast(R.string.repeat_off_notif);
1000             }
1001             setRepeatButtonImage();
1002         } catch (RemoteException ex) {
1003         }
1004         
1005     }
1006     
1007     private void showToast(int resid) {
1008         if (mToast == null) {
1009             mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
1010         }
1011         mToast.setText(resid);
1012         mToast.show();
1013     }
1014
1015     private void startPlayback() {
1016
1017         if(mService == null)
1018             return;
1019         Intent intent = getIntent();
1020         String filename = "";
1021         Uri uri = intent.getData();
1022         if (uri != null && uri.toString().length() > 0) {
1023             // If this is a file:// URI, just use the path directly instead
1024             // of going through the open-from-filedescriptor codepath.
1025             String scheme = uri.getScheme();
1026             if ("file".equals(scheme)) {
1027                 filename = uri.getPath();
1028             } else {
1029                 filename = uri.toString();
1030             }
1031             try {
1032                 if (! ContentResolver.SCHEME_CONTENT.equals(scheme) ||
1033                         ! MediaStore.AUTHORITY.equals(uri.getAuthority())) {
1034                     mOneShot = true;
1035                 }
1036                 mService.stop();
1037                 mService.openFile(filename, mOneShot);
1038                 mService.play();
1039                 setIntent(new Intent());
1040             } catch (Exception ex) {
1041                 Log.d("MediaPlaybackActivity", "couldn't start playback: " + ex);
1042             }
1043         }
1044
1045         updateTrackInfo();
1046         long next = refreshNow();
1047         queueNextRefresh(next);
1048     }
1049
1050     private ServiceConnection osc = new ServiceConnection() {
1051             public void onServiceConnected(ComponentName classname, IBinder obj) {
1052                 mService = IMediaPlaybackService.Stub.asInterface(obj);
1053                 startPlayback();
1054                 try {
1055                     // Assume something is playing when the service says it is,
1056                     // but also if the audio ID is valid but the service is paused.
1057                     if (mService.getAudioId() >= 0 || mService.isPlaying() ||
1058                             mService.getPath() != null) {
1059                         // something is playing now, we're done
1060                         if (mOneShot || mService.getAudioId() < 0) {
1061                             mRepeatButton.setVisibility(View.INVISIBLE);
1062                             mShuffleButton.setVisibility(View.INVISIBLE);
1063                             mQueueButton.setVisibility(View.INVISIBLE);
1064                         } else {
1065                             mRepeatButton.setVisibility(View.VISIBLE);
1066                             mShuffleButton.setVisibility(View.VISIBLE);
1067                             mQueueButton.setVisibility(View.VISIBLE);
1068                             setRepeatButtonImage();
1069                             setShuffleButtonImage();
1070                         }
1071                         setPauseButtonImage();
1072                         return;
1073                     }
1074                 } catch (RemoteException ex) {
1075                 }
1076                 // Service is dead or not playing anything. If we got here as part
1077                 // of a "play this file" Intent, exit. Otherwise go to the Music
1078                 // app start screen.
1079                 if (getIntent().getData() == null) {
1080                     Intent intent = new Intent(Intent.ACTION_MAIN);
1081                     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1082                     intent.setClass(MediaPlaybackActivity.this, MusicBrowserActivity.class);
1083                     startActivity(intent);
1084                 }
1085                 finish();
1086             }
1087             public void onServiceDisconnected(ComponentName classname) {
1088             }
1089     };
1090
1091     private void setRepeatButtonImage() {
1092         try {
1093             switch (mService.getRepeatMode()) {
1094                 case MediaPlaybackService.REPEAT_ALL:
1095                     mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_all_btn);
1096                     break;
1097                 case MediaPlaybackService.REPEAT_CURRENT:
1098                     mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_once_btn);
1099                     break;
1100                 default:
1101                     mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_off_btn);
1102                     break;
1103             }
1104         } catch (RemoteException ex) {
1105         }
1106     }
1107     
1108     private void setShuffleButtonImage() {
1109         try {
1110             switch (mService.getShuffleMode()) {
1111                 case MediaPlaybackService.SHUFFLE_NONE:
1112                     mShuffleButton.setImageResource(R.drawable.ic_mp_shuffle_off_btn);
1113                     break;
1114                 case MediaPlaybackService.SHUFFLE_AUTO:
1115                     mShuffleButton.setImageResource(R.drawable.ic_mp_partyshuffle_on_btn);
1116                     break;
1117                 default:
1118                     mShuffleButton.setImageResource(R.drawable.ic_mp_shuffle_on_btn);
1119                     break;
1120             }
1121         } catch (RemoteException ex) {
1122         }
1123     }
1124     
1125     private void setPauseButtonImage() {
1126         try {
1127             if (mService != null && mService.isPlaying()) {
1128                 mPauseButton.setImageResource(android.R.drawable.ic_media_pause);
1129             } else {
1130                 mPauseButton.setImageResource(android.R.drawable.ic_media_play);
1131             }
1132         } catch (RemoteException ex) {
1133         }
1134     }
1135     
1136     private ImageView mAlbum;
1137     private TextView mCurrentTime;
1138     private TextView mTotalTime;
1139     private TextView mArtistName;
1140     private TextView mAlbumName;
1141     private TextView mTrackName;
1142     private ProgressBar mProgress;
1143     private long mPosOverride = -1;
1144     private boolean mFromTouch = false;
1145     private long mDuration;
1146     private int seekmethod;
1147     private boolean paused;
1148
1149     private static final int REFRESH = 1;
1150     private static final int QUIT = 2;
1151     private static final int GET_ALBUM_ART = 3;
1152     private static final int ALBUM_ART_DECODED = 4;
1153
1154     private void queueNextRefresh(long delay) {
1155         if (!paused) {
1156             Message msg = mHandler.obtainMessage(REFRESH);
1157             mHandler.removeMessages(REFRESH);
1158             mHandler.sendMessageDelayed(msg, delay);
1159         }
1160     }
1161
1162     private long refreshNow() {
1163         if(mService == null)
1164             return 500;
1165         try {
1166             long pos = mPosOverride < 0 ? mService.position() : mPosOverride;
1167             long remaining = 1000 - (pos % 1000);
1168             if ((pos >= 0) && (mDuration > 0)) {
1169                 mCurrentTime.setText(MusicUtils.makeTimeString(this, pos / 1000));
1170                 
1171                 if (mService.isPlaying()) {
1172                     mCurrentTime.setVisibility(View.VISIBLE);
1173                 } else {
1174                     // blink the counter
1175                     int vis = mCurrentTime.getVisibility();
1176                     mCurrentTime.setVisibility(vis == View.INVISIBLE ? View.VISIBLE : View.INVISIBLE);
1177                     remaining = 500;
1178                 }
1179
1180                 mProgress.setProgress((int) (1000 * pos / mDuration));
1181             } else {
1182                 mCurrentTime.setText("--:--");
1183                 mProgress.setProgress(1000);
1184             }
1185             // return the number of milliseconds until the next full second, so
1186             // the counter can be updated at just the right time
1187             return remaining;
1188         } catch (RemoteException ex) {
1189         }
1190         return 500;
1191     }
1192     
1193     private final Handler mHandler = new Handler() {
1194         @Override
1195         public void handleMessage(Message msg) {
1196             switch (msg.what) {
1197                 case ALBUM_ART_DECODED:
1198                     mAlbum.setImageBitmap((Bitmap)msg.obj);
1199                     mAlbum.getDrawable().setDither(true);
1200                     break;
1201
1202                 case REFRESH:
1203                     long next = refreshNow();
1204                     queueNextRefresh(next);
1205                     break;
1206                     
1207                 case QUIT:
1208                     // This can be moved back to onCreate once the bug that prevents
1209                     // Dialogs from being started from onCreate/onResume is fixed.
1210                     new AlertDialog.Builder(MediaPlaybackActivity.this)
1211                             .setTitle(R.string.service_start_error_title)
1212                             .setMessage(R.string.service_start_error_msg)
1213                             .setPositiveButton(R.string.service_start_error_button,
1214                                     new DialogInterface.OnClickListener() {
1215                                         public void onClick(DialogInterface dialog, int whichButton) {
1216                                             finish();
1217                                         }
1218                                     })
1219                             .setCancelable(false)
1220                             .show();
1221                     break;
1222
1223                 default:
1224                     break;
1225             }
1226         }
1227     };
1228
1229     private BroadcastReceiver mStatusListener = new BroadcastReceiver() {
1230         @Override
1231         public void onReceive(Context context, Intent intent) {
1232             String action = intent.getAction();
1233             if (action.equals(MediaPlaybackService.META_CHANGED)) {
1234                 // redraw the artist/title info and
1235                 // set new max for progress bar
1236                 updateTrackInfo();
1237                 setPauseButtonImage();
1238                 queueNextRefresh(1);
1239             } else if (action.equals(MediaPlaybackService.PLAYBACK_COMPLETE)) {
1240                 if (mOneShot) {
1241                     finish();
1242                 } else {
1243                     setPauseButtonImage();
1244                 }
1245             } else if (action.equals(MediaPlaybackService.PLAYSTATE_CHANGED)) {
1246                 setPauseButtonImage();
1247             }
1248         }
1249     };
1250
1251     private static class AlbumSongIdWrapper {
1252         public long albumid;
1253         public long songid;
1254         AlbumSongIdWrapper(long aid, long sid) {
1255             albumid = aid;
1256             songid = sid;
1257         }
1258     }
1259     
1260     private void updateTrackInfo() {
1261         if (mService == null) {
1262             return;
1263         }
1264         try {
1265             String path = mService.getPath();
1266             if (path == null) {
1267                 finish();
1268                 return;
1269             }
1270             
1271             long songid = mService.getAudioId(); 
1272             if (songid < 0 && path.toLowerCase().startsWith("http://")) {
1273                 // Once we can get album art and meta data from MediaPlayer, we
1274                 // can show that info again when streaming.
1275                 ((View) mArtistName.getParent()).setVisibility(View.INVISIBLE);
1276                 ((View) mAlbumName.getParent()).setVisibility(View.INVISIBLE);
1277                 mAlbum.setVisibility(View.GONE);
1278                 mTrackName.setText(path);
1279                 mAlbumArtHandler.removeMessages(GET_ALBUM_ART);
1280                 mAlbumArtHandler.obtainMessage(GET_ALBUM_ART, new AlbumSongIdWrapper(-1, -1)).sendToTarget();
1281             } else {
1282                 ((View) mArtistName.getParent()).setVisibility(View.VISIBLE);
1283                 ((View) mAlbumName.getParent()).setVisibility(View.VISIBLE);
1284                 String artistName = mService.getArtistName();
1285                 if (MediaFile.UNKNOWN_STRING.equals(artistName)) {
1286                     artistName = getString(R.string.unknown_artist_name);
1287                 }
1288                 mArtistName.setText(artistName);
1289                 String albumName = mService.getAlbumName();
1290                 long albumid = mService.getAlbumId();
1291                 if (MediaFile.UNKNOWN_STRING.equals(albumName)) {
1292                     albumName = getString(R.string.unknown_album_name);
1293                     albumid = -1;
1294                 }
1295                 mAlbumName.setText(albumName);
1296                 mTrackName.setText(mService.getTrackName());
1297                 mAlbumArtHandler.removeMessages(GET_ALBUM_ART);
1298                 mAlbumArtHandler.obtainMessage(GET_ALBUM_ART, new AlbumSongIdWrapper(albumid, songid)).sendToTarget();
1299                 mAlbum.setVisibility(View.VISIBLE);
1300             }
1301             mDuration = mService.duration();
1302             mTotalTime.setText(MusicUtils.makeTimeString(this, mDuration / 1000));
1303         } catch (RemoteException ex) {
1304             finish();
1305         }
1306     }
1307     
1308     public class AlbumArtHandler extends Handler {
1309         private long mAlbumId = -1;
1310         
1311         public AlbumArtHandler(Looper looper) {
1312             super(looper);
1313         }
1314         @Override
1315         public void handleMessage(Message msg)
1316         {
1317             long albumid = ((AlbumSongIdWrapper) msg.obj).albumid;
1318             long songid = ((AlbumSongIdWrapper) msg.obj).songid;
1319             if (msg.what == GET_ALBUM_ART && (mAlbumId != albumid || albumid < 0)) {
1320                 // while decoding the new image, show the default album art
1321                 Message numsg = mHandler.obtainMessage(ALBUM_ART_DECODED, null);
1322                 mHandler.removeMessages(ALBUM_ART_DECODED);
1323                 mHandler.sendMessageDelayed(numsg, 300);
1324                 Bitmap bm = MusicUtils.getArtwork(MediaPlaybackActivity.this, songid, albumid);
1325                 if (bm == null) {
1326                     bm = MusicUtils.getArtwork(MediaPlaybackActivity.this, songid, -1);
1327                     albumid = -1;
1328                 }
1329                 if (bm != null) {
1330                     numsg = mHandler.obtainMessage(ALBUM_ART_DECODED, bm);
1331                     mHandler.removeMessages(ALBUM_ART_DECODED);
1332                     mHandler.sendMessage(numsg);
1333                 }
1334                 mAlbumId = albumid;
1335             }
1336         }
1337     }
1338     
1339     private static class Worker implements Runnable {
1340         private final Object mLock = new Object();
1341         private Looper mLooper;
1342         
1343         /**
1344          * Creates a worker thread with the given name. The thread
1345          * then runs a {@link android.os.Looper}.
1346          * @param name A name for the new thread
1347          */
1348         Worker(String name) {
1349             Thread t = new Thread(null, this, name);
1350             t.setPriority(Thread.MIN_PRIORITY);
1351             t.start();
1352             synchronized (mLock) {
1353                 while (mLooper == null) {
1354                     try {
1355                         mLock.wait();
1356                     } catch (InterruptedException ex) {
1357                     }
1358                 }
1359             }
1360         }
1361         
1362         public Looper getLooper() {
1363             return mLooper;
1364         }
1365         
1366         public void run() {
1367             synchronized (mLock) {
1368                 Looper.prepare();
1369                 mLooper = Looper.myLooper();
1370                 mLock.notifyAll();
1371             }
1372             Looper.loop();
1373         }
1374         
1375         public void quit() {
1376             mLooper.quit();
1377         }
1378     }
1379 }
1380