我正在构建一个通过蓝牙查找丢失手机的ping功能。我需要让手机发出声音,即使它已设置为静音模式,就像闹钟通常工作的方式一样。我认为可以将我的notification
的streamtype
设置为AudioManager.STREAM_ALARM
,但这并没有起作用。只有当手机声音开启时才会发出声音。这是我的设置:
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
builder.setSmallIcon(R.drawable.ic_spenwallet)
.setContentTitle("Ping")
.setContentText("Device is trying to find your phone.")
.setAutoCancel(false)
.setSound(sound, STREAM_ALARM)
.setVibrate(vibratePattern)
.addAction(cancelAction);
如果我尝试:
Notification notification = builder.build();
notification.audioStreamType = AudioManager.STREAM_ALARM;
我在Android Studio中收到了有关audioStreamType已被弃用的警告。这是真的吗?即使静音模式开启,还有其他方法可以使通知
声音响起吗?(最好也有震动)
我通过创建专门的mediaplayer来实现它,但我认为这不应该是必需的。以下是我如何做到的:
MediaPlayer mediaPlayer = new MediaPlayer();
final String packageName = getApplicationContext().getPackageName();
Uri sound = Uri.parse("android.resource://" + packageName + "/" + R.raw.ping_sound);
try {
mediaPlayer.setDataSource(this, sound);
} catch (IOException e) {
e.printStackTrace();
}
final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mediaPlayer.setLooping(false);
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}