Android multimedia-MediaPlayer wake-up lock and audio focus

Source: Internet
Author: User

MediaPlayer wake-up lock


Generally, MediaPlayer is used to play audio streams. We recommend that you use a Service to carry MediaPlayer instead of directly using it in the Activity. However, in the Android system's power consumption design, to save battery consumption, if the device is in sleep state, the system will try to reduce or disable some features that are not required by the device, including the CPU and Wifi hardware. Then, if it is an application for playing music in the background, lowering the CUP may affect normal playing of audio during background operation. Disabling Wifi may cause an error in obtaining the network audio stream.

To ensure that the services carried by the MediaPlayer continue to run normally during system sleep, Android provides us with a wake-up lock mechanism. It can sleep in the system and still keeps the locked Hardware working properly.

Make sure that the system can run properly even if the CPU is sleep when the MediaPlayer is running. You need to use MediaPlayer. setWakeMode () to set a wake-up lock for the MediaPlayer. The following is the setWakMode () signature:
SetWakeMode (Context context, int mode)

The first parameter is the current context, and the second parameter is the state to be locked. It is set to a constant of the int type and is defined in the final class PowerManager. PowerManager is designed to manage the locking status of Android power consumption. It is related to locking the CUP. There are four types of locking statuses, namely, setting various wake-up statuses such as CUP, screen, and keyboard, here, you only need to set it to PARTIAL_WAKE_LOCK.

MediaPlayer = new MediaPlayer (); // sets the CUP to lock mediaPlayer. setWakeMode (getApplicationContext (), PowerManager. PARTIAL_WAKE_LOCK );
Generally, you need to unlock a lock, but the wake-up here is associated with the MediaPlayer, so you only need to release the MediaPlayer after use, you do not need to explicitly unlock it. When you use setWakeMode to set the wake-up lock, you must also grant the corresponding permissions to the application:

 
Let's talk about how to lock the wifi hardware and keep it running normally during system sleep. Wi-Fi locks are operated through WifiLock, while WifiLock is managed through WifiManager, And wifi locks are performed through WifiManager. createWifiLock.

WifiManager. WifiLock createWifiLock (int lockType, String tag)

This method has multiple reloads. As described here, the first parameter sets the lock status as an int type constant, which is defined in the Context class, the application scenario here is generally set to WIFI_MODE_FULL. The second parameter is the WifiLock flag, used to determine the wifiLock.

wifiLock= ((WifiManager) getSystemService(this.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");wifiLock.acquire();                 
Of course, after the Wifi is locked in the application, you still need to go to the MediaPlayer. to avoid unexpected shutdown, it is best to release the wifi hardware in the onDestory () of the Android component and use WifiLock to release the Wifi lock. release ().

/*** Stop playing */protected void stop () {if (mediaPlayer! = Null & mediaPlayer. isPlaying () {mediaPlayer. stop (); mediaPlayer. release (); mediaPlayer = null; // release the wifi lock wifiLock. release (); btn_play.setEnabled (true); Toast. makeText (this, "Stop playing", 0 ). show () ;}@ Override protected void onDestroy () {// reclaim resources when activity ends if (mediaPlayer! = Null & mediaPlayer. isPlaying () {mediaPlayer. stop (); mediaPlayer. release (); mediaPlayer = null; // release the wifi lock wifiLock. release ();} super. onDestroy ();}

MediaPlayer audio focus


As we all know, Android is a multi-task operating system, so for audio playback, there may be several different media services that play simultaneously, which may lead to a messy sound environment, and missed some important voice reminders. After Android, Android provides a mechanism for application negotiation to use the device audio output. This mechanism is called the audio focus.


When the application needs to output audio or notifications, it needs to request the audio focus. After the request gets the audio focus, it listens to the audio focus change. When the audio focus changes, process the returned audio focus code. The registration of 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 returned value of this method is of the int type. It is defined in AudioManager to indicate AUDIOFOCUS_REQUEST_FAILED (audio focus is obtained successfully) and AUDIOFOCUS_REQUEST_GRANTED (audio focus fails to be obtained ). The important parameter is the first parameter, which is the callback function for audio focus change. You can set how the current application manages MediaPlayer if the audio focus changes, the second parameter is the media stream type, and the third parameter is the continuous state.


AudioManager. OnAudioFocusChangeListener is the listener for audio focus change. One method must be implemented: onAudioFocusChange (int focusChange) callback during audio focus change. It has a parameter that indicates the status code of the current audio focus for the current application. You can use this status code to specify the corresponding operation. In some cases, the audio status changes, you do not have to stop playing audio.


FocusChange has several status codes:


AUDIOFOCUS_GAIN: obtains the audio focus.
AUDIOFOCUS_LOSS: loses the audio focus for a long time. This is where we need to stop playing MediaPlayer.
AUDIOFOCUS_LOSS_TRANSIENT: the audio focus is lost, but it does not last for a long time. You need to pause MediaPlayer playback and wait for the audio focus to be restored.
AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: the audio focus is temporarily lost, but playback does not need to be stopped. You only need to reduce the sound.

AudioManager = (AudioManager) getSystemService (this. AUDIO_SERVICE); int result = audioManager. requestAudioFocus (new OnAudioFocusChangeListener () {@ Override public void onAudioFocusChange (int focusChange) {switch (focusChange) {case AudioManager. AUDIOFOCUS_GAIN: // obtain the audio focus if (! MediaPlayer. isPlaying () {mediaPlayer. start ();} // restore the volume mediaPlayer. setVolume (1.0f, 1.0f); break; case AudioManager. AUDIOFOCUS_LOSS: // permanently loses the audio focus and releases MediaPlayer if (mediaPlayer. isPlaying () mediaPlayer. stop (); mediaPlayer. release (); mediaPlayer = null; break; case AudioManager. AUDIOFOCUS_LOSS_TRANSIENT: // indicates that the audio focus is lost. Pause the playback and wait for the audio focus to be obtained again. if (mediaPlayer. isPlaying () mediaPlayer. pause (); break; case AudioManager. AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: // if (mediaPlayer. isPlaying () {mediaPlayer. setVolume (0.1f, 0.1f) ;}break ;}}, AudioManager. STREAM_MUSIC, AudioManager. AUDIOFOCUS_GAIN );

Summary


The above explains some advanced MediaPlayer content. After mastering the use of MediaPlayer, you can easily develop music playing applications. From the aspect of user experience, if you develop a player software, you need to listen to AUDIO_BECOMING_NOISY broadcast, it sends this broadcast when the audio output source is changed from another output source to the device speaker. The Listener stops playing when the audio output source changes to the device speaker, this ensures that when the headset or additional audio output hardware is disconnected from the device, the audio will not be output again from the speaker.


Source code 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.