AudioManager详解(结合源代码)



AudioManager:用来对音量大小,声音模式(静音,震动,震动加声音等模式)的管理, 还有用它来注册“插入耳机”时的广播接收者(Action: android.intent.action.MEDIA_BUTTON)

源码(没有Android源码的可以看下我之前的博文,有提供下载地址哈~)所在位置:
Android-4.0/frameworks/base/media/java/android/media/AudioManager.java


一. 首先在应用层面上分析下怎么使用这个类:


1.获取AudioManager实例对象
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

2.AudioManager能实现的一些基本的功能的函数介绍


adjustStreamVolume(int streamType, int direction, int flags)
/**
方法分析:(通过该方法可以控制特定的声音的音量)

用"步长"调整手机声音大小的函数(Adjusts the volume of a particular stream by one step in a direction.)
这个函数只能用于应用程序对Audio属性的设置或者通话(telephony)应用程序

streamType(表示要处理的声音是哪种):
    能使用的streamType的值包括:
    STREAM_VOICE_CALL(通话)
    STREAM_SYSTEM(系统声音)
    STREAM_RING(铃声)
    STREAM_MUSIC(音乐)
    STREAM_ALARM(闹铃)
    
direction(“方向”:顾名思义是要往上增加音量,往下减少音量,还是维持不变):
    能使用的值有:
    ADJUST_LOWER(降低)
    ADJUST_RAISE(升高)
    ADJUST_SAME(维持原来的)[呵~~呵]

flags(可选标志位):
    flags One(单个参数) or more flags.(参数1|参数2|参数3..)
    如下flag:
        AudioManager.FLAG_SHOW_UI(显示出音量调节UI)
        AudioManager.FLAG_ALLOW_RINGER_MODES
        AudioManager.FLAG_PLAY_SOUND
        AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE
        AudioManager.FLAG_VIBRATE

对应get方法:
    getStreamVolume(int streamType)
    最大值为7,最小值为0,当为0时,手机自动将模式调整为“震动模式”
*/


adjustVolume(int direction, int flags)
/**
方法分析:
系统智能地判断现在是要处理的是哪个类型的声音("通话音","媒体音"等)
如果你在打电话,这个时候这个函数相应处理的就是"通话音",而如果你在听歌,处理的就是“媒体音”~~平时其实用一些软件也是有这种感觉的哈~~

direction(“方向”:顾名思义是要往上增加音量,往下减少音量,还是维持不变):
    能使用的值有:
    ADJUST_LOWER(降低)
    ADJUST_RAISE(升高)
    ADJUST_SAME(维持原来的)[呵~~呵]

flags(可选标志位):
    flags One(单个参数) or more flags.(参数1|参数2|参数3..)
    如下flag:
        AudioManager.FLAG_SHOW_UI(显示出音量调节UI)
        AudioManager.FLAG_ALLOW_RINGER_MODES
        AudioManager.FLAG_PLAY_SOUND
        AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE
        AudioManager.FLAG_VIBRATE

*/

int getMode()
/**
方法分析:
得到声音的模式

返回值(int)对应的宏:
    MODE_INVALID: 发生异常的时候返回
    MODE_NORMAL: 普通模式
    MODE_RINGTONE:铃声模式
    MODE_IN_CALL: 通话模式
    MODE_IN_COMMUNICATION:通话模式

对应set方法:
    setMode(int mode)
*/


int getRingerMode()
/**
方法分析:
得到铃声设置的模式

返回值(int)对应的宏:
    RINGER_MODE_NORMAL(铃声模式)
         RINGER_MODE_SILENT(静音模式)
    RINGER_MODE_VIBRATE(静音但是震动)

对应set方法(改变铃声模式):
    setRingerMode(int ringerMode)
*/

getStreamMaxVolume(int streamType)
/**

方法分析:
    得到手机最大的音量

*/

setStreamMute(int streamType, boolean state)
/**

方法分析:
    让streamType指定的对应的声音流做处理
    state为true表示让它静音,false表示不让它静音
    如:让音乐静音
    setStreamMute(AudioManager.STREAM_MUSIC , true);
*/


3.实例Demo代码

//获取实例

AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);



//获取/设置系统音量

audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);

audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM,

            AudioManager.ADJUST_RAISE

            , AudioManager.FLAG_SHOW_UI);

//获取/设置音乐音量

audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,

            AudioManager.ADJUST_RAISE

            , AudioManager.FLAG_SHOW_UI);

//其他的类似







//获取/设置铃声的模式

int ringMode = audioManager.getRingerMode();

//普通模式

audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);

//静音模式

audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);

//其他的类似



//设置声音流静音/不静音

//音乐静音

audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);

//铃声不静音

audioManager.setStreamMute(AudioManager.STREAM_RING, false);

//其他的类似






二. 分析下这个类里面的部分源代码


由于知识水平有限,我觉得下面的代码自己分析不好,建议看这篇博文:http://blog.csdn.net/qinjuning/article/details/6938436



 /*

    为Action == “MEDIA_BUTTON”注册广播接收者



    用来广播“耳机插入”的事件



    eventReceiver一般接受的参数为这样一个ComponentName对象



    如:

    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    ComponentName component = new ComponentName(context.getApplicationContext(),MediaControlReceiver.class);

    audioManager.registerMediaButtonEventReceiver(component);    

    

*/

 public void registerMediaButtonEventReceiver(ComponentName eventReceiver) {

        if (eventReceiver == null) {

            return;

        }

        if (!eventReceiver.getPackageName().equals(mContext.getPackageName())) {

            Log.e(TAG, "registerMediaButtonEventReceiver() error: " +

                    "receiver and context package names don't match");

            return;

        }

        // construct a PendingIntent for the media button and register it

        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);

        //     the associated intent will be handled by the component being registered

        mediaButtonIntent.setComponent(eventReceiver);

        PendingIntent pi = PendingIntent.getBroadcast(mContext,

                0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);

        registerMediaButtonIntent(pi, eventReceiver);

    }



/**

为MediaButton注册一个Intent

可以发现,这边也是通过aidl的方式进行的调用

IAudioService的aidl:https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/media/java/android/media/IAudioService.aidl  

*/

    public void registerMediaButtonIntent(PendingIntent pi, ComponentName eventReceiver) {

        if ((pi == null) || (eventReceiver == null)) {

            Log.e(TAG, "Cannot call registerMediaButtonIntent() with a null parameter");

            return;

        }

        IAudioService service = getService();

        try {

            // pi != null

            service.registerMediaButtonIntent(pi, eventReceiver);

        } catch (RemoteException e) {

            Log.e(TAG, "Dead object in registerMediaButtonIntent"+e);

        }

    }



    /**

     * Unregister the receiver of MEDIA_BUTTON intents.

     * @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}

     *      that was registered with {@link #registerMediaButtonEventReceiver(ComponentName)}.

     */

    public void unregisterMediaButtonEventReceiver(ComponentName eventReceiver) {

        if (eventReceiver == null) {

            return;

        }

        // construct a PendingIntent for the media button and unregister it

        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);

        //     the associated intent will be handled by the component being registered

        mediaButtonIntent.setComponent(eventReceiver);

        PendingIntent pi = PendingIntent.getBroadcast(mContext,

                0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);

        unregisterMediaButtonIntent(pi, eventReceiver);

    }



    /**

     * @hide

     */

    public void unregisterMediaButtonIntent(PendingIntent pi, ComponentName eventReceiver) {

        IAudioService service = getService();

        try {

            service.unregisterMediaButtonIntent(pi, eventReceiver);

        } catch (RemoteException e) {

            Log.e(TAG, "Dead object in unregisterMediaButtonIntent"+e);

        }

    }



    /**

     * Registers the remote control client for providing information to display on the remote

     * controls.

     * @param rcClient The remote control client from which remote controls will receive

     *      information to display.

     * @see RemoteControlClient

     */

    public void registerRemoteControlClient(RemoteControlClient rcClient) {

        if ((rcClient == null) || (rcClient.getRcMediaIntent() == null)) {

            return;

        }

        IAudioService service = getService();

        try {

            service.registerRemoteControlClient(rcClient.getRcMediaIntent(),   /* mediaIntent   */

                    rcClient.getIRemoteControlClient(),                        /* rcClient      */

                    // used to match media button event receiver and audio focus

                    mContext.getPackageName());                                /* packageName   */

        } catch (RemoteException e) {

            Log.e(TAG, "Dead object in registerRemoteControlClient"+e);

        }

    }



    /**

     * Unregisters the remote control client that was providing information to display on the

     * remote controls.

     * @param rcClient The remote control client to unregister.

     * @see #registerRemoteControlClient(RemoteControlClient)

     */

    public void unregisterRemoteControlClient(RemoteControlClient rcClient) {

        if ((rcClient == null) || (rcClient.getRcMediaIntent() == null)) {

            return;

        }

        IAudioService service = getService();

        try {

            service.unregisterRemoteControlClient(rcClient.getRcMediaIntent(), /* mediaIntent   */

                    rcClient.getIRemoteControlClient());                       /* rcClient      */

        } catch (RemoteException e) {

            Log.e(TAG, "Dead object in unregisterRemoteControlClient"+e);

        }

    }



    /**

     * @hide

     * Registers a remote control display that will be sent information by remote control clients.

     * @param rcd

     */

    public void registerRemoteControlDisplay(IRemoteControlDisplay rcd) {

        if (rcd == null) {

            return;

        }

        IAudioService service = getService();

        try {

            service.registerRemoteControlDisplay(rcd);

        } catch (RemoteException e) {

            Log.e(TAG, "Dead object in registerRemoteControlDisplay " + e);

        }

    }



    /**

     * @hide

     * Unregisters a remote control display that was sent information by remote control clients.

     * @param rcd

     */

    public void unregisterRemoteControlDisplay(IRemoteControlDisplay rcd) {

        if (rcd == null) {

            return;

        }

        IAudioService service = getService();

        try {

            service.unregisterRemoteControlDisplay(rcd);

        } catch (RemoteException e) {

            Log.e(TAG, "Dead object in unregisterRemoteControlDisplay " + e);

        }

    }

 



 

你可能感兴趣的:(manager)