안드로이드 알림음 재생 방법
알림음을 미디어 스트림으로 재생하지 않고 재생할 수 있는 방법이 궁금했습니다.지금은 미디어 플레이어를 통해 이 작업을 수행할 수 있지만 미디어 파일로 재생하지 않고 알림, 경고 또는 벨소리로 재생하기를 원합니다.여기 내 코드가 지금 어떤 모습인지 보여주는 예가 있습니다.
MediaPlayer mp = new MediaPlayer();
mp.reset();
mp.setDataSource(notificationsPath+ (String) apptSounds.getSelectedItem());
mp.prepare();
mp.start();
여전히 해결책을 찾고 있는 사람이 있다면 안드로이드에서 벨소리/알람 소리를 재생하는 방법에서 답을 찾았습니다.
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
TYPE_NOTIFY를 TYPE_ALARM으로 변경할 수 있지만, Ringtoner를 계속 추적하여 재생을 중지할 수 있습니다...예를 들어, 사용자가 버튼 같은 것을 클릭할 때.
이제는 별도로 소리를 부르지 않고 알림을 작성할 때 소리를 포함하여 작업할 수 있습니다.
//Define Notification Manager
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(message)
.setSound(soundUri); //This sets the sound to play
//Display notification
notificationManager.notify(0, mBuilder.build());
기본 알림 사운드를 재생하려면 setDefaults(int) 메서드를 사용합니다.NotificationCompat.Builder
클래스:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(R.string.app_name))
.setContentText(someText)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true);
그것이 당신의 임무를 완수하는 가장 쉬운 방법이라고 생각합니다.
시도해 보기:
public void ringtone(){
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
질문하신 지 꽤 됐지만...오디오 스트림 유형을 설정해 보았습니까?
mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
준비하기 전에 반드시 해야 합니다.
Intent intent = new Intent(this, MembersLocation.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("type",type);
intent.putExtra("sender",sender);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri Emergency_sound_uri=Uri.parse("android.resource://"+getPackageName()+"/raw/emergency_sound");
// Uri Default_Sound_uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(type.equals("emergency"))
{
playSound=Emergency_sound_uri;
}
else
{
playSound= Settings.System.DEFAULT_NOTIFICATION_URI;
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(body)
.setSound(playSound, AudioManager.STREAM_NOTIFICATION)
.setAutoCancel(true)
.setColor(getColor(R.color.dark_red))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent);
// notificationBuilder.setOngoing(true);//for Android notification swipe delete disabling...
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
channel.setSound(Emergency_sound_uri, att);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
if (notificationManager != null) {
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
저도 거의 같은 질문을 받았습니다.몇 가지 조사를 해본 결과, 기본 시스템인 "알림음"을 재생하려면 알림을 표시하고 기본음을 사용하라고 말해야 한다고 생각합니다.그리고 일부 다른 답변에서는 알림음을 재생하는 경우에도 알림 메시지를 제시해야 한다는 주장에 대해서도 할 말이 있습니다.
하지만 알림 API를 조금만 조정하면 원하는 것에 근접할 수 있습니다.빈 알림을 표시한 다음 몇 초 후 자동으로 제거할 수 있습니다.저는 이것이 효과가 있을 것이라고 생각합니다. 아마 당신에게도 효과가 있을 것입니다.
나는 여러 가지 편리한 방법들을 만들어 냈습니다.com.globalmentor.android.app.Notifications.java
다음과 같은 알림음을 생성할 수 있습니다.
Notifications.notify(this);
LED도 깜박이고 진동 허가가 있으면 진동이 발생합니다.예, 알림 표시줄에 알림 아이콘이 나타나지만 몇 초 후에는 사라집니다.
이 시점에서 알림이 사라지기 때문에 알림 표시줄에 스크롤 티커 메시지가 표시될 수 있습니다. 다음과 같이 수행할 수 있습니다.
Notifications.notify(this, 5000, "This text will go away after five seconds.");
이 수업에는 여러 가지 편의 방법이 있습니다.서브버전 저장소에서 라이브러리 전체를 다운로드하여 메이븐과 함께 구축할 수 있습니다.이는 Maven과 함께 구축 및 설치할 수 있는 글로벌 멘토 코어 라이브러리에 따라 다릅니다.
안드로이드 UI에서는 '알림음'이라는 개념이 다소 잘못되었다고 생각합니다.
Android가 예상하는 동작은 표준 알림을 사용하여 사용자에게 경고하는 것입니다.상태 표시줄 아이콘 없이 알림음을 재생하면 사용자가 혼동하게 됩니다("무슨 소리였습니까?").여기 아이콘이 없는데 혹시 청력에 문제가 있는 것은 아닐까요?"라고 말했습니다.
알림에 소리를 설정하는 방법은 예를 들어, 다음과 같습니다. 알림에 소리를 설정하는 방법
Notification and Notification Manager를 사용하여 원하는 알림을 표시할 수 있습니다.그런 다음 알림을 사용하여 재생할 사운드를 사용자 지정할 수 있습니다.
소리를 알림 채널로 설정
Uri alarmUri = Uri.fromFile(new File(<path>));
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
channel.setSound(alarmUri, attributes);
언급URL : https://stackoverflow.com/questions/4441334/how-to-play-an-android-notification-sound
'programing' 카테고리의 다른 글
어떻게 하면 디브를 비례감 있게 이미지로 채울 수 있을까요? (0) | 2023.09.09 |
---|---|
텍스트 파일 MySQL 바인딩 및 식별자 만들기 (0) | 2023.09.09 |
'사용자 'user'@'localhost'에 대한 액세스가 거부되었습니다. (0) | 2023.09.09 |
자바스크립트에서 PHP 배열을 비활성화합니다. (0) | 2023.09.09 |
우체부 ReSTful 웹 서비스에서 여러 파일을 보내는 방법? (0) | 2023.09.09 |