從需求說起吧,產(chǎn)品經(jīng)理/老板說有客戶想要有推送通知到達(dá)的時(shí)候有聲音,為了凸顯公司的特色我們自己定義個(gè)通知聲加進(jìn)去吧。就這么個(gè)需求iOS實(shí)現(xiàn)起來還是挺簡單的,根據(jù)文檔拖一個(gè)符合要求的格式(不要超過30秒)例如叫notif.caf放到項(xiàng)目根目錄,極光推送的時(shí)候把sound字段設(shè)置為notif.caf就行了。
Android的話有幾種辦法,一個(gè)是完全自定義notification的樣式,包括ui+聲音。不過我們一直用默認(rèn)的用得好好的就沒必要折騰了,選擇的方案是ui仍然用原生的,而且后臺發(fā)推送的時(shí)候給android發(fā)送的是無聲的,我們在onReceive()里面自己播放自定義聲音。
于是一查SoundPool就開干了,看api還是很簡單的:新建個(gè)sound pool,load然后加載,代碼自然就出來了:
SoundPool.Builder builder = new SoundPool.Builder();
builder.setMaxStreams(1);
AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
attrBuilder.setLegacyStreamType(AudioManager.STREAM_ALARM);
builder.setAudioAttributes(attrBuilder.build());
SoundPool soundPool = builder.build();
新建一個(gè),為了保證能播放成功最好在load成功的回調(diào)里邊播放,結(jié)果as的自動補(bǔ)全給了一段這樣的代碼:
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int i, int i1) {
}
});
嗯?i, i1什么玩意兒(論參數(shù)命名的重要性……),肯定是狀態(tài)什么的不管了。然后在里邊play,play函數(shù)的簽名如下:
play(int, float, float, int, int, float))(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)
于是就這么掉坑里了:
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int i, int i1) {
soundPool.play(R.raw.bird, 0.99f, 0.99f, 0, 0, 1);
}
});
soundID嘛,那個(gè)res id也是id,放進(jìn)來非常合理,于是編譯-通過,運(yùn)行-通過,測試 - 沒聲音。。。換了幾個(gè)android版本的測試機(jī)還是這樣,只能狗哥家搜了下發(fā)現(xiàn)是這么弄的:
SoundPool.Builder builder = new SoundPool.Builder();
builder.setMaxStreams(1);
AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
attrBuilder.setLegacyStreamType(AudioManager.STREAM_ALARM);
builder.setAudioAttributes(attrBuilder.build());
SoundPool soundPool = builder.build();
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
if (status == 0) {
soundPool.play(sampleId, 0.99f, 0.99f, 0, 0, 1);
}
}
});
soundPool.load(context, R.raw.bird, 0);
那兩個(gè)as自作聰明給我補(bǔ)全的參數(shù)原名是sampleId和status,呵呵呵呵。
還好只浪費(fèi)了半個(gè)小時(shí)……