Android Multimedia-mediaplayer Wake-up lock and audio focus

Source: Internet
Author: User

Wake-up lock for MediaPlayer


Generally use MediaPlayer to play the audio stream, it is recommended to use a service to host the MediaPlayer, rather than directly in the activity to use. But in the power design of the Android system, in order to conserve battery consumption, if the device is asleep, the system will attempt to lower or shut down some features that are not required by the device, including the cup and WiFi hardware, and then, if it is an app that plays music in the background, Lowering the cup may cause interference with audio playback while running in the background, and turning off WiFi may cause errors in the access of the network audio stream.

To ensure that MediaPlayer's hosted services continue to function properly while the system sleeps, Android provides us with a mechanism to wake the lock (wake locks). It can sleep in the system and still keep the lock hardware working properly.

Make sure that when the MediaPlayer is running, even if the system sleeps on the CPU, you need to use Mediaplayer.setwakemode () to set the wake-up lock for MediaPlayer. The following is the signature of Setwakmode ():
Setwakemode (context context, int mode)

The first parameter is the current context, the second parameter is the state that needs to be locked, and is set to the constant of type int, defined in the final class of PowerManager. PowerManager is specifically used to manage the Android power consumption of the lock state, related to the lock Cup, there are four, respectively, the cup, screen, keyboard, etc. to maintain a variety of wake-up status, here only need to set to Partial_wake_lock.

MediaPlayer = new MediaPlayer ();//Set Cup lock Mediaplayer.setwakemode (Getapplicationcontext (), Powermanager.partial_ Wake_lock);
Generally for locks, locking is usually required to unlock, but here the wake is said to be associated with the MediaPlayer, so only after the use of release () released MediaPlayer can not be explicitly unlocked. When you use Setwakemode to set the wake-up lock, you must also assign the appropriate permissions to the app:

<uses-permission android:name= "Android.permission.WAKE_LOCK"/>
In other words, how to lock the WiFi hardware while the system is sleeping to keep it running properly. The WiFi lock is operated through the Wifilock, while the Wifilock is managed via Wifimanager, and the WiFi lock is done via Wifimanager.createwifilock ().

Wifimanager.wifilock createwifilock (int lockType, String tag)

This method has multiple overloads, here is the first parameter to set the state of the lock, a constant of type int, defined in the context class, where the application scenario is generally set to Wifi_mode_full. The second parameter is a Wifilock flag that is used to determine the wifilock.

wifilock= (Wifimanager) Getsystemservice (this. Wifi_service). Createwifilock (Wifimanager.wifi_mode_full, "Mylock"); Wifilock.acquire ();                 
Of course, after you lock the WiFi in the app, you need to unlock the WiFi hardware at Mediaplayer.release (), and to avoid accidental shutdowns, it's best to release it in the Android component's Ondestory (). Release the WiFi lock using Wifilock.release ().

/*** Stop playing */protected void Stop () {if (MediaPlayer! = null && mediaplayer.isplaying ()) {              mediaplayer.stop (); C1/>mediaplayer.release ();              MediaPlayer = null;              Free WiFi lock             wifilock.release ();             Btn_play.setenabled (true);             Toast.maketext (This, "Stop playing", 0). Show ();         }      }      @Override     protected void OnDestroy () {         //recycle resources at the end of activity         if (mediaPlayer! = null && Mediaplayer.isplaying ()) {             mediaplayer.stop ();             Mediaplayer.release ();             MediaPlayer = null;             Free WiFi lock             wifilock.release ();         }         Super.ondestroy ();     }

MediaPlayer's audio focus


As is known to all, Android is a multitasking operating system, so for audio playback, there may be several different media services playing simultaneously, which may lead to a more cluttered sound environment, while missing some important sound reminders. After Android2.2, Android provides a mechanism for applications to negotiate the use of device audio output, a mechanism called audio focus.


When the application needs to output audio or notification, need to request the audio focus, when the request to get the audio focus, listen to the audio focus of the transformation, when the audio focus is changed, according to the return of the audio focus code corresponding processing. The registration of the audio focus is set using the Audiomanager.requestaudiofocus () method of the audio manager. Its signature is as follows:


int Requestaudiofocus (audiomanager.onaudiofocuschangelistener l, int streamtype, int durationhint)


The return value of this method is the int type, and its meaning is defined in Audiomanager as a constant representation of audiofocus_request_failed (getting the audio focus succeeds), Audiofocus_request_ Granted (get audio focus failed). One of the important things is the first parameter, the callback function for the change of the audio focus, in which you can set if the audio focus is transformed, how the current application manages the MediaPlayer, the second parameter is the type of the media stream, and the third parameter is the persisted state.


Audiomanager.onaudiofocuschangelistener is the listener for the audio focus transformation, which needs to implement a method: Onaudiofocuschange (int focuschange) callbacks when the audio focus is transformed. It has a parameter, for the current state code that represents the audio focus for the current application, to specify the corresponding operation through this status code, sometimes the audio status changes, and does not necessarily need to stop the audio playback.


Focuschange There are several status codes:


Audiofocus_gain: Gets the audio focus.
Audiofocus_loss: Loses the audio focus and lasts for a long time. This is where we need to stop MediaPlayer playback.
Audiofocus_loss_transient: Loses the audio focus, but does not last for a long time, pauses the playback of the MediaPlayer and waits for the audio focus to regain.
Audiofocus_loss_transient_can_duck: Temporarily loses the audio focus, but does not need to stop playback, just reduce the sound method.

 Audiomanager = (Audiomanager) Getsystemservice (this. Audio_service); int result = Audiomanager.requestaudiofocus (new Onaudiofocuschangelistener () {@Override public void Onaudiofoc Uschange (int focuschange) {switch (focuschange) {case Audiomanager.audiofocus_gain://Get             Audio Focus if (!mediaplayer.isplaying ()) {Mediaplayer.start ();             }//Restore volume Mediaplayer.setvolume (1.0f, 1.0f);         Break                 Case Audiomanager.audiofocus_loss://Long lost audio focus, release MediaPlayer if (mediaplayer.isplaying ())             Mediaplayer.stop ();             Mediaplayer.release ();             MediaPlayer = null;         Break Case Audiomanager.audiofocus_loss_transient://Show lost audio focus, pause playback wait to regain audio focus if (mediaplayer.isplaying (             )) Mediaplayer.pause ();         Break      Case Audiomanager.audiofocus_loss_transient_can_duck:       Loss of audio focus, no need to stop playback, lower sound if (mediaplayer.isplaying ()) {Mediaplayer.setvolume (0.1f, 0.1f             );         } break; }}}, Audiomanager.stream_music, Audiomanager.audiofocus_gain);

Summarize


The above explains some of the advanced content of MediaPlayer, after mastering the use of MediaPlayer, the development of music playing the application of the class can be handy. From the aspect of user experience, if the real development of a player class software, you need to listen to Audio_becoming_noisy broadcast, it will be in the audio output source from other output sources to the device speakers when the broadcast, listen to the radio when the audio output source changes to the device speaker, Stop playback so that you do not continue to output audio playback from the speaker when the headset or the extra audio output hardware is disconnected from the device.


SOURCE Link: http://download.csdn.net/detail/duanyu218/7475569


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.