Android multimedia and camera details 3

Source: Internet
Author: User
Process audio focus

Although only one activity can run at a time, Android is a multi-task environment. this poses a special challenge to the use of audio applications, because only one audio output may be used by multiple media. before Android, there was no built-in mechanism to handle this problem, so it may lead to bad User Experience in some cases. for example, when a user is listening to music and another application needs to notify the user of important things, the user may be unable to listen to the notifications due to the sound of music. since android2.2, the platform provides applications with a way to negotiate how they use the device audio output. This mechanism is called the audio focus.

When your application needs to output audio, such as music and notifications, you should always request the audio focus. once the application has focus, it can use audio output freely. however, it should always listen to changes in focus. if the notification loses the focus, it should immediately kill the sound or reduce it to the mute level (there is a flag indicating which one should be selected) and resume loud playback only after the focus is obtained again.

In the future, the audio focus will be on cooperation. therefore, applications are expected to (and strongly encouraged) follow the audio focus policy, but are not forced by the system. if an app still wants to play music loudly after it loses the audio focus, the system will not stop it. however, the user has a bad experience and wants to uninstall the bird application.

To request the audio focus, you must call requestaudiofocus () from audiomanager, as shown below:

Audiomanager = (audiomanager) getsystemservice (context. audio_service); int result = audiomanager. requestaudiofocus (this, audiomanager. stream_music, audiomanager. audiofocus_gain); If (result! = Audiomanager. audiofocus_request_granted) {// cannot obtain audio focus}

The first parameter of requestaudiofocus () is an audiomanager. onaudiofocuschangelistener, whose onaudiofocuschange () method is called when the audio focus is changed. therefore, you should also implement this interface on your service and activity. for example:

class MyService extends Service                implements AudioManager.OnAudioFocusChangeListener {    // ....    public void onAudioFocusChange(int focusChange) {        // Do something based on focus change...    }}

The focuschange parameter tells you how the audio focus changes. It can be a constant defined in audiomanager ):

  • Audiofocus_gain: You have obtained the audio focus.

  • Audiofocus_loss: You have lost the audio focus for a long time. you must stop playing all audio. it is expected that you may not obtain the audio focus for a long time, so this is a good place to clean up your resources. for example, you must release mediaplayer.

  • Audiofocus_loss_transient: You temporarily lose the audio focus and will soon get it again. You must stop all the audio playback, but you can keep your resources, because you may soon get the focus again.

  • Audiofocus_loss_transient_can_duck: You temporarily lose the audio focus, but you are allowed to continue playing at low volume instead of completely stopping.

The following is an example:

public void onAudioFocusChange(int focusChange) {    switch (focusChange) {        case AudioManager.AUDIOFOCUS_GAIN:            // resume playback            if (mMediaPlayer == null) initMediaPlayer();            else if (!mMediaPlayer.isPlaying()) mMediaPlayer.start();            mMediaPlayer.setVolume(1.0f, 1.0f);            break;        case AudioManager.AUDIOFOCUS_LOSS:            // Lost focus for an unbounded amount of time: stop playback and release media player            if (mMediaPlayer.isPlaying()) mMediaPlayer.stop();            mMediaPlayer.release();            mMediaPlayer = null;            break;        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:            // Lost focus for a short time, but we have to stop            // playback. We don't release the media player because playback            // is likely to resume            if (mMediaPlayer.isPlaying()) mMediaPlayer.pause();            break;        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:            // Lost focus for a short time, but it's ok to keep playing            // at an attenuated level            if (mMediaPlayer.isPlaying()) mMediaPlayer.setVolume(0.1f, 0.1f);            break;    }}

Remember that the audio focus API is only available in apilevel 8 (android2.2) and later versions. If you want to support earlier Android versions, you must adopt a compatibility policy when possible to use features, if not, you shoshould adopt a backward compatibility strategy that allows you touse this feature if available, and fall back seamlessly if not.

You can use reflection to call the audio focus method or implement all audio focus functions in a separate class called audiofocushelper to achieve forward compatibility. The following is a class:

Public class audiofocushelper implements audiomanager. onaudiofocuschangelistener {audiomanager maudiomanager; // here is another field. You may want to save an interface reference. This interface is used to communicate with your service to report changes in focus. public audiofocushelper (context CTX,/* Other parameters */) {maudiomanager = (audiomanager) mcontext. getsystemservice (context. audio_service );//...} public Boolean requestfocus () {return audiomanager. audiofocus_request_granted = maudiomanager. requestaudiofocus (mcontext, audiomanager. stream_music, audiomanager. audiofocus_gain);} public Boolean abandonfocus () {return audiomanager. audiofocus_request_granted = maudiomanager. abandonaudiofocus (this) ;}@ override public void onaudiofocuschange (INT focuschange) {// Let your service know that the focus has changed} You can create an audiofocushelper class instance only when detecting that the system is running API Level 8 or earlier. for example: if (Android. OS. build. version. sdk_int> = 8) {maudiofocushelper = new audiofocushelper (getapplicationcontext (), this);} else {maudiofocushelper = NULL ;}

Clear

As mentioned above, a mediaplayer object can consume a large amount of system resources, so you should keep it and release it immediately when it is used up. it is important to call clear methods rather than relying on the system's garbage collection mechanism, because mediaplayer may exist for a long time before being collected, although it only occupies memory, it does not affect other media-related resources. therefore, when you use a service, you should always override the ondestroy () method to ensure the release of mediaplayer:

public class MyService extends Service {   MediaPlayer mMediaPlayer;   // ...   @Override   public void onDestroy() {       if (mMediaPlayer != null) mMediaPlayer.release();   }}

You should also find other opportunities to release your mediaplayer. for example, if you expect that the media cannot be played for a long time (for example, after losing the audio focus), you should release your mediaplayer and recreate it later. in turn, if you predict that playing will only stop for a short time, you should keep your mediaplayer to avoid creating too much, rather than re-"prepare" it.

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.