MediaPlayer.java revision 1ee60119c4fa51ebfa781cf5fdc33f192e8551b8
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.media;
18
19import android.content.ContentResolver;
20import android.content.Context;
21import android.content.res.AssetFileDescriptor;
22import android.net.Uri;
23import android.os.Handler;
24import android.os.Looper;
25import android.os.Message;
26import android.os.Parcel;
27import android.os.ParcelFileDescriptor;
28import android.os.PowerManager;
29import android.util.Log;
30import android.view.Surface;
31import android.view.SurfaceHolder;
32import android.graphics.Bitmap;
33import android.graphics.SurfaceTexture;
34import android.media.AudioManager;
35
36import java.io.FileDescriptor;
37import java.io.IOException;
38import java.util.Map;
39import java.util.Set;
40import java.lang.ref.WeakReference;
41
42/**
43 * MediaPlayer class can be used to control playback
44 * of audio/video files and streams. An example on how to use the methods in
45 * this class can be found in {@link android.widget.VideoView}.
46 * Please see <a href="{@docRoot}guide/topics/media/index.html">Audio and Video</a>
47 * for additional help using MediaPlayer.
48 *
49 * <p>Topics covered here are:
50 * <ol>
51 * <li><a href="#StateDiagram">State Diagram</a>
52 * <li><a href="#Valid_and_Invalid_States">Valid and Invalid States</a>
53 * <li><a href="#Permissions">Permissions</a>
54 * <li><a href="#Callbacks">Register informational and error callbacks</a>
55 * </ol>
56 *
57 * <a name="StateDiagram"></a>
58 * <h3>State Diagram</h3>
59 *
60 * <p>Playback control of audio/video files and streams is managed as a state
61 * machine. The following diagram shows the life cycle and the states of a
62 * MediaPlayer object driven by the supported playback control operations.
63 * The ovals represent the states a MediaPlayer object may reside
64 * in. The arcs represent the playback control operations that drive the object
65 * state transition. There are two types of arcs. The arcs with a single arrow
66 * head represent synchronous method calls, while those with
67 * a double arrow head represent asynchronous method calls.</p>
68 *
69 * <p><img src="../../../images/mediaplayer_state_diagram.gif"
70 *         alt="MediaPlayer State diagram"
71 *         border="0" /></p>
72 *
73 * <p>From this state diagram, one can see that a MediaPlayer object has the
74 *    following states:</p>
75 * <ul>
76 *     <li>When a MediaPlayer object is just created using <code>new</code> or
77 *         after {@link #reset()} is called, it is in the <em>Idle</em> state; and after
78 *         {@link #release()} is called, it is in the <em>End</em> state. Between these
79 *         two states is the life cycle of the MediaPlayer object.
80 *         <ul>
81 *         <li>There is a subtle but important difference between a newly constructed
82 *         MediaPlayer object and the MediaPlayer object after {@link #reset()}
83 *         is called. It is a programming error to invoke methods such
84 *         as {@link #getCurrentPosition()},
85 *         {@link #getDuration()}, {@link #getVideoHeight()},
86 *         {@link #getVideoWidth()}, {@link #setAudioStreamType(int)},
87 *         {@link #setLooping(boolean)},
88 *         {@link #setVolume(float, float)}, {@link #pause()}, {@link #start()},
89 *         {@link #stop()}, {@link #seekTo(int)}, {@link #prepare()} or
90 *         {@link #prepareAsync()} in the <em>Idle</em> state for both cases. If any of these
91 *         methods is called right after a MediaPlayer object is constructed,
92 *         the user supplied callback method OnErrorListener.onError() won't be
93 *         called by the internal player engine and the object state remains
94 *         unchanged; but if these methods are called right after {@link #reset()},
95 *         the user supplied callback method OnErrorListener.onError() will be
96 *         invoked by the internal player engine and the object will be
97 *         transfered to the <em>Error</em> state. </li>
98 *         <li>It is also recommended that once
99 *         a MediaPlayer object is no longer being used, call {@link #release()} immediately
100 *         so that resources used by the internal player engine associated with the
101 *         MediaPlayer object can be released immediately. Resource may include
102 *         singleton resources such as hardware acceleration components and
103 *         failure to call {@link #release()} may cause subsequent instances of
104 *         MediaPlayer objects to fallback to software implementations or fail
105 *         altogether. Once the MediaPlayer
106 *         object is in the <em>End</em> state, it can no longer be used and
107 *         there is no way to bring it back to any other state. </li>
108 *         <li>Furthermore,
109 *         the MediaPlayer objects created using <code>new</code> is in the
110 *         <em>Idle</em> state, while those created with one
111 *         of the overloaded convenient <code>create</code> methods are <em>NOT</em>
112 *         in the <em>Idle</em> state. In fact, the objects are in the <em>Prepared</em>
113 *         state if the creation using <code>create</code> method is successful.
114 *         </li>
115 *         </ul>
116 *         </li>
117 *     <li>In general, some playback control operation may fail due to various
118 *         reasons, such as unsupported audio/video format, poorly interleaved
119 *         audio/video, resolution too high, streaming timeout, and the like.
120 *         Thus, error reporting and recovery is an important concern under
121 *         these circumstances. Sometimes, due to programming errors, invoking a playback
122 *         control operation in an invalid state may also occur. Under all these
123 *         error conditions, the internal player engine invokes a user supplied
124 *         OnErrorListener.onError() method if an OnErrorListener has been
125 *         registered beforehand via
126 *         {@link #setOnErrorListener(android.media.MediaPlayer.OnErrorListener)}.
127 *         <ul>
128 *         <li>It is important to note that once an error occurs, the
129 *         MediaPlayer object enters the <em>Error</em> state (except as noted
130 *         above), even if an error listener has not been registered by the application.</li>
131 *         <li>In order to reuse a MediaPlayer object that is in the <em>
132 *         Error</em> state and recover from the error,
133 *         {@link #reset()} can be called to restore the object to its <em>Idle</em>
134 *         state.</li>
135 *         <li>It is good programming practice to have your application
136 *         register a OnErrorListener to look out for error notifications from
137 *         the internal player engine.</li>
138 *         <li>IllegalStateException is
139 *         thrown to prevent programming errors such as calling {@link #prepare()},
140 *         {@link #prepareAsync()}, or one of the overloaded <code>setDataSource
141 *         </code> methods in an invalid state. </li>
142 *         </ul>
143 *         </li>
144 *     <li>Calling
145 *         {@link #setDataSource(FileDescriptor)}, or
146 *         {@link #setDataSource(String)}, or
147 *         {@link #setDataSource(Context, Uri)}, or
148 *         {@link #setDataSource(FileDescriptor, long, long)} transfers a
149 *         MediaPlayer object in the <em>Idle</em> state to the
150 *         <em>Initialized</em> state.
151 *         <ul>
152 *         <li>An IllegalStateException is thrown if
153 *         setDataSource() is called in any other state.</li>
154 *         <li>It is good programming
155 *         practice to always look out for <code>IllegalArgumentException</code>
156 *         and <code>IOException</code> that may be thrown from the overloaded
157 *         <code>setDataSource</code> methods.</li>
158 *         </ul>
159 *         </li>
160 *     <li>A MediaPlayer object must first enter the <em>Prepared</em> state
161 *         before playback can be started.
162 *         <ul>
163 *         <li>There are two ways (synchronous vs.
164 *         asynchronous) that the <em>Prepared</em> state can be reached:
165 *         either a call to {@link #prepare()} (synchronous) which
166 *         transfers the object to the <em>Prepared</em> state once the method call
167 *         returns, or a call to {@link #prepareAsync()} (asynchronous) which
168 *         first transfers the object to the <em>Preparing</em> state after the
169 *         call returns (which occurs almost right way) while the internal
170 *         player engine continues working on the rest of preparation work
171 *         until the preparation work completes. When the preparation completes or when {@link #prepare()} call returns,
172 *         the internal player engine then calls a user supplied callback method,
173 *         onPrepared() of the OnPreparedListener interface, if an
174 *         OnPreparedListener is registered beforehand via {@link
175 *         #setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener)}.</li>
176 *         <li>It is important to note that
177 *         the <em>Preparing</em> state is a transient state, and the behavior
178 *         of calling any method with side effect while a MediaPlayer object is
179 *         in the <em>Preparing</em> state is undefined.</li>
180 *         <li>An IllegalStateException is
181 *         thrown if {@link #prepare()} or {@link #prepareAsync()} is called in
182 *         any other state.</li>
183 *         <li>While in the <em>Prepared</em> state, properties
184 *         such as audio/sound volume, screenOnWhilePlaying, looping can be
185 *         adjusted by invoking the corresponding set methods.</li>
186 *         </ul>
187 *         </li>
188 *     <li>To start the playback, {@link #start()} must be called. After
189 *         {@link #start()} returns successfully, the MediaPlayer object is in the
190 *         <em>Started</em> state. {@link #isPlaying()} can be called to test
191 *         whether the MediaPlayer object is in the <em>Started</em> state.
192 *         <ul>
193 *         <li>While in the <em>Started</em> state, the internal player engine calls
194 *         a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback
195 *         method if a OnBufferingUpdateListener has been registered beforehand
196 *         via {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}.
197 *         This callback allows applications to keep track of the buffering status
198 *         while streaming audio/video.</li>
199 *         <li>Calling {@link #start()} has not effect
200 *         on a MediaPlayer object that is already in the <em>Started</em> state.</li>
201 *         </ul>
202 *         </li>
203 *     <li>Playback can be paused and stopped, and the current playback position
204 *         can be adjusted. Playback can be paused via {@link #pause()}. When the call to
205 *         {@link #pause()} returns, the MediaPlayer object enters the
206 *         <em>Paused</em> state. Note that the transition from the <em>Started</em>
207 *         state to the <em>Paused</em> state and vice versa happens
208 *         asynchronously in the player engine. It may take some time before
209 *         the state is updated in calls to {@link #isPlaying()}, and it can be
210 *         a number of seconds in the case of streamed content.
211 *         <ul>
212 *         <li>Calling {@link #start()} to resume playback for a paused
213 *         MediaPlayer object, and the resumed playback
214 *         position is the same as where it was paused. When the call to
215 *         {@link #start()} returns, the paused MediaPlayer object goes back to
216 *         the <em>Started</em> state.</li>
217 *         <li>Calling {@link #pause()} has no effect on
218 *         a MediaPlayer object that is already in the <em>Paused</em> state.</li>
219 *         </ul>
220 *         </li>
221 *     <li>Calling  {@link #stop()} stops playback and causes a
222 *         MediaPlayer in the <em>Started</em>, <em>Paused</em>, <em>Prepared
223 *         </em> or <em>PlaybackCompleted</em> state to enter the
224 *         <em>Stopped</em> state.
225 *         <ul>
226 *         <li>Once in the <em>Stopped</em> state, playback cannot be started
227 *         until {@link #prepare()} or {@link #prepareAsync()} are called to set
228 *         the MediaPlayer object to the <em>Prepared</em> state again.</li>
229 *         <li>Calling {@link #stop()} has no effect on a MediaPlayer
230 *         object that is already in the <em>Stopped</em> state.</li>
231 *         </ul>
232 *         </li>
233 *     <li>The playback position can be adjusted with a call to
234 *         {@link #seekTo(int)}.
235 *         <ul>
236 *         <li>Although the asynchronuous {@link #seekTo(int)}
237 *         call returns right way, the actual seek operation may take a while to
238 *         finish, especially for audio/video being streamed. When the actual
239 *         seek operation completes, the internal player engine calls a user
240 *         supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener
241 *         has been registered beforehand via
242 *         {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}.</li>
243 *         <li>Please
244 *         note that {@link #seekTo(int)} can also be called in the other states,
245 *         such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted
246 *         </em> state.</li>
247 *         <li>Furthermore, the actual current playback position
248 *         can be retrieved with a call to {@link #getCurrentPosition()}, which
249 *         is helpful for applications such as a Music player that need to keep
250 *         track of the playback progress.</li>
251 *         </ul>
252 *         </li>
253 *     <li>When the playback reaches the end of stream, the playback completes.
254 *         <ul>
255 *         <li>If the looping mode was being set to <var>true</var>with
256 *         {@link #setLooping(boolean)}, the MediaPlayer object shall remain in
257 *         the <em>Started</em> state.</li>
258 *         <li>If the looping mode was set to <var>false
259 *         </var>, the player engine calls a user supplied callback method,
260 *         OnCompletion.onCompletion(), if a OnCompletionListener is registered
261 *         beforehand via {@link #setOnCompletionListener(OnCompletionListener)}.
262 *         The invoke of the callback signals that the object is now in the <em>
263 *         PlaybackCompleted</em> state.</li>
264 *         <li>While in the <em>PlaybackCompleted</em>
265 *         state, calling {@link #start()} can restart the playback from the
266 *         beginning of the audio/video source.</li>
267 * </ul>
268 *
269 *
270 * <a name="Valid_and_Invalid_States"></a>
271 * <h3>Valid and invalid states</h3>
272 *
273 * <table border="0" cellspacing="0" cellpadding="0">
274 * <tr><td>Method Name </p></td>
275 *     <td>Valid Sates </p></td>
276 *     <td>Invalid States </p></td>
277 *     <td>Comments </p></td></tr>
278 * <tr><td>attachAuxEffect </p></td>
279 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
280 *     <td>{Idle, Error} </p></td>
281 *     <td>This method must be called after setDataSource.
282 *     Calling it does not change the object state. </p></td></tr>
283 * <tr><td>getAudioSessionId </p></td>
284 *     <td>any </p></td>
285 *     <td>{} </p></td>
286 *     <td>This method can be called in any state and calling it does not change
287 *         the object state. </p></td></tr>
288 * <tr><td>getCurrentPosition </p></td>
289 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
290 *         PlaybackCompleted} </p></td>
291 *     <td>{Error}</p></td>
292 *     <td>Successful invoke of this method in a valid state does not change the
293 *         state. Calling this method in an invalid state transfers the object
294 *         to the <em>Error</em> state. </p></td></tr>
295 * <tr><td>getDuration </p></td>
296 *     <td>{Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
297 *     <td>{Idle, Initialized, Error} </p></td>
298 *     <td>Successful invoke of this method in a valid state does not change the
299 *         state. Calling this method in an invalid state transfers the object
300 *         to the <em>Error</em> state. </p></td></tr>
301 * <tr><td>getVideoHeight </p></td>
302 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
303 *         PlaybackCompleted}</p></td>
304 *     <td>{Error}</p></td>
305 *     <td>Successful invoke of this method in a valid state does not change the
306 *         state. Calling this method in an invalid state transfers the object
307 *         to the <em>Error</em> state.  </p></td></tr>
308 * <tr><td>getVideoWidth </p></td>
309 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
310 *         PlaybackCompleted}</p></td>
311 *     <td>{Error}</p></td>
312 *     <td>Successful invoke of this method in a valid state does not change
313 *         the state. Calling this method in an invalid state transfers the
314 *         object to the <em>Error</em> state. </p></td></tr>
315 * <tr><td>isPlaying </p></td>
316 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
317 *          PlaybackCompleted}</p></td>
318 *     <td>{Error}</p></td>
319 *     <td>Successful invoke of this method in a valid state does not change
320 *         the state. Calling this method in an invalid state transfers the
321 *         object to the <em>Error</em> state. </p></td></tr>
322 * <tr><td>pause </p></td>
323 *     <td>{Started, Paused}</p></td>
324 *     <td>{Idle, Initialized, Prepared, Stopped, PlaybackCompleted, Error}</p></td>
325 *     <td>Successful invoke of this method in a valid state transfers the
326 *         object to the <em>Paused</em> state. Calling this method in an
327 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
328 * <tr><td>prepare </p></td>
329 *     <td>{Initialized, Stopped} </p></td>
330 *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
331 *     <td>Successful invoke of this method in a valid state transfers the
332 *         object to the <em>Prepared</em> state. Calling this method in an
333 *         invalid state throws an IllegalStateException.</p></td></tr>
334 * <tr><td>prepareAsync </p></td>
335 *     <td>{Initialized, Stopped} </p></td>
336 *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
337 *     <td>Successful invoke of this method in a valid state transfers the
338 *         object to the <em>Preparing</em> state. Calling this method in an
339 *         invalid state throws an IllegalStateException.</p></td></tr>
340 * <tr><td>release </p></td>
341 *     <td>any </p></td>
342 *     <td>{} </p></td>
343 *     <td>After {@link #release()}, the object is no longer available. </p></td></tr>
344 * <tr><td>reset </p></td>
345 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
346 *         PlaybackCompleted, Error}</p></td>
347 *     <td>{}</p></td>
348 *     <td>After {@link #reset()}, the object is like being just created.</p></td></tr>
349 * <tr><td>seekTo </p></td>
350 *     <td>{Prepared, Started, Paused, PlaybackCompleted} </p></td>
351 *     <td>{Idle, Initialized, Stopped, Error}</p></td>
352 *     <td>Successful invoke of this method in a valid state does not change
353 *         the state. Calling this method in an invalid state transfers the
354 *         object to the <em>Error</em> state. </p></td></tr>
355 * <tr><td>setAudioSessionId </p></td>
356 *     <td>{Idle} </p></td>
357 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
358 *          Error} </p></td>
359 *     <td>This method must be called in idle state as the audio session ID must be known before
360 *         calling setDataSource. Calling it does not change the object state. </p></td></tr>
361 * <tr><td>setAudioStreamType </p></td>
362 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
363 *          PlaybackCompleted}</p></td>
364 *     <td>{Error}</p></td>
365 *     <td>Successful invoke of this method does not change the state. In order for the
366 *         target audio stream type to become effective, this method must be called before
367 *         prepare() or prepareAsync().</p></td></tr>
368 * <tr><td>setAuxEffectSendLevel </p></td>
369 *     <td>any</p></td>
370 *     <td>{} </p></td>
371 *     <td>Calling this method does not change the object state. </p></td></tr>
372 * <tr><td>setDataSource </p></td>
373 *     <td>{Idle} </p></td>
374 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
375 *          Error} </p></td>
376 *     <td>Successful invoke of this method in a valid state transfers the
377 *         object to the <em>Initialized</em> state. Calling this method in an
378 *         invalid state throws an IllegalStateException.</p></td></tr>
379 * <tr><td>setDisplay </p></td>
380 *     <td>any </p></td>
381 *     <td>{} </p></td>
382 *     <td>This method can be called in any state and calling it does not change
383 *         the object state. </p></td></tr>
384 * <tr><td>setTexture </p></td>
385 *     <td>any </p></td>
386 *     <td>{} </p></td>
387 *     <td>This method can be called in any state and calling it does not change
388 *         the object state. </p></td></tr>
389 * <tr><td>setLooping </p></td>
390 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
391 *         PlaybackCompleted}</p></td>
392 *     <td>{Error}</p></td>
393 *     <td>Successful invoke of this method in a valid state does not change
394 *         the state. Calling this method in an
395 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
396 * <tr><td>isLooping </p></td>
397 *     <td>any </p></td>
398 *     <td>{} </p></td>
399 *     <td>This method can be called in any state and calling it does not change
400 *         the object state. </p></td></tr>
401 * <tr><td>setOnBufferingUpdateListener </p></td>
402 *     <td>any </p></td>
403 *     <td>{} </p></td>
404 *     <td>This method can be called in any state and calling it does not change
405 *         the object state. </p></td></tr>
406 * <tr><td>setOnCompletionListener </p></td>
407 *     <td>any </p></td>
408 *     <td>{} </p></td>
409 *     <td>This method can be called in any state and calling it does not change
410 *         the object state. </p></td></tr>
411 * <tr><td>setOnErrorListener </p></td>
412 *     <td>any </p></td>
413 *     <td>{} </p></td>
414 *     <td>This method can be called in any state and calling it does not change
415 *         the object state. </p></td></tr>
416 * <tr><td>setOnPreparedListener </p></td>
417 *     <td>any </p></td>
418 *     <td>{} </p></td>
419 *     <td>This method can be called in any state and calling it does not change
420 *         the object state. </p></td></tr>
421 * <tr><td>setOnSeekCompleteListener </p></td>
422 *     <td>any </p></td>
423 *     <td>{} </p></td>
424 *     <td>This method can be called in any state and calling it does not change
425 *         the object state. </p></td></tr>
426 * <tr><td>setScreenOnWhilePlaying</></td>
427 *     <td>any </p></td>
428 *     <td>{} </p></td>
429 *     <td>This method can be called in any state and calling it does not change
430 *         the object state.  </p></td></tr>
431 * <tr><td>setVolume </p></td>
432 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
433 *          PlaybackCompleted}</p></td>
434 *     <td>{Error}</p></td>
435 *     <td>Successful invoke of this method does not change the state.
436 * <tr><td>setWakeMode </p></td>
437 *     <td>any </p></td>
438 *     <td>{} </p></td>
439 *     <td>This method can be called in any state and calling it does not change
440 *         the object state.</p></td></tr>
441 * <tr><td>start </p></td>
442 *     <td>{Prepared, Started, Paused, PlaybackCompleted}</p></td>
443 *     <td>{Idle, Initialized, Stopped, Error}</p></td>
444 *     <td>Successful invoke of this method in a valid state transfers the
445 *         object to the <em>Started</em> state. Calling this method in an
446 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
447 * <tr><td>stop </p></td>
448 *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
449 *     <td>{Idle, Initialized, Error}</p></td>
450 *     <td>Successful invoke of this method in a valid state transfers the
451 *         object to the <em>Stopped</em> state. Calling this method in an
452 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
453 *
454 * </table>
455 *
456 * <a name="Permissions"></a>
457 * <h3>Permissions</h3>
458 * <p>One may need to declare a corresponding WAKE_LOCK permission {@link
459 * android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
460 * element.
461 *
462 * <a name="Callbacks"></a>
463 * <h3>Callbacks</h3>
464 * <p>Applications may want to register for informational and error
465 * events in order to be informed of some internal state update and
466 * possible runtime errors during playback or streaming. Registration for
467 * these events is done by properly setting the appropriate listeners (via calls
468 * to
469 * {@link #setOnPreparedListener(OnPreparedListener)}setOnPreparedListener,
470 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}setOnVideoSizeChangedListener,
471 * {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}setOnSeekCompleteListener,
472 * {@link #setOnCompletionListener(OnCompletionListener)}setOnCompletionListener,
473 * {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}setOnBufferingUpdateListener,
474 * {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener,
475 * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener, etc).
476 * In order to receive the respective callback
477 * associated with these listeners, applications are required to create
478 * MediaPlayer objects on a thread with its own Looper running (main UI
479 * thread by default has a Looper running).
480 *
481 */
482public class MediaPlayer
483{
484    /**
485       Constant to retrieve only the new metadata since the last
486       call.
487       // FIXME: unhide.
488       // FIXME: add link to getMetadata(boolean, boolean)
489       {@hide}
490     */
491    public static final boolean METADATA_UPDATE_ONLY = true;
492
493    /**
494       Constant to retrieve all the metadata.
495       // FIXME: unhide.
496       // FIXME: add link to getMetadata(boolean, boolean)
497       {@hide}
498     */
499    public static final boolean METADATA_ALL = false;
500
501    /**
502       Constant to enable the metadata filter during retrieval.
503       // FIXME: unhide.
504       // FIXME: add link to getMetadata(boolean, boolean)
505       {@hide}
506     */
507    public static final boolean APPLY_METADATA_FILTER = true;
508
509    /**
510       Constant to disable the metadata filter during retrieval.
511       // FIXME: unhide.
512       // FIXME: add link to getMetadata(boolean, boolean)
513       {@hide}
514     */
515    public static final boolean BYPASS_METADATA_FILTER = false;
516
517    static {
518        System.loadLibrary("media_jni");
519        native_init();
520    }
521
522    private final static String TAG = "MediaPlayer";
523    // Name of the remote interface for the media player. Must be kept
524    // in sync with the 2nd parameter of the IMPLEMENT_META_INTERFACE
525    // macro invocation in IMediaPlayer.cpp
526    private final static String IMEDIA_PLAYER = "android.media.IMediaPlayer";
527
528    private int mNativeContext; // accessed by native methods
529    private int mNativeSurfaceTexture;  // accessed by native methods
530    private int mListenerContext; // accessed by native methods
531    private SurfaceHolder mSurfaceHolder;
532    private EventHandler mEventHandler;
533    private PowerManager.WakeLock mWakeLock = null;
534    private boolean mScreenOnWhilePlaying;
535    private boolean mStayAwake;
536
537    /**
538     * Default constructor. Consider using one of the create() methods for
539     * synchronously instantiating a MediaPlayer from a Uri or resource.
540     * <p>When done with the MediaPlayer, you should call  {@link #release()},
541     * to free the resources. If not released, too many MediaPlayer instances may
542     * result in an exception.</p>
543     */
544    public MediaPlayer() {
545
546        Looper looper;
547        if ((looper = Looper.myLooper()) != null) {
548            mEventHandler = new EventHandler(this, looper);
549        } else if ((looper = Looper.getMainLooper()) != null) {
550            mEventHandler = new EventHandler(this, looper);
551        } else {
552            mEventHandler = null;
553        }
554
555        /* Native setup requires a weak reference to our object.
556         * It's easier to create it here than in C++.
557         */
558        native_setup(new WeakReference<MediaPlayer>(this));
559    }
560
561    /*
562     * Update the MediaPlayer SurfaceTexture.
563     * Call after setting a new display surface.
564     */
565    private native void _setVideoSurface(Surface surface);
566
567    /**
568     * Create a request parcel which can be routed to the native media
569     * player using {@link #invoke(Parcel, Parcel)}. The Parcel
570     * returned has the proper InterfaceToken set. The caller should
571     * not overwrite that token, i.e it can only append data to the
572     * Parcel.
573     *
574     * @return A parcel suitable to hold a request for the native
575     * player.
576     * {@hide}
577     */
578    public Parcel newRequest() {
579        Parcel parcel = Parcel.obtain();
580        parcel.writeInterfaceToken(IMEDIA_PLAYER);
581        return parcel;
582    }
583
584    /**
585     * Invoke a generic method on the native player using opaque
586     * parcels for the request and reply. Both payloads' format is a
587     * convention between the java caller and the native player.
588     * Must be called after setDataSource to make sure a native player
589     * exists.
590     *
591     * @param request Parcel with the data for the extension. The
592     * caller must use {@link #newRequest()} to get one.
593     *
594     * @param reply Output parcel with the data returned by the
595     * native player.
596     *
597     * @return The status code see utils/Errors.h
598     * {@hide}
599     */
600    public int invoke(Parcel request, Parcel reply) {
601        int retcode = native_invoke(request, reply);
602        reply.setDataPosition(0);
603        return retcode;
604    }
605
606    /**
607     * Sets the {@link SurfaceHolder} to use for displaying the video
608     * portion of the media.
609     *
610     * Either a surface holder or surface must be set if a display or video sink
611     * is needed.  Not calling this method or {@link #setTexture(SurfaceTexture)}
612     * when playing back a video will result in only the audio track being played.
613     * A null surface holder or surface will result in only the audio track being
614     * played.
615     *
616     * @param sh the SurfaceHolder to use for video display
617     */
618    public void setDisplay(SurfaceHolder sh) {
619        mSurfaceHolder = sh;
620        Surface surface;
621        if (sh != null) {
622            surface = sh.getSurface();
623        } else {
624            surface = null;
625        }
626        _setVideoSurface(surface);
627        updateSurfaceScreenOn();
628    }
629
630    /**
631     * Sets the {@link Surface} to be used as the sink for the video portion of
632     * the media. This is similar to {@link #setDisplay(SurfaceHolder)}, but does not
633     * support {@link #setScreenOnWhilePlaying(boolean)} or {@link #updateSurfaceScreenOn()}.
634     * Setting a Surface will un-set any Surface or SurfaceHolder that was previously set.
635     * A null surface will result in only the audio track being played.
636     *
637     * @param surface The {@link Surface} to be used for the video portion of the media.
638     *
639     * @hide Pending review by API council.
640     */
641    public void setSurface(Surface surface) {
642        if (mScreenOnWhilePlaying && surface != null) {
643            Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface");
644        }
645        mSurfaceHolder = null;
646        _setVideoSurface(surface);
647        updateSurfaceScreenOn();
648    }
649
650    /**
651     * Sets the {@link SurfaceTexture} to be used as the sink for the
652     * video portion of the media. Either a surface or surface texture
653     * must be set if a video sink is needed.  The same surface texture
654     * can be re-set without harm. Setting a surface texture will un-set
655     * any surface that was set via {@link #setDisplay(SurfaceHolder)}.
656     * Not calling this method or {@link #setDisplay(SurfaceHolder)}
657     * when playing back a video will result in only the audio track
658     * being played. Note that if a SurfaceTexture is used, the value
659     * set via setScreenOnWhilePlaying has no effect.
660     *
661     * The timestamps provided by {@link SurfaceTexture#getTimestamp()} for a
662     * SurfaceTexture set as the video sink have an unspecified zero point,
663     * and cannot be directly compared between different media sources or different
664     * instances of the same media source, or across multiple runs of the same
665     * program.  The timestamp is normally monotonically increasing and unaffected
666     * by time-of-day adjustments, but is reset when the position is set.
667     */
668    public void setTexture(SurfaceTexture st) {
669        // TODO: This method should be hidden before it is published and setSurface
670        // should be unhidden and made public instead.
671        if (st != null) {
672            Surface surface = new Surface(st);
673            setSurface(surface);
674
675            // It is safe and desired to release the newly created Surface here since the
676            // native code will grab a reference to the underlying ISurfaceTexture. At that
677            // point the Surface we just created is no longer needed.
678            surface.release();
679        } else {
680            setSurface(null);
681        }
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 && mSurfaceHolder == null) {
1007                Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder");
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    // There are currently no defined keys usable from Java with get*Parameter.
1319    // But if any keys are defined, the order must be kept in sync with include/media/mediaplayer.h.
1320    // private static final int KEY_PARAMETER_... = ...;
1321
1322    /**
1323     * Sets the parameter indicated by key.
1324     * @param key key indicates the parameter to be set.
1325     * @param value value of the parameter to be set.
1326     * @return true if the parameter is set successfully, false otherwise
1327     * {@hide}
1328     */
1329    public native boolean setParameter(int key, Parcel value);
1330
1331    /**
1332     * Sets the parameter indicated by key.
1333     * @param key key indicates the parameter to be set.
1334     * @param value value of the parameter to be set.
1335     * @return true if the parameter is set successfully, false otherwise
1336     * {@hide}
1337     */
1338    public boolean setParameter(int key, String value) {
1339        Parcel p = Parcel.obtain();
1340        p.writeString(value);
1341        boolean ret = setParameter(key, p);
1342        p.recycle();
1343        return ret;
1344    }
1345
1346    /**
1347     * Sets the parameter indicated by key.
1348     * @param key key indicates the parameter to be set.
1349     * @param value value of the parameter to be set.
1350     * @return true if the parameter is set successfully, false otherwise
1351     * {@hide}
1352     */
1353    public boolean setParameter(int key, int value) {
1354        Parcel p = Parcel.obtain();
1355        p.writeInt(value);
1356        boolean ret = setParameter(key, p);
1357        p.recycle();
1358        return ret;
1359    }
1360
1361    /**
1362     * Gets the value of the parameter indicated by key.
1363     * @param key key indicates the parameter to get.
1364     * @param reply value of the parameter to get.
1365     */
1366    private native void getParameter(int key, Parcel reply);
1367
1368    /**
1369     * Gets the value of the parameter indicated by key.
1370     * The caller is responsible for recycling the returned parcel.
1371     * @param key key indicates the parameter to get.
1372     * @return value of the parameter.
1373     * {@hide}
1374     */
1375    public Parcel getParcelParameter(int key) {
1376        Parcel p = Parcel.obtain();
1377        getParameter(key, p);
1378        return p;
1379    }
1380
1381    /**
1382     * Gets the value of the parameter indicated by key.
1383     * @param key key indicates the parameter to get.
1384     * @return value of the parameter.
1385     * {@hide}
1386     */
1387    public String getStringParameter(int key) {
1388        Parcel p = Parcel.obtain();
1389        getParameter(key, p);
1390        String ret = p.readString();
1391        p.recycle();
1392        return ret;
1393    }
1394
1395    /**
1396     * Gets the value of the parameter indicated by key.
1397     * @param key key indicates the parameter to get.
1398     * @return value of the parameter.
1399     * {@hide}
1400     */
1401    public int getIntParameter(int key) {
1402        Parcel p = Parcel.obtain();
1403        getParameter(key, p);
1404        int ret = p.readInt();
1405        p.recycle();
1406        return ret;
1407    }
1408
1409    /**
1410     * Sets the send level of the player to the attached auxiliary effect
1411     * {@see #attachAuxEffect(int)}. The level value range is 0 to 1.0.
1412     * <p>By default the send level is 0, so even if an effect is attached to the player
1413     * this method must be called for the effect to be applied.
1414     * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
1415     * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
1416     * so an appropriate conversion from linear UI input x to level is:
1417     * x == 0 -> level = 0
1418     * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
1419     * @param level send level scalar
1420     */
1421    public native void setAuxEffectSendLevel(float level);
1422
1423    /**
1424     * @param request Parcel destinated to the media player. The
1425     *                Interface token must be set to the IMediaPlayer
1426     *                one to be routed correctly through the system.
1427     * @param reply[out] Parcel that will contain the reply.
1428     * @return The status code.
1429     */
1430    private native final int native_invoke(Parcel request, Parcel reply);
1431
1432
1433    /**
1434     * @param update_only If true fetch only the set of metadata that have
1435     *                    changed since the last invocation of getMetadata.
1436     *                    The set is built using the unfiltered
1437     *                    notifications the native player sent to the
1438     *                    MediaPlayerService during that period of
1439     *                    time. If false, all the metadatas are considered.
1440     * @param apply_filter  If true, once the metadata set has been built based on
1441     *                     the value update_only, the current filter is applied.
1442     * @param reply[out] On return contains the serialized
1443     *                   metadata. Valid only if the call was successful.
1444     * @return The status code.
1445     */
1446    private native final boolean native_getMetadata(boolean update_only,
1447                                                    boolean apply_filter,
1448                                                    Parcel reply);
1449
1450    /**
1451     * @param request Parcel with the 2 serialized lists of allowed
1452     *                metadata types followed by the one to be
1453     *                dropped. Each list starts with an integer
1454     *                indicating the number of metadata type elements.
1455     * @return The status code.
1456     */
1457    private native final int native_setMetadataFilter(Parcel request);
1458
1459    private static native final void native_init();
1460    private native final void native_setup(Object mediaplayer_this);
1461    private native final void native_finalize();
1462
1463    /**
1464     * @param index The index of the text track to be turned on.
1465     * @return true if the text track is enabled successfully.
1466     * {@hide}
1467     */
1468    public boolean enableTimedTextTrackIndex(int index) {
1469        if (index < 0) {
1470            return false;
1471        }
1472        return setParameter(KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX, index);
1473    }
1474
1475    /**
1476     * Enables the first timed text track if any.
1477     * @return true if the text track is enabled successfully
1478     * {@hide}
1479     */
1480    public boolean enableTimedText() {
1481        return enableTimedTextTrackIndex(0);
1482    }
1483
1484    /**
1485     * Disables timed text display.
1486     * @return true if the text track is disabled successfully.
1487     * {@hide}
1488     */
1489    public boolean disableTimedText() {
1490        return setParameter(KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX, -1);
1491    }
1492
1493    /**
1494     * @param reply Parcel with audio/video duration info for battery
1495                    tracking usage
1496     * @return The status code.
1497     * {@hide}
1498     */
1499    public native static int native_pullBatteryData(Parcel reply);
1500
1501    @Override
1502    protected void finalize() { native_finalize(); }
1503
1504    /* Do not change these values without updating their counterparts
1505     * in include/media/mediaplayer.h!
1506     */
1507    private static final int MEDIA_NOP = 0; // interface test message
1508    private static final int MEDIA_PREPARED = 1;
1509    private static final int MEDIA_PLAYBACK_COMPLETE = 2;
1510    private static final int MEDIA_BUFFERING_UPDATE = 3;
1511    private static final int MEDIA_SEEK_COMPLETE = 4;
1512    private static final int MEDIA_SET_VIDEO_SIZE = 5;
1513    private static final int MEDIA_TIMED_TEXT = 99;
1514    private static final int MEDIA_ERROR = 100;
1515    private static final int MEDIA_INFO = 200;
1516
1517    private class EventHandler extends Handler
1518    {
1519        private MediaPlayer mMediaPlayer;
1520
1521        public EventHandler(MediaPlayer mp, Looper looper) {
1522            super(looper);
1523            mMediaPlayer = mp;
1524        }
1525
1526        @Override
1527        public void handleMessage(Message msg) {
1528            if (mMediaPlayer.mNativeContext == 0) {
1529                Log.w(TAG, "mediaplayer went away with unhandled events");
1530                return;
1531            }
1532            switch(msg.what) {
1533            case MEDIA_PREPARED:
1534                if (mOnPreparedListener != null)
1535                    mOnPreparedListener.onPrepared(mMediaPlayer);
1536                return;
1537
1538            case MEDIA_PLAYBACK_COMPLETE:
1539                if (mOnCompletionListener != null)
1540                    mOnCompletionListener.onCompletion(mMediaPlayer);
1541                stayAwake(false);
1542                return;
1543
1544            case MEDIA_BUFFERING_UPDATE:
1545                if (mOnBufferingUpdateListener != null)
1546                    mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
1547                return;
1548
1549            case MEDIA_SEEK_COMPLETE:
1550              if (mOnSeekCompleteListener != null)
1551                  mOnSeekCompleteListener.onSeekComplete(mMediaPlayer);
1552              return;
1553
1554            case MEDIA_SET_VIDEO_SIZE:
1555              if (mOnVideoSizeChangedListener != null)
1556                  mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2);
1557              return;
1558
1559            case MEDIA_ERROR:
1560                // For PV specific error values (msg.arg2) look in
1561                // opencore/pvmi/pvmf/include/pvmf_return_codes.h
1562                Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
1563                boolean error_was_handled = false;
1564                if (mOnErrorListener != null) {
1565                    error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
1566                }
1567                if (mOnCompletionListener != null && ! error_was_handled) {
1568                    mOnCompletionListener.onCompletion(mMediaPlayer);
1569                }
1570                stayAwake(false);
1571                return;
1572
1573            case MEDIA_INFO:
1574                if (msg.arg1 != MEDIA_INFO_VIDEO_TRACK_LAGGING) {
1575                    Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
1576                }
1577                if (mOnInfoListener != null) {
1578                    mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
1579                }
1580                // No real default action so far.
1581                return;
1582            case MEDIA_TIMED_TEXT:
1583                if (mOnTimedTextListener != null) {
1584                    if (msg.obj == null) {
1585                        mOnTimedTextListener.onTimedText(mMediaPlayer, null);
1586                    } else {
1587                        if (msg.obj instanceof byte[]) {
1588                            TimedText text = new TimedText((byte[])(msg.obj));
1589                            mOnTimedTextListener.onTimedText(mMediaPlayer, text);
1590                        }
1591                    }
1592                }
1593                return;
1594
1595            case MEDIA_NOP: // interface test message - ignore
1596                break;
1597
1598            default:
1599                Log.e(TAG, "Unknown message type " + msg.what);
1600                return;
1601            }
1602        }
1603    }
1604
1605    /**
1606     * Called from native code when an interesting event happens.  This method
1607     * just uses the EventHandler system to post the event back to the main app thread.
1608     * We use a weak reference to the original MediaPlayer object so that the native
1609     * code is safe from the object disappearing from underneath it.  (This is
1610     * the cookie passed to native_setup().)
1611     */
1612    private static void postEventFromNative(Object mediaplayer_ref,
1613                                            int what, int arg1, int arg2, Object obj)
1614    {
1615        MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
1616        if (mp == null) {
1617            return;
1618        }
1619
1620        if (mp.mEventHandler != null) {
1621            Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
1622            mp.mEventHandler.sendMessage(m);
1623        }
1624    }
1625
1626    /**
1627     * Interface definition for a callback to be invoked when the media
1628     * source is ready for playback.
1629     */
1630    public interface OnPreparedListener
1631    {
1632        /**
1633         * Called when the media file is ready for playback.
1634         *
1635         * @param mp the MediaPlayer that is ready for playback
1636         */
1637        void onPrepared(MediaPlayer mp);
1638    }
1639
1640    /**
1641     * Register a callback to be invoked when the media source is ready
1642     * for playback.
1643     *
1644     * @param listener the callback that will be run
1645     */
1646    public void setOnPreparedListener(OnPreparedListener listener)
1647    {
1648        mOnPreparedListener = listener;
1649    }
1650
1651    private OnPreparedListener mOnPreparedListener;
1652
1653    /**
1654     * Interface definition for a callback to be invoked when playback of
1655     * a media source has completed.
1656     */
1657    public interface OnCompletionListener
1658    {
1659        /**
1660         * Called when the end of a media source is reached during playback.
1661         *
1662         * @param mp the MediaPlayer that reached the end of the file
1663         */
1664        void onCompletion(MediaPlayer mp);
1665    }
1666
1667    /**
1668     * Register a callback to be invoked when the end of a media source
1669     * has been reached during playback.
1670     *
1671     * @param listener the callback that will be run
1672     */
1673    public void setOnCompletionListener(OnCompletionListener listener)
1674    {
1675        mOnCompletionListener = listener;
1676    }
1677
1678    private OnCompletionListener mOnCompletionListener;
1679
1680    /**
1681     * Interface definition of a callback to be invoked indicating buffering
1682     * status of a media resource being streamed over the network.
1683     */
1684    public interface OnBufferingUpdateListener
1685    {
1686        /**
1687         * Called to update status in buffering a media stream received through
1688         * progressive HTTP download. The received buffering percentage
1689         * indicates how much of the content has been buffered or played.
1690         * For example a buffering update of 80 percent when half the content
1691         * has already been played indicates that the next 30 percent of the
1692         * content to play has been buffered.
1693         *
1694         * @param mp      the MediaPlayer the update pertains to
1695         * @param percent the percentage (0-100) of the content
1696         *                that has been buffered or played thus far
1697         */
1698        void onBufferingUpdate(MediaPlayer mp, int percent);
1699    }
1700
1701    /**
1702     * Register a callback to be invoked when the status of a network
1703     * stream's buffer has changed.
1704     *
1705     * @param listener the callback that will be run.
1706     */
1707    public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
1708    {
1709        mOnBufferingUpdateListener = listener;
1710    }
1711
1712    private OnBufferingUpdateListener mOnBufferingUpdateListener;
1713
1714    /**
1715     * Interface definition of a callback to be invoked indicating
1716     * the completion of a seek operation.
1717     */
1718    public interface OnSeekCompleteListener
1719    {
1720        /**
1721         * Called to indicate the completion of a seek operation.
1722         *
1723         * @param mp the MediaPlayer that issued the seek operation
1724         */
1725        public void onSeekComplete(MediaPlayer mp);
1726    }
1727
1728    /**
1729     * Register a callback to be invoked when a seek operation has been
1730     * completed.
1731     *
1732     * @param listener the callback that will be run
1733     */
1734    public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
1735    {
1736        mOnSeekCompleteListener = listener;
1737    }
1738
1739    private OnSeekCompleteListener mOnSeekCompleteListener;
1740
1741    /**
1742     * Interface definition of a callback to be invoked when the
1743     * video size is first known or updated
1744     */
1745    public interface OnVideoSizeChangedListener
1746    {
1747        /**
1748         * Called to indicate the video size
1749         *
1750         * @param mp        the MediaPlayer associated with this callback
1751         * @param width     the width of the video
1752         * @param height    the height of the video
1753         */
1754        public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
1755    }
1756
1757    /**
1758     * Register a callback to be invoked when the video size is
1759     * known or updated.
1760     *
1761     * @param listener the callback that will be run
1762     */
1763    public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
1764    {
1765        mOnVideoSizeChangedListener = listener;
1766    }
1767
1768    private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
1769
1770    /**
1771     * Interface definition of a callback to be invoked when a
1772     * timed text is available for display.
1773     * {@hide}
1774     */
1775    public interface OnTimedTextListener
1776    {
1777        /**
1778         * Called to indicate an avaliable timed text
1779         *
1780         * @param mp             the MediaPlayer associated with this callback
1781         * @param text           the timed text sample which contains the text
1782         *                       needed to be displayed and the display format.
1783         * {@hide}
1784         */
1785        public void onTimedText(MediaPlayer mp, TimedText text);
1786    }
1787
1788    /**
1789     * Register a callback to be invoked when a timed text is available
1790     * for display.
1791     *
1792     * @param listener the callback that will be run
1793     * {@hide}
1794     */
1795    public void setOnTimedTextListener(OnTimedTextListener listener)
1796    {
1797        mOnTimedTextListener = listener;
1798    }
1799
1800    private OnTimedTextListener mOnTimedTextListener;
1801
1802
1803    /* Do not change these values without updating their counterparts
1804     * in include/media/mediaplayer.h!
1805     */
1806    /** Unspecified media player error.
1807     * @see android.media.MediaPlayer.OnErrorListener
1808     */
1809    public static final int MEDIA_ERROR_UNKNOWN = 1;
1810
1811    /** Media server died. In this case, the application must release the
1812     * MediaPlayer object and instantiate a new one.
1813     * @see android.media.MediaPlayer.OnErrorListener
1814     */
1815    public static final int MEDIA_ERROR_SERVER_DIED = 100;
1816
1817    /** The video is streamed and its container is not valid for progressive
1818     * playback i.e the video's index (e.g moov atom) is not at the start of the
1819     * file.
1820     * @see android.media.MediaPlayer.OnErrorListener
1821     */
1822    public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
1823
1824    /**
1825     * Interface definition of a callback to be invoked when there
1826     * has been an error during an asynchronous operation (other errors
1827     * will throw exceptions at method call time).
1828     */
1829    public interface OnErrorListener
1830    {
1831        /**
1832         * Called to indicate an error.
1833         *
1834         * @param mp      the MediaPlayer the error pertains to
1835         * @param what    the type of error that has occurred:
1836         * <ul>
1837         * <li>{@link #MEDIA_ERROR_UNKNOWN}
1838         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
1839         * </ul>
1840         * @param extra an extra code, specific to the error. Typically
1841         * implementation dependant.
1842         * @return True if the method handled the error, false if it didn't.
1843         * Returning false, or not having an OnErrorListener at all, will
1844         * cause the OnCompletionListener to be called.
1845         */
1846        boolean onError(MediaPlayer mp, int what, int extra);
1847    }
1848
1849    /**
1850     * Register a callback to be invoked when an error has happened
1851     * during an asynchronous operation.
1852     *
1853     * @param listener the callback that will be run
1854     */
1855    public void setOnErrorListener(OnErrorListener listener)
1856    {
1857        mOnErrorListener = listener;
1858    }
1859
1860    private OnErrorListener mOnErrorListener;
1861
1862
1863    /* Do not change these values without updating their counterparts
1864     * in include/media/mediaplayer.h!
1865     */
1866    /** Unspecified media player info.
1867     * @see android.media.MediaPlayer.OnInfoListener
1868     */
1869    public static final int MEDIA_INFO_UNKNOWN = 1;
1870
1871    /** The video is too complex for the decoder: it can't decode frames fast
1872     *  enough. Possibly only the audio plays fine at this stage.
1873     * @see android.media.MediaPlayer.OnInfoListener
1874     */
1875    public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
1876
1877    /** MediaPlayer is temporarily pausing playback internally in order to
1878     * buffer more data.
1879     * @see android.media.MediaPlayer.OnInfoListener
1880     */
1881    public static final int MEDIA_INFO_BUFFERING_START = 701;
1882
1883    /** MediaPlayer is resuming playback after filling buffers.
1884     * @see android.media.MediaPlayer.OnInfoListener
1885     */
1886    public static final int MEDIA_INFO_BUFFERING_END = 702;
1887
1888    /** Bad interleaving means that a media has been improperly interleaved or
1889     * not interleaved at all, e.g has all the video samples first then all the
1890     * audio ones. Video is playing but a lot of disk seeks may be happening.
1891     * @see android.media.MediaPlayer.OnInfoListener
1892     */
1893    public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
1894
1895    /** The media cannot be seeked (e.g live stream)
1896     * @see android.media.MediaPlayer.OnInfoListener
1897     */
1898    public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
1899
1900    /** A new set of metadata is available.
1901     * @see android.media.MediaPlayer.OnInfoListener
1902     */
1903    public static final int MEDIA_INFO_METADATA_UPDATE = 802;
1904
1905    /**
1906     * Interface definition of a callback to be invoked to communicate some
1907     * info and/or warning about the media or its playback.
1908     */
1909    public interface OnInfoListener
1910    {
1911        /**
1912         * Called to indicate an info or a warning.
1913         *
1914         * @param mp      the MediaPlayer the info pertains to.
1915         * @param what    the type of info or warning.
1916         * <ul>
1917         * <li>{@link #MEDIA_INFO_UNKNOWN}
1918         * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
1919         * <li>{@link #MEDIA_INFO_BUFFERING_START}
1920         * <li>{@link #MEDIA_INFO_BUFFERING_END}
1921         * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
1922         * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
1923         * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
1924         * </ul>
1925         * @param extra an extra code, specific to the info. Typically
1926         * implementation dependant.
1927         * @return True if the method handled the info, false if it didn't.
1928         * Returning false, or not having an OnErrorListener at all, will
1929         * cause the info to be discarded.
1930         */
1931        boolean onInfo(MediaPlayer mp, int what, int extra);
1932    }
1933
1934    /**
1935     * Register a callback to be invoked when an info/warning is available.
1936     *
1937     * @param listener the callback that will be run
1938     */
1939    public void setOnInfoListener(OnInfoListener listener)
1940    {
1941        mOnInfoListener = listener;
1942    }
1943
1944    private OnInfoListener mOnInfoListener;
1945
1946}
1947