如何在用户通话时播放通知声音?

时间:2017-10-29 06:03:37

标签: java android notifications

我正在开发一款能够连续检测特定信标的BLE信号的应用程序。如果这些信标的电池即将死亡,信号的内容将会改变。因此,我可以提示用户哪个灯塔将会死亡,他或她可能需要更换电池或为其充电。

我把检测放在了服务中,在一般情况下它完全正常。无论应用程序处于前台还是后台,只要应用程序检测到异常信号,应用程序就会向用户发送振动和声音通知。以下是我的代码中Notification的设置:

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(getResources().getString(R.string.app_name))
       .setContentText(getResources().getString(R.string.app_name))
       .setAutoCancel(true)
       .setSmallIcon(R.mipmap.ic_launcher)
       .setContentIntent(contentIntent)
       .setDefaults(NotificationCompat.DEFAULT_VIBRATE)
       .setSound(sound)
       .setVibrate(new long[]{INTERVAL_VIBRATE, INTERVAL_VIBRATE});

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    builder.setPriority(Notification.PRIORITY_DEFAULT);
    builder.setFullScreenIntent(contentIntent, true);
}

if (!TextUtils.isEmpty(message)) {
    builder.setContentText(message);
}

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());

问题出现了:

当用户正在通话时,他或她将收到通知以及振动。但是无法接收通知声音,我想知道是否有办法完成此功能。

1 个答案:

答案 0 :(得分:0)

我终于找到了另一种解决方案:使用ToneGenerator播放声音。

在这种情况下,当我只使用Notification时,当我在手机上时通知的声音消失了,即使振动仍然有效,我想找到一种提示用户的高级方法他或她需要提防一些事情。

因此,在我的服务中,我添加PhoneStateListener来监控手机状态

    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    PhoneStateListener phoneStateListener = createPhoneStateListener();
    telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

我的createPhoneStateListener()方法:

private PhoneStateListener createPhoneStateListener() {
    return new PhoneStateListener() {

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch(state){
                case TelephonyManager.CALL_STATE_IDLE :
                    isUserSpeakingOnPhone = false;
                    break;
                case TelephonyManager.CALL_STATE_RINGING :
                    isUserSpeakingOnPhone = true;
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK :
                    isUserSpeakingOnPhone = true;
                    break;
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    };
}

我使用布尔 isUserSpeakingOnPhone 来确定我是否需要启动一个名为IntentService的{​​{1}}来生成音调并在我需要推送时同时播放通知:

PlayToneService

PlayToneService.class:

if (isUserSpeakingOnPhone) {
        Intent playTone = new Intent(this, PlayToneService.class);
        startService(playTone);

}

然后,当用户在电话上发言并收到通知时,他/她将听到"哔声"来自设备扬声器的声音。当用户没有通过电话讲话时,通知声音将照常工作。