MediaPlayer.java revision 05be9531b6faf9313e7577284a547b89950d0d55
12502e004d93734a99bdfeab811b3c5ae06f45becbuzbee/*
22502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * Copyright (C) 2006 The Android Open Source Project
32502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
42502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * Licensed under the Apache License, Version 2.0 (the "License");
52502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * you may not use this file except in compliance with the License.
62502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * You may obtain a copy of the License at
72502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
82502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *      http://www.apache.org/licenses/LICENSE-2.0
92502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
102502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * Unless required by applicable law or agreed to in writing, software
112502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * distributed under the License is distributed on an "AS IS" BASIS,
122502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
132502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * See the License for the specific language governing permissions and
142502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * limitations under the License.
152502e004d93734a99bdfeab811b3c5ae06f45becbuzbee */
162502e004d93734a99bdfeab811b3c5ae06f45becbuzbee
17311ca169f4727d46a55bdc8dfa0059719fa72b65buzbeepackage android.media;
182502e004d93734a99bdfeab811b3c5ae06f45becbuzbee
192502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.content.ContentResolver;
202502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.content.Context;
212502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.content.res.AssetFileDescriptor;
222ce745c06271d5223d57dbf08117b20d5b60694aBrian Carlstromimport android.net.Uri;
232502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.os.Handler;
242502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.os.Looper;
252502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.os.Message;
262502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.os.Parcel;
272502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.os.ParcelFileDescriptor;
282502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.os.PowerManager;
292502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.util.Log;
302502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.view.Surface;
312502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.view.SurfaceHolder;
322502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.graphics.Bitmap;
332502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.graphics.ParcelSurfaceTexture;
342502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.graphics.SurfaceTexture;
352502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport android.media.AudioManager;
362502e004d93734a99bdfeab811b3c5ae06f45becbuzbee
372502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport java.io.FileDescriptor;
382502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport java.io.IOException;
392502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport java.util.Map;
402502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport java.util.Set;
412502e004d93734a99bdfeab811b3c5ae06f45becbuzbeeimport java.lang.ref.WeakReference;
422502e004d93734a99bdfeab811b3c5ae06f45becbuzbee
432502e004d93734a99bdfeab811b3c5ae06f45becbuzbee/**
442502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * MediaPlayer class can be used to control playback
452502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * of audio/video files and streams. An example on how to use the methods in
462502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * this class can be found in {@link android.widget.VideoView}.
472502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * Please see <a href="{@docRoot}guide/topics/media/index.html">Audio and Video</a>
482502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * for additional help using MediaPlayer.
492502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
502502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <p>Topics covered here are:
512502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <ol>
522502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <li><a href="#StateDiagram">State Diagram</a>
532502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <li><a href="#Valid_and_Invalid_States">Valid and Invalid States</a>
542502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <li><a href="#Permissions">Permissions</a>
552502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <li><a href="#Callbacks">Register informational and error callbacks</a>
562502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * </ol>
572502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
582502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <a name="StateDiagram"></a>
592502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <h3>State Diagram</h3>
602502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
612502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <p>Playback control of audio/video files and streams is managed as a state
622502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * machine. The following diagram shows the life cycle and the states of a
632502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * MediaPlayer object driven by the supported playback control operations.
642502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * The ovals represent the states a MediaPlayer object may reside
652502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * in. The arcs represent the playback control operations that drive the object
662502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * state transition. There are two types of arcs. The arcs with a single arrow
672502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * head represent synchronous method calls, while those with
682502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * a double arrow head represent asynchronous method calls.</p>
692502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
702502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <p><img src="../../../images/mediaplayer_state_diagram.gif"
712502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         alt="MediaPlayer State diagram"
722502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         border="0" /></p>
732502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
742502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <p>From this state diagram, one can see that a MediaPlayer object has the
752502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *    following states:</p>
762502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <ul>
772502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <li>When a MediaPlayer object is just created using <code>new</code> or
782502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         after {@link #reset()} is called, it is in the <em>Idle</em> state; and after
792502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #release()} is called, it is in the <em>End</em> state. Between these
802502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         two states is the life cycle of the MediaPlayer object.
812502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <ul>
822502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>There is a subtle but important difference between a newly constructed
832502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         MediaPlayer object and the MediaPlayer object after {@link #reset()}
842502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         is called. It is a programming error to invoke methods such
852502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         as {@link #getCurrentPosition()},
862502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #getDuration()}, {@link #getVideoHeight()},
872502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #getVideoWidth()}, {@link #setAudioStreamType(int)},
882502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #setLooping(boolean)},
892502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #setVolume(float, float)}, {@link #pause()}, {@link #start()},
902502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #stop()}, {@link #seekTo(int)}, {@link #prepare()} or
912502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #prepareAsync()} in the <em>Idle</em> state for both cases. If any of these
922502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         methods is called right after a MediaPlayer object is constructed,
932502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the user supplied callback method OnErrorListener.onError() won't be
942502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         called by the internal player engine and the object state remains
952502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         unchanged; but if these methods are called right after {@link #reset()},
962502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the user supplied callback method OnErrorListener.onError() will be
972502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         invoked by the internal player engine and the object will be
982502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         transfered to the <em>Error</em> state. </li>
992502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>It is also recommended that once
1002502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         a MediaPlayer object is no longer being used, call {@link #release()} immediately
1012502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         so that resources used by the internal player engine associated with the
1022502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         MediaPlayer object can be released immediately. Resource may include
1032502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         singleton resources such as hardware acceleration components and
1042502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         failure to call {@link #release()} may cause subsequent instances of
1052502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         MediaPlayer objects to fallback to software implementations or fail
1062502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         altogether. Once the MediaPlayer
1072502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         object is in the <em>End</em> state, it can no longer be used and
1082502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         there is no way to bring it back to any other state. </li>
1092502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>Furthermore,
1102502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the MediaPlayer objects created using <code>new</code> is in the
1112502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <em>Idle</em> state, while those created with one
1122502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         of the overloaded convenient <code>create</code> methods are <em>NOT</em>
1132502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         in the <em>Idle</em> state. In fact, the objects are in the <em>Prepared</em>
1142502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         state if the creation using <code>create</code> method is successful.
1152502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </li>
1162502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </ul>
1172502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </li>
1182502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <li>In general, some playback control operation may fail due to various
1192502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         reasons, such as unsupported audio/video format, poorly interleaved
1202502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         audio/video, resolution too high, streaming timeout, and the like.
1212502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         Thus, error reporting and recovery is an important concern under
1222502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         these circumstances. Sometimes, due to programming errors, invoking a playback
1232502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         control operation in an invalid state may also occur. Under all these
1242502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         error conditions, the internal player engine invokes a user supplied
1252502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         OnErrorListener.onError() method if an OnErrorListener has been
1262502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         registered beforehand via
1272502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #setOnErrorListener(android.media.MediaPlayer.OnErrorListener)}.
1282502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <ul>
1292502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>It is important to note that once an error occurs, the
1302502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         MediaPlayer object enters the <em>Error</em> state (except as noted
1312502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         above), even if an error listener has not been registered by the application.</li>
1322502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>In order to reuse a MediaPlayer object that is in the <em>
1332502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         Error</em> state and recover from the error,
1342502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #reset()} can be called to restore the object to its <em>Idle</em>
1352502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         state.</li>
1362502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>It is good programming practice to have your application
1372502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         register a OnErrorListener to look out for error notifications from
1382502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the internal player engine.</li>
1392502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>IllegalStateException is
1402502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         thrown to prevent programming errors such as calling {@link #prepare()},
1412502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #prepareAsync()}, or one of the overloaded <code>setDataSource
1422502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </code> methods in an invalid state. </li>
1432502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </ul>
1442502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </li>
1452502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <li>Calling
1462502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #setDataSource(FileDescriptor)}, or
1472502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #setDataSource(String)}, or
1482502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #setDataSource(Context, Uri)}, or
1492502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #setDataSource(FileDescriptor, long, long)} transfers a
1502502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         MediaPlayer object in the <em>Idle</em> state to the
1512502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <em>Initialized</em> state.
1522502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <ul>
1532502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>An IllegalStateException is thrown if
1542502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         setDataSource() is called in any other state.</li>
1552502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>It is good programming
1562502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         practice to always look out for <code>IllegalArgumentException</code>
1572502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         and <code>IOException</code> that may be thrown from the overloaded
1582502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <code>setDataSource</code> methods.</li>
1592502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </ul>
1602502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </li>
1612502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <li>A MediaPlayer object must first enter the <em>Prepared</em> state
1622502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         before playback can be started.
1632502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <ul>
1642502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>There are two ways (synchronous vs.
1652502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         asynchronous) that the <em>Prepared</em> state can be reached:
1662502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         either a call to {@link #prepare()} (synchronous) which
1672502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         transfers the object to the <em>Prepared</em> state once the method call
1682502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         returns, or a call to {@link #prepareAsync()} (asynchronous) which
1692502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         first transfers the object to the <em>Preparing</em> state after the
1702502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         call returns (which occurs almost right way) while the internal
1712502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         player engine continues working on the rest of preparation work
1722502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         until the preparation work completes. When the preparation completes or when {@link #prepare()} call returns,
1732502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the internal player engine then calls a user supplied callback method,
1742502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         onPrepared() of the OnPreparedListener interface, if an
1752502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         OnPreparedListener is registered beforehand via {@link
1762502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         #setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener)}.</li>
1772502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>It is important to note that
1782502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the <em>Preparing</em> state is a transient state, and the behavior
1792502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         of calling any method with side effect while a MediaPlayer object is
1802502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         in the <em>Preparing</em> state is undefined.</li>
1812502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>An IllegalStateException is
1822502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         thrown if {@link #prepare()} or {@link #prepareAsync()} is called in
1832502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         any other state.</li>
1842502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>While in the <em>Prepared</em> state, properties
1852502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         such as audio/sound volume, screenOnWhilePlaying, looping can be
1862502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         adjusted by invoking the corresponding set methods.</li>
1872502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </ul>
1882502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </li>
1892502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <li>To start the playback, {@link #start()} must be called. After
1902502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #start()} returns successfully, the MediaPlayer object is in the
1912502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <em>Started</em> state. {@link #isPlaying()} can be called to test
1922502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         whether the MediaPlayer object is in the <em>Started</em> state.
1932502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <ul>
1942502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>While in the <em>Started</em> state, the internal player engine calls
1952502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback
1962502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         method if a OnBufferingUpdateListener has been registered beforehand
1972502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         via {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}.
1982502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         This callback allows applications to keep track of the buffering status
1992502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         while streaming audio/video.</li>
2002502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>Calling {@link #start()} has not effect
2012502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         on a MediaPlayer object that is already in the <em>Started</em> state.</li>
2022502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </ul>
2032502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </li>
2042502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <li>Playback can be paused and stopped, and the current playback position
2052502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         can be adjusted. Playback can be paused via {@link #pause()}. When the call to
2062502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #pause()} returns, the MediaPlayer object enters the
2072502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <em>Paused</em> state. Note that the transition from the <em>Started</em>
2082502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         state to the <em>Paused</em> state and vice versa happens
2092502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         asynchronously in the player engine. It may take some time before
2102502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the state is updated in calls to {@link #isPlaying()}, and it can be
2112502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         a number of seconds in the case of streamed content.
2122502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <ul>
2132502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>Calling {@link #start()} to resume playback for a paused
2142502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         MediaPlayer object, and the resumed playback
2152502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         position is the same as where it was paused. When the call to
2162502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #start()} returns, the paused MediaPlayer object goes back to
2172502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the <em>Started</em> state.</li>
2182502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>Calling {@link #pause()} has no effect on
2192502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         a MediaPlayer object that is already in the <em>Paused</em> state.</li>
2202502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </ul>
2212502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </li>
2222502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <li>Calling  {@link #stop()} stops playback and causes a
2232502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         MediaPlayer in the <em>Started</em>, <em>Paused</em>, <em>Prepared
2242502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </em> or <em>PlaybackCompleted</em> state to enter the
2252502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <em>Stopped</em> state.
2262502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <ul>
2272502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>Once in the <em>Stopped</em> state, playback cannot be started
2282502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         until {@link #prepare()} or {@link #prepareAsync()} are called to set
2292502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the MediaPlayer object to the <em>Prepared</em> state again.</li>
2302502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>Calling {@link #stop()} has no effect on a MediaPlayer
2312502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         object that is already in the <em>Stopped</em> state.</li>
2322502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </ul>
2332502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </li>
2342502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <li>The playback position can be adjusted with a call to
2352502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #seekTo(int)}.
2362502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <ul>
2372502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>Although the asynchronuous {@link #seekTo(int)}
2382502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         call returns right way, the actual seek operation may take a while to
2392502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         finish, especially for audio/video being streamed. When the actual
2402502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         seek operation completes, the internal player engine calls a user
2412502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener
2422502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         has been registered beforehand via
2432502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}.</li>
2442502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>Please
2452502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         note that {@link #seekTo(int)} can also be called in the other states,
2462502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted
2472502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </em> state.</li>
2482502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>Furthermore, the actual current playback position
2492502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         can be retrieved with a call to {@link #getCurrentPosition()}, which
2502502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         is helpful for applications such as a Music player that need to keep
2512502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         track of the playback progress.</li>
2522502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </ul>
2532502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </li>
2542502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <li>When the playback reaches the end of stream, the playback completes.
2552502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <ul>
2562502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>If the looping mode was being set to <var>true</var>with
2572502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         {@link #setLooping(boolean)}, the MediaPlayer object shall remain in
2582502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the <em>Started</em> state.</li>
2592502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>If the looping mode was set to <var>false
2602502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         </var>, the player engine calls a user supplied callback method,
2612502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         OnCompletion.onCompletion(), if a OnCompletionListener is registered
2622502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         beforehand via {@link #setOnCompletionListener(OnCompletionListener)}.
2632502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         The invoke of the callback signals that the object is now in the <em>
2642502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         PlaybackCompleted</em> state.</li>
2652502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         <li>While in the <em>PlaybackCompleted</em>
2662502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         state, calling {@link #start()} can restart the playback from the
2672502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         beginning of the audio/video source.</li>
2682502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * </ul>
2692502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
2702502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
2712502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <a name="Valid_and_Invalid_States"></a>
2722502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <h3>Valid and invalid states</h3>
2732502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
2742502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <table border="0" cellspacing="0" cellpadding="0">
2752502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>Method Name </p></td>
2762502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Valid Sates </p></td>
2772502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Invalid States </p></td>
2782502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Comments </p></td></tr>
2792502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>attachAuxEffect </p></td>
2802502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
2812502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Error} </p></td>
2822502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>This method must be called after setDataSource.
2832502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     Calling it does not change the object state. </p></td></tr>
2842502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>getAudioSessionId </p></td>
2852502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>any </p></td>
2862502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{} </p></td>
2872502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>This method can be called in any state and calling it does not change
2882502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the object state. </p></td></tr>
2892502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>getCurrentPosition </p></td>
2902502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
2912502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         PlaybackCompleted} </p></td>
2922502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Error}</p></td>
2932502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method in a valid state does not change the
2942502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         state. Calling this method in an invalid state transfers the object
2952502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         to the <em>Error</em> state. </p></td></tr>
2962502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>getDuration </p></td>
2972502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
2982502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Initialized, Error} </p></td>
2992502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method in a valid state does not change the
3002502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         state. Calling this method in an invalid state transfers the object
3012502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         to the <em>Error</em> state. </p></td></tr>
3022502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>getVideoHeight </p></td>
3032502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
3042502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         PlaybackCompleted}</p></td>
3052502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Error}</p></td>
3062502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method in a valid state does not change the
3072502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         state. Calling this method in an invalid state transfers the object
3082502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         to the <em>Error</em> state.  </p></td></tr>
3092502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>getVideoWidth </p></td>
3102502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
3112502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         PlaybackCompleted}</p></td>
3122502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Error}</p></td>
3132502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method in a valid state does not change
3142502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the state. Calling this method in an invalid state transfers the
3152502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         object to the <em>Error</em> state. </p></td></tr>
3162502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>isPlaying </p></td>
3172502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
3182502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *          PlaybackCompleted}</p></td>
3192502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Error}</p></td>
3202502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method in a valid state does not change
3212502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the state. Calling this method in an invalid state transfers the
3222502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         object to the <em>Error</em> state. </p></td></tr>
3232502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>pause </p></td>
3242502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Started, Paused}</p></td>
3252502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Initialized, Prepared, Stopped, PlaybackCompleted, Error}</p></td>
3262502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method in a valid state transfers the
3272502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         object to the <em>Paused</em> state. Calling this method in an
3282502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
3292502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>prepare </p></td>
3302502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Initialized, Stopped} </p></td>
3312502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
3322502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method in a valid state transfers the
3332502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         object to the <em>Prepared</em> state. Calling this method in an
3342502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         invalid state throws an IllegalStateException.</p></td></tr>
3352502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>prepareAsync </p></td>
3362502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Initialized, Stopped} </p></td>
3372502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
3382502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method in a valid state transfers the
3392502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         object to the <em>Preparing</em> state. Calling this method in an
3402502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         invalid state throws an IllegalStateException.</p></td></tr>
3412502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>release </p></td>
3422502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>any </p></td>
3432502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{} </p></td>
3442502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>After {@link #release()}, the object is no longer available. </p></td></tr>
3452502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>reset </p></td>
3462502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
3472502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         PlaybackCompleted, Error}</p></td>
3482502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{}</p></td>
3492502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>After {@link #reset()}, the object is like being just created.</p></td></tr>
3502502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>seekTo </p></td>
3512502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Prepared, Started, Paused, PlaybackCompleted} </p></td>
3522502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Initialized, Stopped, Error}</p></td>
3532502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method in a valid state does not change
3542502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the state. Calling this method in an invalid state transfers the
3552502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         object to the <em>Error</em> state. </p></td></tr>
3562502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setAudioSessionId </p></td>
3572502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle} </p></td>
3582502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
3592502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *          Error} </p></td>
3602502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>This method must be called in idle state as the audio session ID must be known before
3612502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         calling setDataSource. Calling it does not change the object state. </p></td></tr>
3622502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setAudioStreamType </p></td>
3632502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
3642502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *          PlaybackCompleted}</p></td>
3652502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Error}</p></td>
3662502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method does not change the state. In order for the
3672502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         target audio stream type to become effective, this method must be called before
3682502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         prepare() or prepareAsync().</p></td></tr>
3692502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setAuxEffectSendLevel </p></td>
3702502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>any</p></td>
3712502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{} </p></td>
3722502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Calling this method does not change the object state. </p></td></tr>
3732502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setDataSource </p></td>
3742502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle} </p></td>
3752502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
3762502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *          Error} </p></td>
3772502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method in a valid state transfers the
3782502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         object to the <em>Initialized</em> state. Calling this method in an
3792502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         invalid state throws an IllegalStateException.</p></td></tr>
3802502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setDisplay </p></td>
3812502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>any </p></td>
3822502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{} </p></td>
3832502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>This method can be called in any state and calling it does not change
3842502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the object state. </p></td></tr>
3852502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setTexture </p></td>
3862502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>any </p></td>
3872502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{} </p></td>
3882502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>This method can be called in any state and calling it does not change
3892502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the object state. </p></td></tr>
3902502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setLooping </p></td>
3912502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
3922502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         PlaybackCompleted}</p></td>
3932502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Error}</p></td>
3942502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method in a valid state does not change
3952502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the state. Calling this method in an
3962502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
3972502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>isLooping </p></td>
3982502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>any </p></td>
3992502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{} </p></td>
4002502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>This method can be called in any state and calling it does not change
4012502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the object state. </p></td></tr>
4022502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setOnBufferingUpdateListener </p></td>
4032502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>any </p></td>
4042502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{} </p></td>
4052502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>This method can be called in any state and calling it does not change
4062502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the object state. </p></td></tr>
4072502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setOnCompletionListener </p></td>
4082502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>any </p></td>
4092502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{} </p></td>
4102502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>This method can be called in any state and calling it does not change
4112502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the object state. </p></td></tr>
4122502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setOnErrorListener </p></td>
4132502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>any </p></td>
4142502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{} </p></td>
4152502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>This method can be called in any state and calling it does not change
4162502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the object state. </p></td></tr>
4172502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setOnPreparedListener </p></td>
4182502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>any </p></td>
4192502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{} </p></td>
4202502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>This method can be called in any state and calling it does not change
4212502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the object state. </p></td></tr>
4222502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setOnSeekCompleteListener </p></td>
4232502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>any </p></td>
4242502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{} </p></td>
4252502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>This method can be called in any state and calling it does not change
4262502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the object state. </p></td></tr>
4272502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setScreenOnWhilePlaying</></td>
4282502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>any </p></td>
4292502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{} </p></td>
4302502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>This method can be called in any state and calling it does not change
4312502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the object state.  </p></td></tr>
4322502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setVolume </p></td>
4332502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
4342502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *          PlaybackCompleted}</p></td>
4352502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Error}</p></td>
4362502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method does not change the state.
4372502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>setWakeMode </p></td>
4382502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>any </p></td>
4392502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{} </p></td>
4402502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>This method can be called in any state and calling it does not change
4412502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         the object state.</p></td></tr>
4422502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>start </p></td>
4432502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Prepared, Started, Paused, PlaybackCompleted}</p></td>
4442502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Initialized, Stopped, Error}</p></td>
4452502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method in a valid state transfers the
4462502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         object to the <em>Started</em> state. Calling this method in an
4472502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
4482502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <tr><td>stop </p></td>
4492502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
4502502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>{Idle, Initialized, Error}</p></td>
4512502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *     <td>Successful invoke of this method in a valid state transfers the
4522502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         object to the <em>Stopped</em> state. Calling this method in an
4532502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
4542502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
4552502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * </table>
4562502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
4572502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <a name="Permissions"></a>
4582502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <h3>Permissions</h3>
4592502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <p>One may need to declare a corresponding WAKE_LOCK permission {@link
4602502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
4612502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * element.
4622502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
4632502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <a name="Callbacks"></a>
4642502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <h3>Callbacks</h3>
4652502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * <p>Applications may want to register for informational and error
4662502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * events in order to be informed of some internal state update and
4672502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * possible runtime errors during playback or streaming. Registration for
4682502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * these events is done by properly setting the appropriate listeners (via calls
4692502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * to
4702502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * {@link #setOnPreparedListener(OnPreparedListener)}setOnPreparedListener,
4712502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}setOnVideoSizeChangedListener,
4722502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}setOnSeekCompleteListener,
4732502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * {@link #setOnCompletionListener(OnCompletionListener)}setOnCompletionListener,
4742502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}setOnBufferingUpdateListener,
4752502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener,
4762502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener, etc).
4772502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * In order to receive the respective callback
4782502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * associated with these listeners, applications are required to create
4792502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * MediaPlayer objects on a thread with its own Looper running (main UI
4802502e004d93734a99bdfeab811b3c5ae06f45becbuzbee * thread by default has a Looper running).
4812502e004d93734a99bdfeab811b3c5ae06f45becbuzbee *
4822502e004d93734a99bdfeab811b3c5ae06f45becbuzbee */
4832502e004d93734a99bdfeab811b3c5ae06f45becbuzbeepublic class MediaPlayer
4842502e004d93734a99bdfeab811b3c5ae06f45becbuzbee{
4852502e004d93734a99bdfeab811b3c5ae06f45becbuzbee    /**
4862502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       Constant to retrieve only the new metadata since the last
4872502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       call.
4882502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       // FIXME: unhide.
4892502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       // FIXME: add link to getMetadata(boolean, boolean)
4902502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       {@hide}
4912502e004d93734a99bdfeab811b3c5ae06f45becbuzbee     */
4922502e004d93734a99bdfeab811b3c5ae06f45becbuzbee    public static final boolean METADATA_UPDATE_ONLY = true;
4932502e004d93734a99bdfeab811b3c5ae06f45becbuzbee
4942502e004d93734a99bdfeab811b3c5ae06f45becbuzbee    /**
4952502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       Constant to retrieve all the metadata.
4962502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       // FIXME: unhide.
4972502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       // FIXME: add link to getMetadata(boolean, boolean)
4982502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       {@hide}
4992502e004d93734a99bdfeab811b3c5ae06f45becbuzbee     */
5002502e004d93734a99bdfeab811b3c5ae06f45becbuzbee    public static final boolean METADATA_ALL = false;
5012502e004d93734a99bdfeab811b3c5ae06f45becbuzbee
5022502e004d93734a99bdfeab811b3c5ae06f45becbuzbee    /**
5032502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       Constant to enable the metadata filter during retrieval.
5042502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       // FIXME: unhide.
5052502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       // FIXME: add link to getMetadata(boolean, boolean)
5062502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       {@hide}
5072502e004d93734a99bdfeab811b3c5ae06f45becbuzbee     */
5082502e004d93734a99bdfeab811b3c5ae06f45becbuzbee    public static final boolean APPLY_METADATA_FILTER = true;
5092502e004d93734a99bdfeab811b3c5ae06f45becbuzbee
5102502e004d93734a99bdfeab811b3c5ae06f45becbuzbee    /**
5112502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       Constant to disable the metadata filter during retrieval.
5122502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       // FIXME: unhide.
5132502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       // FIXME: add link to getMetadata(boolean, boolean)
5142502e004d93734a99bdfeab811b3c5ae06f45becbuzbee       {@hide}
5152502e004d93734a99bdfeab811b3c5ae06f45becbuzbee     */
5162502e004d93734a99bdfeab811b3c5ae06f45becbuzbee    public static final boolean BYPASS_METADATA_FILTER = false;
517
518    static {
519        System.loadLibrary("media_jni");
520        native_init();
521    }
522
523    private final static String TAG = "MediaPlayer";
524    // Name of the remote interface for the media player. Must be kept
525    // in sync with the 2nd parameter of the IMPLEMENT_META_INTERFACE
526    // macro invocation in IMediaPlayer.cpp
527    private final static String IMEDIA_PLAYER = "android.media.IMediaPlayer";
528
529    private int mNativeContext; // accessed by native methods
530    private int mListenerContext; // accessed by native methods
531    private Surface mSurface; // accessed by native methods
532    private SurfaceHolder  mSurfaceHolder;
533    private ParcelSurfaceTexture mParcelSurfaceTexture; // accessed by native methods
534    private EventHandler mEventHandler;
535    private PowerManager.WakeLock mWakeLock = null;
536    private boolean mScreenOnWhilePlaying;
537    private boolean mStayAwake;
538
539    /**
540     * Default constructor. Consider using one of the create() methods for
541     * synchronously instantiating a MediaPlayer from a Uri or resource.
542     * <p>When done with the MediaPlayer, you should call  {@link #release()},
543     * to free the resources. If not released, too many MediaPlayer instances may
544     * result in an exception.</p>
545     */
546    public MediaPlayer() {
547
548        Looper looper;
549        if ((looper = Looper.myLooper()) != null) {
550            mEventHandler = new EventHandler(this, looper);
551        } else if ((looper = Looper.getMainLooper()) != null) {
552            mEventHandler = new EventHandler(this, looper);
553        } else {
554            mEventHandler = null;
555        }
556
557        /* Native setup requires a weak reference to our object.
558         * It's easier to create it here than in C++.
559         */
560        native_setup(new WeakReference<MediaPlayer>(this));
561    }
562
563    /*
564     * Update the MediaPlayer ISurface and ISurfaceTexture.
565     * Call after updating mSurface and/or mParcelSurfaceTexture.
566     */
567    private native void _setVideoSurfaceOrSurfaceTexture();
568
569    /**
570     * Create a request parcel which can be routed to the native media
571     * player using {@link #invoke(Parcel, Parcel)}. The Parcel
572     * returned has the proper InterfaceToken set. The caller should
573     * not overwrite that token, i.e it can only append data to the
574     * Parcel.
575     *
576     * @return A parcel suitable to hold a request for the native
577     * player.
578     * {@hide}
579     */
580    public Parcel newRequest() {
581        Parcel parcel = Parcel.obtain();
582        parcel.writeInterfaceToken(IMEDIA_PLAYER);
583        return parcel;
584    }
585
586    /**
587     * Invoke a generic method on the native player using opaque
588     * parcels for the request and reply. Both payloads' format is a
589     * convention between the java caller and the native player.
590     * Must be called after setDataSource to make sure a native player
591     * exists.
592     *
593     * @param request Parcel with the data for the extension. The
594     * caller must use {@link #newRequest()} to get one.
595     *
596     * @param reply Output parcel with the data returned by the
597     * native player.
598     *
599     * @return The status code see utils/Errors.h
600     * {@hide}
601     */
602    public int invoke(Parcel request, Parcel reply) {
603        int retcode = native_invoke(request, reply);
604        reply.setDataPosition(0);
605        return retcode;
606    }
607
608    /**
609     * Sets the {@link SurfaceHolder} to use for displaying the video
610     * portion of the media.  A surface must be set if a display is
611     * needed.  Not calling this method when playing back a video will
612     * result in only the audio track being played.
613     *
614     * @param sh the SurfaceHolder to use for video display
615     */
616    /*
617     * This portion of comment has a non-Javadoc prefix so as not to refer to a
618     * hidden method. When unhidden, merge it with the previous javadoc comment.
619     *
620     * Either a surface or surface texture must be set if a display or video sink
621     * is needed.  Not calling this method or {@link #setTexture(SurfaceTexture)}
622     * when playing back a video will result in only the audio track being played.
623     */
624    public void setDisplay(SurfaceHolder sh) {
625        mSurfaceHolder = sh;
626        if (sh != null) {
627            mSurface = sh.getSurface();
628        } else {
629            mSurface = null;
630        }
631        mParcelSurfaceTexture = null;
632        _setVideoSurfaceOrSurfaceTexture();
633        updateSurfaceScreenOn();
634    }
635
636    /**
637     * Sets the {@link SurfaceTexture} to be used as the sink for the
638     * video portion of the media. Either a surface or surface texture
639     * must be set if a video sink is needed.  The same surface texture
640     * can be re-set without harm. Setting a surface texture will un-set
641     * any surface that was set via {@link #setDisplay(SurfaceHolder)}.
642     * Not calling this method or {@link #setDisplay(SurfaceHolder)}
643     * when playing back a video will result in only the audio track
644     * being played. Note that if a SurfaceTexture is used, the value
645     * set via setScreenOnWhilePlaying has no effect.
646     *
647     * The timestamps provided by {@link SurfaceTexture#getTimestamp()} for a
648     * SurfaceTexture set as the video sink have an unspecified zero point,
649     * and cannot be directly compared between different media sources or different
650     * instances of the same media source, or across multiple runs of the same
651     * program.
652     */
653    public void setTexture(SurfaceTexture st) {
654        ParcelSurfaceTexture pst = null;
655        if (st != null) {
656            pst = ParcelSurfaceTexture.fromSurfaceTexture(st);
657        }
658        setParcelSurfaceTexture(pst);
659    }
660
661    /**
662     * Sets the {@link ParcelSurfaceTexture} to be used as the sink for the video portion of
663     * the media. This is similar to {@link #setTexture(SurfaceTexture)}, but supports using
664     * a {@link ParcelSurfaceTexture} to transport the texture to be used via Binder. Setting
665     * a parceled surface texture will un-set any surface or surface texture that was previously
666     * set. See {@link #setTexture(SurfaceTexture)} for more details.
667     *
668     * @param pst The {@link ParcelSurfaceTexture} to be used as the sink for
669     * the video portion of the media.
670     *
671     * @hide Pending review by API council.
672     */
673    public void setParcelSurfaceTexture(ParcelSurfaceTexture pst) {
674        if (mScreenOnWhilePlaying && pst != null && mParcelSurfaceTexture == null) {
675            Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for SurfaceTexture");
676        }
677        mSurfaceHolder = null;
678        mSurface = null;
679        mParcelSurfaceTexture = pst;
680        _setVideoSurfaceOrSurfaceTexture();
681        updateSurfaceScreenOn();
682    }
683
684    /**
685     * Convenience method to create a MediaPlayer for a given Uri.
686     * On success, {@link #prepare()} will already have been called and must not be called again.
687     * <p>When done with the MediaPlayer, you should call  {@link #release()},
688     * to free the resources. If not released, too many MediaPlayer instances will
689     * result in an exception.</p>
690     *
691     * @param context the Context to use
692     * @param uri the Uri from which to get the datasource
693     * @return a MediaPlayer object, or null if creation failed
694     */
695    public static MediaPlayer create(Context context, Uri uri) {
696        return create (context, uri, null);
697    }
698
699    /**
700     * Convenience method to create a MediaPlayer for a given Uri.
701     * On success, {@link #prepare()} will already have been called and must not be called again.
702     * <p>When done with the MediaPlayer, you should call  {@link #release()},
703     * to free the resources. If not released, too many MediaPlayer instances will
704     * result in an exception.</p>
705     *
706     * @param context the Context to use
707     * @param uri the Uri from which to get the datasource
708     * @param holder the SurfaceHolder to use for displaying the video
709     * @return a MediaPlayer object, or null if creation failed
710     */
711    public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) {
712
713        try {
714            MediaPlayer mp = new MediaPlayer();
715            mp.setDataSource(context, uri);
716            if (holder != null) {
717                mp.setDisplay(holder);
718            }
719            mp.prepare();
720            return mp;
721        } catch (IOException ex) {
722            Log.d(TAG, "create failed:", ex);
723            // fall through
724        } catch (IllegalArgumentException ex) {
725            Log.d(TAG, "create failed:", ex);
726            // fall through
727        } catch (SecurityException ex) {
728            Log.d(TAG, "create failed:", ex);
729            // fall through
730        }
731
732        return null;
733    }
734
735    // Note no convenience method to create a MediaPlayer with SurfaceTexture sink.
736
737    /**
738     * Convenience method to create a MediaPlayer for a given resource id.
739     * On success, {@link #prepare()} will already have been called and must not be called again.
740     * <p>When done with the MediaPlayer, you should call  {@link #release()},
741     * to free the resources. If not released, too many MediaPlayer instances will
742     * result in an exception.</p>
743     *
744     * @param context the Context to use
745     * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
746     *              the resource to use as the datasource
747     * @return a MediaPlayer object, or null if creation failed
748     */
749    public static MediaPlayer create(Context context, int resid) {
750        try {
751            AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
752            if (afd == null) return null;
753
754            MediaPlayer mp = new MediaPlayer();
755            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
756            afd.close();
757            mp.prepare();
758            return mp;
759        } catch (IOException ex) {
760            Log.d(TAG, "create failed:", ex);
761            // fall through
762        } catch (IllegalArgumentException ex) {
763            Log.d(TAG, "create failed:", ex);
764           // fall through
765        } catch (SecurityException ex) {
766            Log.d(TAG, "create failed:", ex);
767            // fall through
768        }
769        return null;
770    }
771
772    /**
773     * Sets the data source as a content Uri.
774     *
775     * @param context the Context to use when resolving the Uri
776     * @param uri the Content URI of the data you want to play
777     * @throws IllegalStateException if it is called in an invalid state
778     */
779    public void setDataSource(Context context, Uri uri)
780        throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
781        setDataSource(context, uri, null);
782    }
783
784    /**
785     * Sets the data source as a content Uri.
786     *
787     * @param context the Context to use when resolving the Uri
788     * @param uri the Content URI of the data you want to play
789     * @param headers the headers to be sent together with the request for the data
790     * @throws IllegalStateException if it is called in an invalid state
791     */
792    public void setDataSource(Context context, Uri uri, Map<String, String> headers)
793        throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
794
795        String scheme = uri.getScheme();
796        if(scheme == null || scheme.equals("file")) {
797            setDataSource(uri.getPath());
798            return;
799        }
800
801        AssetFileDescriptor fd = null;
802        try {
803            ContentResolver resolver = context.getContentResolver();
804            fd = resolver.openAssetFileDescriptor(uri, "r");
805            if (fd == null) {
806                return;
807            }
808            // Note: using getDeclaredLength so that our behavior is the same
809            // as previous versions when the content provider is returning
810            // a full file.
811            if (fd.getDeclaredLength() < 0) {
812                setDataSource(fd.getFileDescriptor());
813            } else {
814                setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getDeclaredLength());
815            }
816            return;
817        } catch (SecurityException ex) {
818        } catch (IOException ex) {
819        } finally {
820            if (fd != null) {
821                fd.close();
822            }
823        }
824        Log.d(TAG, "Couldn't open file on client side, trying server side");
825        setDataSource(uri.toString(), headers);
826        return;
827    }
828
829    /**
830     * Sets the data source (file-path or http/rtsp URL) to use.
831     *
832     * @param path the path of the file, or the http/rtsp URL of the stream you want to play
833     * @throws IllegalStateException if it is called in an invalid state
834     */
835    public native void setDataSource(String path) throws IOException, IllegalArgumentException, IllegalStateException;
836
837    /**
838     * Sets the data source (file-path or http/rtsp URL) to use.
839     *
840     * @param path the path of the file, or the http/rtsp URL of the stream you want to play
841     * @param headers the headers associated with the http request for the stream you want to play
842     * @throws IllegalStateException if it is called in an invalid state
843     * @hide pending API council
844     */
845    public void setDataSource(String path, Map<String, String> headers)
846            throws IOException, IllegalArgumentException, IllegalStateException
847    {
848        String[] keys = null;
849        String[] values = null;
850
851        if (headers != null) {
852            keys = new String[headers.size()];
853            values = new String[headers.size()];
854
855            int i = 0;
856            for (Map.Entry<String, String> entry: headers.entrySet()) {
857                keys[i] = entry.getKey();
858                values[i] = entry.getValue();
859                ++i;
860            }
861        }
862        _setDataSource(path, keys, values);
863    }
864
865    private native void _setDataSource(
866        String path, String[] keys, String[] values)
867        throws IOException, IllegalArgumentException, IllegalStateException;
868
869    /**
870     * Sets the data source (FileDescriptor) to use. It is the caller's responsibility
871     * to close the file descriptor. It is safe to do so as soon as this call returns.
872     *
873     * @param fd the FileDescriptor for the file you want to play
874     * @throws IllegalStateException if it is called in an invalid state
875     */
876    public void setDataSource(FileDescriptor fd)
877            throws IOException, IllegalArgumentException, IllegalStateException {
878        // intentionally less than LONG_MAX
879        setDataSource(fd, 0, 0x7ffffffffffffffL);
880    }
881
882    /**
883     * Sets the data source (FileDescriptor) to use.  The FileDescriptor must be
884     * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility
885     * to close the file descriptor. It is safe to do so as soon as this call returns.
886     *
887     * @param fd the FileDescriptor for the file you want to play
888     * @param offset the offset into the file where the data to be played starts, in bytes
889     * @param length the length in bytes of the data to be played
890     * @throws IllegalStateException if it is called in an invalid state
891     */
892    public native void setDataSource(FileDescriptor fd, long offset, long length)
893            throws IOException, IllegalArgumentException, IllegalStateException;
894
895    /**
896     * Prepares the player for playback, synchronously.
897     *
898     * After setting the datasource and the display surface, you need to either
899     * call prepare() or prepareAsync(). For files, it is OK to call prepare(),
900     * which blocks until MediaPlayer is ready for playback.
901     *
902     * @throws IllegalStateException if it is called in an invalid state
903     */
904    public native void prepare() throws IOException, IllegalStateException;
905
906    /**
907     * Prepares the player for playback, asynchronously.
908     *
909     * After setting the datasource and the display surface, you need to either
910     * call prepare() or prepareAsync(). For streams, you should call prepareAsync(),
911     * which returns immediately, rather than blocking until enough data has been
912     * buffered.
913     *
914     * @throws IllegalStateException if it is called in an invalid state
915     */
916    public native void prepareAsync() throws IllegalStateException;
917
918    /**
919     * Starts or resumes playback. If playback had previously been paused,
920     * playback will continue from where it was paused. If playback had
921     * been stopped, or never started before, playback will start at the
922     * beginning.
923     *
924     * @throws IllegalStateException if it is called in an invalid state
925     */
926    public  void start() throws IllegalStateException {
927        stayAwake(true);
928        _start();
929    }
930
931    private native void _start() throws IllegalStateException;
932
933    /**
934     * Stops playback after playback has been stopped or paused.
935     *
936     * @throws IllegalStateException if the internal player engine has not been
937     * initialized.
938     */
939    public void stop() throws IllegalStateException {
940        stayAwake(false);
941        _stop();
942    }
943
944    private native void _stop() throws IllegalStateException;
945
946    /**
947     * Pauses playback. Call start() to resume.
948     *
949     * @throws IllegalStateException if the internal player engine has not been
950     * initialized.
951     */
952    public void pause() throws IllegalStateException {
953        stayAwake(false);
954        _pause();
955    }
956
957    private native void _pause() throws IllegalStateException;
958
959    /**
960     * Set the low-level power management behavior for this MediaPlayer.  This
961     * can be used when the MediaPlayer is not playing through a SurfaceHolder
962     * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
963     * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
964     *
965     * <p>This function has the MediaPlayer access the low-level power manager
966     * service to control the device's power usage while playing is occurring.
967     * The parameter is a combination of {@link android.os.PowerManager} wake flags.
968     * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
969     * permission.
970     * By default, no attempt is made to keep the device awake during playback.
971     *
972     * @param context the Context to use
973     * @param mode    the power/wake mode to set
974     * @see android.os.PowerManager
975     */
976    public void setWakeMode(Context context, int mode) {
977        boolean washeld = false;
978        if (mWakeLock != null) {
979            if (mWakeLock.isHeld()) {
980                washeld = true;
981                mWakeLock.release();
982            }
983            mWakeLock = null;
984        }
985
986        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
987        mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
988        mWakeLock.setReferenceCounted(false);
989        if (washeld) {
990            mWakeLock.acquire();
991        }
992    }
993
994    /**
995     * Control whether we should use the attached SurfaceHolder to keep the
996     * screen on while video playback is occurring.  This is the preferred
997     * method over {@link #setWakeMode} where possible, since it doesn't
998     * require that the application have permission for low-level wake lock
999     * access.
1000     *
1001     * @param screenOn Supply true to keep the screen on, false to allow it
1002     * to turn off.
1003     */
1004    public void setScreenOnWhilePlaying(boolean screenOn) {
1005        if (mScreenOnWhilePlaying != screenOn) {
1006            if (screenOn && mParcelSurfaceTexture != null) {
1007                Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for SurfaceTexture");
1008            }
1009            mScreenOnWhilePlaying = screenOn;
1010            updateSurfaceScreenOn();
1011        }
1012    }
1013
1014    private void stayAwake(boolean awake) {
1015        if (mWakeLock != null) {
1016            if (awake && !mWakeLock.isHeld()) {
1017                mWakeLock.acquire();
1018            } else if (!awake && mWakeLock.isHeld()) {
1019                mWakeLock.release();
1020            }
1021        }
1022        mStayAwake = awake;
1023        updateSurfaceScreenOn();
1024    }
1025
1026    private void updateSurfaceScreenOn() {
1027        if (mSurfaceHolder != null) {
1028            mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
1029        }
1030    }
1031
1032    /**
1033     * Returns the width of the video.
1034     *
1035     * @return the width of the video, or 0 if there is no video,
1036     * no display surface was set, or the width has not been determined
1037     * yet. The OnVideoSizeChangedListener can be registered via
1038     * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1039     * to provide a notification when the width is available.
1040     */
1041    public native int getVideoWidth();
1042
1043    /**
1044     * Returns the height of the video.
1045     *
1046     * @return the height of the video, or 0 if there is no video,
1047     * no display surface was set, or the height has not been determined
1048     * yet. The OnVideoSizeChangedListener can be registered via
1049     * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1050     * to provide a notification when the height is available.
1051     */
1052    public native int getVideoHeight();
1053
1054    /**
1055     * Checks whether the MediaPlayer is playing.
1056     *
1057     * @return true if currently playing, false otherwise
1058     */
1059    public native boolean isPlaying();
1060
1061    /**
1062     * Seeks to specified time position.
1063     *
1064     * @param msec the offset in milliseconds from the start to seek to
1065     * @throws IllegalStateException if the internal player engine has not been
1066     * initialized
1067     */
1068    public native void seekTo(int msec) throws IllegalStateException;
1069
1070    /**
1071     * Gets the current playback position.
1072     *
1073     * @return the current position in milliseconds
1074     */
1075    public native int getCurrentPosition();
1076
1077    /**
1078     * Gets the duration of the file.
1079     *
1080     * @return the duration in milliseconds
1081     */
1082    public native int getDuration();
1083
1084    /**
1085     * Gets the media metadata.
1086     *
1087     * @param update_only controls whether the full set of available
1088     * metadata is returned or just the set that changed since the
1089     * last call. See {@see #METADATA_UPDATE_ONLY} and {@see
1090     * #METADATA_ALL}.
1091     *
1092     * @param apply_filter if true only metadata that matches the
1093     * filter is returned. See {@see #APPLY_METADATA_FILTER} and {@see
1094     * #BYPASS_METADATA_FILTER}.
1095     *
1096     * @return The metadata, possibly empty. null if an error occured.
1097     // FIXME: unhide.
1098     * {@hide}
1099     */
1100    public Metadata getMetadata(final boolean update_only,
1101                                final boolean apply_filter) {
1102        Parcel reply = Parcel.obtain();
1103        Metadata data = new Metadata();
1104
1105        if (!native_getMetadata(update_only, apply_filter, reply)) {
1106            reply.recycle();
1107            return null;
1108        }
1109
1110        // Metadata takes over the parcel, don't recycle it unless
1111        // there is an error.
1112        if (!data.parse(reply)) {
1113            reply.recycle();
1114            return null;
1115        }
1116        return data;
1117    }
1118
1119    /**
1120     * Set a filter for the metadata update notification and update
1121     * retrieval. The caller provides 2 set of metadata keys, allowed
1122     * and blocked. The blocked set always takes precedence over the
1123     * allowed one.
1124     * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as
1125     * shorthands to allow/block all or no metadata.
1126     *
1127     * By default, there is no filter set.
1128     *
1129     * @param allow Is the set of metadata the client is interested
1130     *              in receiving new notifications for.
1131     * @param block Is the set of metadata the client is not interested
1132     *              in receiving new notifications for.
1133     * @return The call status code.
1134     *
1135     // FIXME: unhide.
1136     * {@hide}
1137     */
1138    public int setMetadataFilter(Set<Integer> allow, Set<Integer> block) {
1139        // Do our serialization manually instead of calling
1140        // Parcel.writeArray since the sets are made of the same type
1141        // we avoid paying the price of calling writeValue (used by
1142        // writeArray) which burns an extra int per element to encode
1143        // the type.
1144        Parcel request =  newRequest();
1145
1146        // The parcel starts already with an interface token. There
1147        // are 2 filters. Each one starts with a 4bytes number to
1148        // store the len followed by a number of int (4 bytes as well)
1149        // representing the metadata type.
1150        int capacity = request.dataSize() + 4 * (1 + allow.size() + 1 + block.size());
1151
1152        if (request.dataCapacity() < capacity) {
1153            request.setDataCapacity(capacity);
1154        }
1155
1156        request.writeInt(allow.size());
1157        for(Integer t: allow) {
1158            request.writeInt(t);
1159        }
1160        request.writeInt(block.size());
1161        for(Integer t: block) {
1162            request.writeInt(t);
1163        }
1164        return native_setMetadataFilter(request);
1165    }
1166
1167    /**
1168     * Releases resources associated with this MediaPlayer object.
1169     * It is considered good practice to call this method when you're
1170     * done using the MediaPlayer. For instance, whenever the Activity
1171     * of an application is paused, this method should be invoked to
1172     * release the MediaPlayer object. In addition to unnecessary resources
1173     * (such as memory and instances of codecs) being hold, failure to
1174     * call this method immediately if a MediaPlayer object is no longer
1175     * needed may also lead to continuous battery consumption for mobile
1176     * devices, and playback failure if no multiple instances of the
1177     * same codec is supported on a device.
1178     */
1179    public void release() {
1180        stayAwake(false);
1181        updateSurfaceScreenOn();
1182        mOnPreparedListener = null;
1183        mOnBufferingUpdateListener = null;
1184        mOnCompletionListener = null;
1185        mOnSeekCompleteListener = null;
1186        mOnErrorListener = null;
1187        mOnInfoListener = null;
1188        mOnVideoSizeChangedListener = null;
1189        mOnTimedTextListener = null;
1190        _release();
1191    }
1192
1193    private native void _release();
1194
1195    /**
1196     * Resets the MediaPlayer to its uninitialized state. After calling
1197     * this method, you will have to initialize it again by setting the
1198     * data source and calling prepare().
1199     */
1200    public void reset() {
1201        stayAwake(false);
1202        _reset();
1203        // make sure none of the listeners get called anymore
1204        mEventHandler.removeCallbacksAndMessages(null);
1205    }
1206
1207    private native void _reset();
1208
1209    /**
1210     * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
1211     * for a list of stream types. Must call this method before prepare() or
1212     * prepareAsync() in order for the target stream type to become effective
1213     * thereafter.
1214     *
1215     * @param streamtype the audio stream type
1216     * @see android.media.AudioManager
1217     */
1218    public native void setAudioStreamType(int streamtype);
1219
1220    /**
1221     * Sets the player to be looping or non-looping.
1222     *
1223     * @param looping whether to loop or not
1224     */
1225    public native void setLooping(boolean looping);
1226
1227    /**
1228     * Checks whether the MediaPlayer is looping or non-looping.
1229     *
1230     * @return true if the MediaPlayer is currently looping, false otherwise
1231     */
1232    public native boolean isLooping();
1233
1234    /**
1235     * Sets the volume on this player.
1236     * This API is recommended for balancing the output of audio streams
1237     * within an application. Unless you are writing an application to
1238     * control user settings, this API should be used in preference to
1239     * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
1240     * a particular type. Note that the passed volume values are raw scalars.
1241     * UI controls should be scaled logarithmically.
1242     *
1243     * @param leftVolume left volume scalar
1244     * @param rightVolume right volume scalar
1245     */
1246    public native void setVolume(float leftVolume, float rightVolume);
1247
1248    /**
1249     * Currently not implemented, returns null.
1250     * @deprecated
1251     * @hide
1252     */
1253    public native Bitmap getFrameAt(int msec) throws IllegalStateException;
1254
1255    /**
1256     * Sets the audio session ID.
1257     *
1258     * @param sessionId the audio session ID.
1259     * The audio session ID is a system wide unique identifier for the audio stream played by
1260     * this MediaPlayer instance.
1261     * The primary use of the audio session ID  is to associate audio effects to a particular
1262     * instance of MediaPlayer: if an audio session ID is provided when creating an audio effect,
1263     * this effect will be applied only to the audio content of media players within the same
1264     * audio session and not to the output mix.
1265     * When created, a MediaPlayer instance automatically generates its own audio session ID.
1266     * However, it is possible to force this player to be part of an already existing audio session
1267     * by calling this method.
1268     * This method must be called before one of the overloaded <code> setDataSource </code> methods.
1269     * @throws IllegalStateException if it is called in an invalid state
1270     */
1271    public native void setAudioSessionId(int sessionId)  throws IllegalArgumentException, IllegalStateException;
1272
1273    /**
1274     * Returns the audio session ID.
1275     *
1276     * @return the audio session ID. {@see #setAudioSessionId(int)}
1277     * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer was contructed.
1278     */
1279    public native int getAudioSessionId();
1280
1281    /**
1282     * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation
1283     * effect which can be applied on any sound source that directs a certain amount of its
1284     * energy to this effect. This amount is defined by setAuxEffectSendLevel().
1285     * {@see #setAuxEffectSendLevel(float)}.
1286     * <p>After creating an auxiliary effect (e.g.
1287     * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
1288     * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method
1289     * to attach the player to the effect.
1290     * <p>To detach the effect from the player, call this method with a null effect id.
1291     * <p>This method must be called after one of the overloaded <code> setDataSource </code>
1292     * methods.
1293     * @param effectId system wide unique id of the effect to attach
1294     */
1295    public native void attachAuxEffect(int effectId);
1296
1297    /* Do not change these values (starting with KEY_PARAMETER) without updating
1298     * their counterparts in include/media/mediaplayer.h!
1299     */
1300    /*
1301     * Key used in setParameter method.
1302     * Indicates the index of the timed text track to be enabled/disabled.
1303     * The index includes both the in-band and out-of-band timed text.
1304     * The index should start from in-band text if any. Application can retrieve the number
1305     * of in-band text tracks by using MediaMetadataRetriever::extractMetadata().
1306     * Note it might take a few hundred ms to scan an out-of-band text file
1307     * before displaying it.
1308     */
1309    private static final int KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX = 1000;
1310    /*
1311     * Key used in setParameter method.
1312     * Used to add out-of-band timed text source path.
1313     * Application can add multiple text sources by calling setParameter() with
1314     * KEY_PARAMETER_TIMED_TEXT_ADD_OUT_OF_BAND_SOURCE multiple times.
1315     */
1316    private static final int KEY_PARAMETER_TIMED_TEXT_ADD_OUT_OF_BAND_SOURCE = 1001;
1317
1318    /**
1319     * Sets the parameter indicated by key.
1320     * @param key key indicates the parameter to be set.
1321     * @param value value of the parameter to be set.
1322     * @return true if the parameter is set successfully, false otherwise
1323     * {@hide}
1324     */
1325    public native boolean setParameter(int key, Parcel value);
1326
1327    /**
1328     * Sets the parameter indicated by key.
1329     * @param key key indicates the parameter to be set.
1330     * @param value value of the parameter to be set.
1331     * @return true if the parameter is set successfully, false otherwise
1332     * {@hide}
1333     */
1334    public boolean setParameter(int key, String value) {
1335        Parcel p = Parcel.obtain();
1336        p.writeString(value);
1337        return setParameter(key, p);
1338    }
1339
1340    /**
1341     * Sets the parameter indicated by key.
1342     * @param key key indicates the parameter to be set.
1343     * @param value value of the parameter to be set.
1344     * @return true if the parameter is set successfully, false otherwise
1345     * {@hide}
1346     */
1347    public boolean setParameter(int key, int value) {
1348        Parcel p = Parcel.obtain();
1349        p.writeInt(value);
1350        return setParameter(key, p);
1351    }
1352
1353    /**
1354     * Gets the value of the parameter indicated by key.
1355     * @param key key indicates the parameter to get.
1356     * @param reply value of the parameter to get.
1357     */
1358    private native void getParameter(int key, Parcel reply);
1359
1360    /**
1361     * Gets the value of the parameter indicated by key.
1362     * @param key key indicates the parameter to get.
1363     * @return value of the parameter.
1364     * {@hide}
1365     */
1366    public Parcel getParcelParameter(int key) {
1367        Parcel p = Parcel.obtain();
1368        getParameter(key, p);
1369        return p;
1370    }
1371
1372    /**
1373     * Gets the value of the parameter indicated by key.
1374     * @param key key indicates the parameter to get.
1375     * @return value of the parameter.
1376     * {@hide}
1377     */
1378    public String getStringParameter(int key) {
1379        Parcel p = Parcel.obtain();
1380        getParameter(key, p);
1381        return p.readString();
1382    }
1383
1384    /**
1385     * Gets the value of the parameter indicated by key.
1386     * @param key key indicates the parameter to get.
1387     * @return value of the parameter.
1388     * {@hide}
1389     */
1390    public int getIntParameter(int key) {
1391        Parcel p = Parcel.obtain();
1392        getParameter(key, p);
1393        return p.readInt();
1394    }
1395
1396    /**
1397     * Sets the send level of the player to the attached auxiliary effect
1398     * {@see #attachAuxEffect(int)}. The level value range is 0 to 1.0.
1399     * <p>By default the send level is 0, so even if an effect is attached to the player
1400     * this method must be called for the effect to be applied.
1401     * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
1402     * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
1403     * so an appropriate conversion from linear UI input x to level is:
1404     * x == 0 -> level = 0
1405     * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
1406     * @param level send level scalar
1407     */
1408    public native void setAuxEffectSendLevel(float level);
1409
1410    /**
1411     * @param request Parcel destinated to the media player. The
1412     *                Interface token must be set to the IMediaPlayer
1413     *                one to be routed correctly through the system.
1414     * @param reply[out] Parcel that will contain the reply.
1415     * @return The status code.
1416     */
1417    private native final int native_invoke(Parcel request, Parcel reply);
1418
1419
1420    /**
1421     * @param update_only If true fetch only the set of metadata that have
1422     *                    changed since the last invocation of getMetadata.
1423     *                    The set is built using the unfiltered
1424     *                    notifications the native player sent to the
1425     *                    MediaPlayerService during that period of
1426     *                    time. If false, all the metadatas are considered.
1427     * @param apply_filter  If true, once the metadata set has been built based on
1428     *                     the value update_only, the current filter is applied.
1429     * @param reply[out] On return contains the serialized
1430     *                   metadata. Valid only if the call was successful.
1431     * @return The status code.
1432     */
1433    private native final boolean native_getMetadata(boolean update_only,
1434                                                    boolean apply_filter,
1435                                                    Parcel reply);
1436
1437    /**
1438     * @param request Parcel with the 2 serialized lists of allowed
1439     *                metadata types followed by the one to be
1440     *                dropped. Each list starts with an integer
1441     *                indicating the number of metadata type elements.
1442     * @return The status code.
1443     */
1444    private native final int native_setMetadataFilter(Parcel request);
1445
1446    private static native final void native_init();
1447    private native final void native_setup(Object mediaplayer_this);
1448    private native final void native_finalize();
1449
1450    /**
1451     * @param index The index of the text track to be turned on.
1452     * @return true if the text track is enabled successfully.
1453     * {@hide}
1454     */
1455    public boolean enableTimedTextTrackIndex(int index) {
1456        if (index < 0) {
1457            return false;
1458        }
1459        return setParameter(KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX, index);
1460    }
1461
1462    /**
1463     * Enables the first timed text track if any.
1464     * @return true if the text track is enabled successfully
1465     * {@hide}
1466     */
1467    public boolean enableTimedText() {
1468        return enableTimedTextTrackIndex(0);
1469    }
1470
1471    /**
1472     * Disables timed text display.
1473     * @return true if the text track is disabled successfully.
1474     * {@hide}
1475     */
1476    public boolean disableTimedText() {
1477        return setParameter(KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX, -1);
1478    }
1479
1480    /**
1481     * @param reply Parcel with audio/video duration info for battery
1482                    tracking usage
1483     * @return The status code.
1484     * {@hide}
1485     */
1486    public native static int native_pullBatteryData(Parcel reply);
1487
1488    @Override
1489    protected void finalize() { native_finalize(); }
1490
1491    /* Do not change these values without updating their counterparts
1492     * in include/media/mediaplayer.h!
1493     */
1494    private static final int MEDIA_NOP = 0; // interface test message
1495    private static final int MEDIA_PREPARED = 1;
1496    private static final int MEDIA_PLAYBACK_COMPLETE = 2;
1497    private static final int MEDIA_BUFFERING_UPDATE = 3;
1498    private static final int MEDIA_SEEK_COMPLETE = 4;
1499    private static final int MEDIA_SET_VIDEO_SIZE = 5;
1500    private static final int MEDIA_TIMED_TEXT = 99;
1501    private static final int MEDIA_ERROR = 100;
1502    private static final int MEDIA_INFO = 200;
1503
1504    private class EventHandler extends Handler
1505    {
1506        private MediaPlayer mMediaPlayer;
1507
1508        public EventHandler(MediaPlayer mp, Looper looper) {
1509            super(looper);
1510            mMediaPlayer = mp;
1511        }
1512
1513        @Override
1514        public void handleMessage(Message msg) {
1515            if (mMediaPlayer.mNativeContext == 0) {
1516                Log.w(TAG, "mediaplayer went away with unhandled events");
1517                return;
1518            }
1519            switch(msg.what) {
1520            case MEDIA_PREPARED:
1521                if (mOnPreparedListener != null)
1522                    mOnPreparedListener.onPrepared(mMediaPlayer);
1523                return;
1524
1525            case MEDIA_PLAYBACK_COMPLETE:
1526                if (mOnCompletionListener != null)
1527                    mOnCompletionListener.onCompletion(mMediaPlayer);
1528                stayAwake(false);
1529                return;
1530
1531            case MEDIA_BUFFERING_UPDATE:
1532                if (mOnBufferingUpdateListener != null)
1533                    mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
1534                return;
1535
1536            case MEDIA_SEEK_COMPLETE:
1537              if (mOnSeekCompleteListener != null)
1538                  mOnSeekCompleteListener.onSeekComplete(mMediaPlayer);
1539              return;
1540
1541            case MEDIA_SET_VIDEO_SIZE:
1542              if (mOnVideoSizeChangedListener != null)
1543                  mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2);
1544              return;
1545
1546            case MEDIA_ERROR:
1547                // For PV specific error values (msg.arg2) look in
1548                // opencore/pvmi/pvmf/include/pvmf_return_codes.h
1549                Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
1550                boolean error_was_handled = false;
1551                if (mOnErrorListener != null) {
1552                    error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
1553                }
1554                if (mOnCompletionListener != null && ! error_was_handled) {
1555                    mOnCompletionListener.onCompletion(mMediaPlayer);
1556                }
1557                stayAwake(false);
1558                return;
1559
1560            case MEDIA_INFO:
1561                if (msg.arg1 != MEDIA_INFO_VIDEO_TRACK_LAGGING) {
1562                    Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
1563                }
1564                if (mOnInfoListener != null) {
1565                    mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
1566                }
1567                // No real default action so far.
1568                return;
1569            case MEDIA_TIMED_TEXT:
1570                if (mOnTimedTextListener != null) {
1571                    mOnTimedTextListener.onTimedText(mMediaPlayer, (String)msg.obj);
1572                }
1573                return;
1574
1575            case MEDIA_NOP: // interface test message - ignore
1576                break;
1577
1578            default:
1579                Log.e(TAG, "Unknown message type " + msg.what);
1580                return;
1581            }
1582        }
1583    }
1584
1585    /**
1586     * Called from native code when an interesting event happens.  This method
1587     * just uses the EventHandler system to post the event back to the main app thread.
1588     * We use a weak reference to the original MediaPlayer object so that the native
1589     * code is safe from the object disappearing from underneath it.  (This is
1590     * the cookie passed to native_setup().)
1591     */
1592    private static void postEventFromNative(Object mediaplayer_ref,
1593                                            int what, int arg1, int arg2, Object obj)
1594    {
1595        MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
1596        if (mp == null) {
1597            return;
1598        }
1599
1600        if (mp.mEventHandler != null) {
1601            Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
1602            mp.mEventHandler.sendMessage(m);
1603        }
1604    }
1605
1606    /**
1607     * Interface definition for a callback to be invoked when the media
1608     * source is ready for playback.
1609     */
1610    public interface OnPreparedListener
1611    {
1612        /**
1613         * Called when the media file is ready for playback.
1614         *
1615         * @param mp the MediaPlayer that is ready for playback
1616         */
1617        void onPrepared(MediaPlayer mp);
1618    }
1619
1620    /**
1621     * Register a callback to be invoked when the media source is ready
1622     * for playback.
1623     *
1624     * @param listener the callback that will be run
1625     */
1626    public void setOnPreparedListener(OnPreparedListener listener)
1627    {
1628        mOnPreparedListener = listener;
1629    }
1630
1631    private OnPreparedListener mOnPreparedListener;
1632
1633    /**
1634     * Interface definition for a callback to be invoked when playback of
1635     * a media source has completed.
1636     */
1637    public interface OnCompletionListener
1638    {
1639        /**
1640         * Called when the end of a media source is reached during playback.
1641         *
1642         * @param mp the MediaPlayer that reached the end of the file
1643         */
1644        void onCompletion(MediaPlayer mp);
1645    }
1646
1647    /**
1648     * Register a callback to be invoked when the end of a media source
1649     * has been reached during playback.
1650     *
1651     * @param listener the callback that will be run
1652     */
1653    public void setOnCompletionListener(OnCompletionListener listener)
1654    {
1655        mOnCompletionListener = listener;
1656    }
1657
1658    private OnCompletionListener mOnCompletionListener;
1659
1660    /**
1661     * Interface definition of a callback to be invoked indicating buffering
1662     * status of a media resource being streamed over the network.
1663     */
1664    public interface OnBufferingUpdateListener
1665    {
1666        /**
1667         * Called to update status in buffering a media stream received through
1668         * progressive HTTP download. The received buffering percentage
1669         * indicates how much of the content has been buffered or played.
1670         * For example a buffering update of 80 percent when half the content
1671         * has already been played indicates that the next 30 percent of the
1672         * content to play has been buffered.
1673         *
1674         * @param mp      the MediaPlayer the update pertains to
1675         * @param percent the percentage (0-100) of the content
1676         *                that has been buffered or played thus far
1677         */
1678        void onBufferingUpdate(MediaPlayer mp, int percent);
1679    }
1680
1681    /**
1682     * Register a callback to be invoked when the status of a network
1683     * stream's buffer has changed.
1684     *
1685     * @param listener the callback that will be run.
1686     */
1687    public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
1688    {
1689        mOnBufferingUpdateListener = listener;
1690    }
1691
1692    private OnBufferingUpdateListener mOnBufferingUpdateListener;
1693
1694    /**
1695     * Interface definition of a callback to be invoked indicating
1696     * the completion of a seek operation.
1697     */
1698    public interface OnSeekCompleteListener
1699    {
1700        /**
1701         * Called to indicate the completion of a seek operation.
1702         *
1703         * @param mp the MediaPlayer that issued the seek operation
1704         */
1705        public void onSeekComplete(MediaPlayer mp);
1706    }
1707
1708    /**
1709     * Register a callback to be invoked when a seek operation has been
1710     * completed.
1711     *
1712     * @param listener the callback that will be run
1713     */
1714    public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
1715    {
1716        mOnSeekCompleteListener = listener;
1717    }
1718
1719    private OnSeekCompleteListener mOnSeekCompleteListener;
1720
1721    /**
1722     * Interface definition of a callback to be invoked when the
1723     * video size is first known or updated
1724     */
1725    public interface OnVideoSizeChangedListener
1726    {
1727        /**
1728         * Called to indicate the video size
1729         *
1730         * @param mp        the MediaPlayer associated with this callback
1731         * @param width     the width of the video
1732         * @param height    the height of the video
1733         */
1734        public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
1735    }
1736
1737    /**
1738     * Register a callback to be invoked when the video size is
1739     * known or updated.
1740     *
1741     * @param listener the callback that will be run
1742     */
1743    public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
1744    {
1745        mOnVideoSizeChangedListener = listener;
1746    }
1747
1748    private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
1749
1750    /**
1751     * Interface definition of a callback to be invoked when a
1752     * timed text is available for display.
1753     * {@hide}
1754     */
1755    public interface OnTimedTextListener
1756    {
1757        /**
1758         * Called to indicate the video size
1759         *
1760         * @param mp             the MediaPlayer associated with this callback
1761         * @param text           the timed text sample which contains the
1762         *                       text needed to be displayed.
1763         * {@hide}
1764         */
1765        public void onTimedText(MediaPlayer mp, String text);
1766    }
1767
1768    /**
1769     * Register a callback to be invoked when a timed text is available
1770     * for display.
1771     *
1772     * @param listener the callback that will be run
1773     * {@hide}
1774     */
1775    public void setOnTimedTextListener(OnTimedTextListener listener)
1776    {
1777        mOnTimedTextListener = listener;
1778    }
1779
1780    private OnTimedTextListener mOnTimedTextListener;
1781
1782
1783    /* Do not change these values without updating their counterparts
1784     * in include/media/mediaplayer.h!
1785     */
1786    /** Unspecified media player error.
1787     * @see android.media.MediaPlayer.OnErrorListener
1788     */
1789    public static final int MEDIA_ERROR_UNKNOWN = 1;
1790
1791    /** Media server died. In this case, the application must release the
1792     * MediaPlayer object and instantiate a new one.
1793     * @see android.media.MediaPlayer.OnErrorListener
1794     */
1795    public static final int MEDIA_ERROR_SERVER_DIED = 100;
1796
1797    /** The video is streamed and its container is not valid for progressive
1798     * playback i.e the video's index (e.g moov atom) is not at the start of the
1799     * file.
1800     * @see android.media.MediaPlayer.OnErrorListener
1801     */
1802    public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
1803
1804    /**
1805     * Interface definition of a callback to be invoked when there
1806     * has been an error during an asynchronous operation (other errors
1807     * will throw exceptions at method call time).
1808     */
1809    public interface OnErrorListener
1810    {
1811        /**
1812         * Called to indicate an error.
1813         *
1814         * @param mp      the MediaPlayer the error pertains to
1815         * @param what    the type of error that has occurred:
1816         * <ul>
1817         * <li>{@link #MEDIA_ERROR_UNKNOWN}
1818         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
1819         * </ul>
1820         * @param extra an extra code, specific to the error. Typically
1821         * implementation dependant.
1822         * @return True if the method handled the error, false if it didn't.
1823         * Returning false, or not having an OnErrorListener at all, will
1824         * cause the OnCompletionListener to be called.
1825         */
1826        boolean onError(MediaPlayer mp, int what, int extra);
1827    }
1828
1829    /**
1830     * Register a callback to be invoked when an error has happened
1831     * during an asynchronous operation.
1832     *
1833     * @param listener the callback that will be run
1834     */
1835    public void setOnErrorListener(OnErrorListener listener)
1836    {
1837        mOnErrorListener = listener;
1838    }
1839
1840    private OnErrorListener mOnErrorListener;
1841
1842
1843    /* Do not change these values without updating their counterparts
1844     * in include/media/mediaplayer.h!
1845     */
1846    /** Unspecified media player info.
1847     * @see android.media.MediaPlayer.OnInfoListener
1848     */
1849    public static final int MEDIA_INFO_UNKNOWN = 1;
1850
1851    /** The video is too complex for the decoder: it can't decode frames fast
1852     *  enough. Possibly only the audio plays fine at this stage.
1853     * @see android.media.MediaPlayer.OnInfoListener
1854     */
1855    public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
1856
1857    /** MediaPlayer is temporarily pausing playback internally in order to
1858     * buffer more data.
1859     * @see android.media.MediaPlayer.OnInfoListener
1860     */
1861    public static final int MEDIA_INFO_BUFFERING_START = 701;
1862
1863    /** MediaPlayer is resuming playback after filling buffers.
1864     * @see android.media.MediaPlayer.OnInfoListener
1865     */
1866    public static final int MEDIA_INFO_BUFFERING_END = 702;
1867
1868    /** Bad interleaving means that a media has been improperly interleaved or
1869     * not interleaved at all, e.g has all the video samples first then all the
1870     * audio ones. Video is playing but a lot of disk seeks may be happening.
1871     * @see android.media.MediaPlayer.OnInfoListener
1872     */
1873    public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
1874
1875    /** The media cannot be seeked (e.g live stream)
1876     * @see android.media.MediaPlayer.OnInfoListener
1877     */
1878    public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
1879
1880    /** A new set of metadata is available.
1881     * @see android.media.MediaPlayer.OnInfoListener
1882     */
1883    public static final int MEDIA_INFO_METADATA_UPDATE = 802;
1884
1885    /**
1886     * Interface definition of a callback to be invoked to communicate some
1887     * info and/or warning about the media or its playback.
1888     */
1889    public interface OnInfoListener
1890    {
1891        /**
1892         * Called to indicate an info or a warning.
1893         *
1894         * @param mp      the MediaPlayer the info pertains to.
1895         * @param what    the type of info or warning.
1896         * <ul>
1897         * <li>{@link #MEDIA_INFO_UNKNOWN}
1898         * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
1899         * <li>{@link #MEDIA_INFO_BUFFERING_START}
1900         * <li>{@link #MEDIA_INFO_BUFFERING_END}
1901         * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
1902         * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
1903         * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
1904         * </ul>
1905         * @param extra an extra code, specific to the info. Typically
1906         * implementation dependant.
1907         * @return True if the method handled the info, false if it didn't.
1908         * Returning false, or not having an OnErrorListener at all, will
1909         * cause the info to be discarded.
1910         */
1911        boolean onInfo(MediaPlayer mp, int what, int extra);
1912    }
1913
1914    /**
1915     * Register a callback to be invoked when an info/warning is available.
1916     *
1917     * @param listener the callback that will be run
1918     */
1919    public void setOnInfoListener(OnInfoListener listener)
1920    {
1921        mOnInfoListener = listener;
1922    }
1923
1924    private OnInfoListener mOnInfoListener;
1925
1926}
1927