淺談Android O Notification聲音播放流程

前言

咱們在作Android開發的時候,免不了會使用到Notification,並且在android設備的設置中還能夠設置通知音的優先級,以及播放的聲音種類。那麼通知音是如何播放的呢,今天咱們就來談談這個。android

Notification的使用

NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        //重點:先建立通知渠道
        if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.O){
    NotificationChannel mChannel=new NotificationChannel(getString(R.string.app_name),getString(R.string.app_name),NotificationManager.IMPORTANCE_MAX);
        NotificationChannel channel=new NotificationChannel(channelId,
        channelName,NotificationManager.IMPORTANCE_DEFAULT);
        channel.enableLights(true); //設置開啓指示燈,若是設備有的話
        channel.setLightColor(Color.RED); //設置指示燈顏色
        channel.setShowBadge(true); //設置是否顯示角標
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);//設置是否應在鎖定屏幕上顯示此頻道的通知
        channel.setDescription(channelDescription);//設置渠道描述
        channel.setVibrationPattern(new long[]{100,200,300,400,500,600});//設置震動頻率
        channel.setBypassDnd(true);//設置是否繞過免打擾模式
        notificationManager.createNotificationChannel(mChannel);
        }

        //再建立通知
        NotificationCompat.Builder builder=new NotificationCompat.Builder(this,getString(R.string.app_name));
        //設置通知欄大圖標,上圖中右邊的大圖
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
        // 設置狀態欄和通知欄小圖標
        .setSmallIcon(R.drawable.ic_launcher_background)
        // 設置通知欄應用名稱
        .setTicker("通知欄應用名稱")
        // 設置通知欄顯示時間
        .setWhen(System.currentTimeMillis())
        // 設置通知欄標題
        .setContentTitle("通知欄標題")
        // 設置通知欄內容
        .setContentText("通知欄內")
        // 設置通知欄點擊後是否清除,設置爲true,當點擊此通知欄後,它會自動消失
        .setAutoCancel(false)
        // 將Ongoing設爲true 那麼左滑右滑將不能刪除通知欄
        .setOngoing(true)
        // 設置通知欄點擊意圖
        .setContentIntent(pendingIntent)
        // 鈴聲、閃光、震動均系統默認
        .setDefaults(Notification.DEFAULT_ALL)
        //設置通知時間
         .setWhen(System.currentTimeMillis())
        // 設置爲public後,通知欄將在鎖屏界面顯示
        .setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
        //發送通知
         notificationManager.notify(10, builder.build());

ANdroid O主要增長了NotificationChannel,詳細用法可參照其API。app

正文

那麼就從發送通知的notify開始入手oop

public void notify(String tag, int id, Notification notification)
    {
    //當咱們調用Notification的notify()發送通知時,會繼續調到notifyAsUser
       notifyAsUser(tag, id, notification, new UserHandle(UserHandle.myUserId()));
   }
 public void notifyAsUser(String tag, int id, Notification notification, UserHandle user)
    {
        //獲得NotificationManagerService
        INotificationManager service = getService();

        //…………
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        boolean isLowRam = am.isLowRamDevice();
        final Notification copy = Builder.maybeCloneStrippedForDelivery(notification, isLowRam);
        try {
        //把Nofitication copy到了NofificationManagerservie中
            service.enqueueNotificationWithTag(pkg, mContext.getOpPackageName(), tag, id,
                    copy, user.getIdentifier());
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
       }
}

而enqueueNotificationWithTag()又調用了 enqueueNotificationInternal()
在enqueueNotificationInternal()中須要注意下面這行代碼:post

final NotificationRecord r = new NotificationRecord(getContext(), n, channel);

咱們來看下NotificationRecord的初始化,在NotificationRecoder的構造方法中ui

mAttributes = calculateAttributes();

mAttributes 是否是很熟悉,就是audio播放時須要傳入的那個AudioAttributes,在this

calculateAttributes()中會取咱們在建立channel時傳入的AudioAttributes,若是沒有則使用默認的,若是ANdroid O以前的版本,沒有channel,則會使用Notification中默認的AudioAttributes,(NotificationChannel中的AudioAttributes是經過setSounde()方法設置下來的)。默認的AudioAttributes
是什麼呢?就是線程

//通知中默認的AudioAttributes 
   public static final AudioAttributes AUDIO_ATTRIBUTES_DEFAULT = new AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
            .build();

在enqueueNotificationInternal()中有將notificationRecord放到了EnqueueNotificationRunnable中線程運行代碼以下:code

mHandler.post(new EnqueueNotificationRunnable(userId, r));

而在EnqueueNotificationRunnable線程中又調用的PostNotificationRunnable線程中執行,代碼以下ip

mHandler.post(new PostNotificationRunnable(r.getKey()));

在PostNotificationRunnable中 經過buzzBeepBlinkLocked(r)方法播放開發

if (hasValidSound) {
                        mSoundNotificationKey = key;
                        //若是電話中則playInCallNotification()
                        if (mInCall) {
                            playInCallNotification();                            
                            beep = true;
                        } else {
                        //不然調用playSound(),
                            beep = playSound(record, soundUri);
                        }
                    }

不管哪一個方法方法都是同樣的,只是 AudioAttributes不一樣,playInCallNotification()使用的mInCallNotificationAudioAttributes即

mInCallNotificationAudioAttributes = new AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
                .build();

而playSound()使用的AudioAttributes若是未經過channel傳入,則使用上面提到的默認的,那麼看看究竟是如何播放的呢,通知音的播放是經過

final IRingtonePlayer player = mAudioManager.getRingtonePlayer();

來播放的,代碼略過,簡單說下RingTonePlayer的play()和playerAsync()這倆方法,仍是有點區別的,play使用的Ringtone來播放的,源碼:

client.mRingtone.setLooping(looping);
            client.mRingtone.setVolume(volume);
            client.mRingtone.play();

而playerAsync()是經過NotificationPlayer來播放的,對於NotificationPlayer的play()會經過enqueueLocked()建立CmdThread線程。在CmdThread線程中startSound(),在startSound()中建立CreationAndCompletionThread線程

mCompletionThread = new CreationAndCompletionThread(cmd);
                synchronized (mCompletionThread) {
                  mCompletionThread.start();
                    mCompletionThread.wait();
                }

在CreationAndCompletionThread線程中經過mediaplayer播放

private final class CreationAndCompletionThread extends Thread {
        public Command mCmd;
        public CreationAndCompletionThread(Command cmd) {
            super();
            mCmd = cmd;
        }

        public void run() {
            Looper.prepare();
            // ok to modify mLooper as here we are
            // synchronized on mCompletionHandlingLock due to the Object.wait() in startSound(cmd)
            mLooper = Looper.myLooper();
            if (DEBUG) Log.d(mTag, "in run: new looper " + mLooper);
            synchronized(this) {
                AudioManager audioManager =
                    (AudioManager) mCmd.context.getSystemService(Context.AUDIO_SERVICE);
                try {
                    //饒了一大圈居然也用mediaplayer來播放
                    MediaPlayer player = new MediaPlayer();
                    //attributes 就是從NotificationChannel傳下來的attributes 
                    if (mCmd.attributes == null) {
                        mCmd.attributes = new AudioAttributes.Builder()
                                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                                .build();
                    }
                    player.setAudioAttributes(mCmd.attributes);
                    player.setDataSource(mCmd.context, mCmd.uri);
                    player.setLooping(mCmd.looping);
                    player.setOnCompletionListener(NotificationPlayer.this);
                    player.setOnErrorListener(NotificationPlayer.this);
                    player.prepare();
                    if ((mCmd.uri != null) && (mCmd.uri.getEncodedPath() != null)
                            && (mCmd.uri.getEncodedPath().length() > 0)) {
                        if (!audioManager.isMusicActiveRemotely()) {
                            synchronized (mQueueAudioFocusLock) {
                                if (mAudioManagerWithAudioFocus == null) {
                                    if (DEBUG) Log.d(mTag, "requesting AudioFocus");
                                    int focusGain = AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK;
                                    if (mCmd.looping) {
                                        focusGain = AudioManager.AUDIOFOCUS_GAIN;
                                    }
                                    mNotificationRampTimeMs = audioManager.getFocusRampTimeMs(
                                            focusGain, mCmd.attributes);
                                     //須要注意i,通知音是會申請焦點的。
                                    audioManager.requestAudioFocus(null, mCmd.attributes,
                                                focusGain, 0);
                                    mAudioManagerWithAudioFocus = audioManager;
                                } else {
                                    if (DEBUG) Log.d(mTag, "AudioFocus was previously requested");
                                }
                            }
                        }
                    }
                    // FIXME Having to start a new thread so we can receive completion callbacks
                    //  is wrong, as we kill this thread whenever a new sound is to be played. This
                    //  can lead to AudioFocus being released too early, before the second sound is
                    //  done playing. This class should be modified to use a single thread, on which
                    //  command are issued, and on which it receives the completion callbacks.
                    if (DEBUG)  { Log.d(mTag, "notification will be delayed by "
                            + mNotificationRampTimeMs + "ms"); }
                    try {
                        Thread.sleep(mNotificationRampTimeMs);
                        player.start();
                    } catch (InterruptedException e) {
                        Log.e(mTag, "Exception while sleeping to sync notification playback"
                                + " with ducking", e);
                    }
                    if (DEBUG) { Log.d(mTag, "player.start"); }
                    if (mPlayer != null) {
                        if (DEBUG) { Log.d(mTag, "mPlayer.release"); }
                        mPlayer.release();
                    }
                    mPlayer = player;
                }
                catch (Exception e) {
                    Log.w(mTag, "error loading sound for " + mCmd.uri, e);
                }
                this.notify();
            }
            Looper.loop();
        }
    };

到此over,代碼邏輯很複雜,涉及的類也比較多,有興趣的能夠去看看源碼,我就很少說了。

總結

Notification從建立到播放的流程基本就這樣,至於聲音的區分是否電話中,若是incall則使用RingTone播放,反之mediaplayer播放。
而使用的attributes也區分是否incall。

以上。

相關文章
相關標籤/搜索