알림시 진동 및 소리 기본값


93

내 알림이 올 때 기본 진동 및 소리 알림을 받으려고 노력하고 있지만 지금까지는 운이 없습니다. 기본값을 설정하는 방법과 관련이 있다고 생각하지만 어떻게 고칠 지 모르겠습니다. 이견있는 사람?

public void connectedNotify() {
    Integer mId = 0;
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notify)
            .setContentTitle("Device Connected")
            .setContentText("Click to monitor");

    Intent resultIntent = new Intent(this, MainActivity.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =     
          PendingIntent.getActivity(getApplicationContext(), 
          0, 
          resultIntent,  
          PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    mBuilder.setOngoing(true);
    Notification note = mBuilder.build();
    note.defaults |= Notification.DEFAULT_VIBRATE;
    note.defaults |= Notification.DEFAULT_SOUND;
    NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(mId, note);

}

3
모든 답변은 이미 가지고있는 코드의 일부 변형을 반복 할 뿐이며 내 의견으로는 질문에 대한 답변이 없습니다. 코드는 괜찮아 보입니다. AFAICT. 대부분의 경우 android.permission.VIBRATEAndroidManifest.xml에서 누락 되었습니다.
Olaf Dietsche 2016

이 스레드에서 솔루션을 적용 할 수 있고 알림에 여전히 진동이없는 사람에게 먼저 알림 채널의 진동을 활성화해야 할 수 있습니다. 이것을보세요 : stackoverflow.com/a/47646166/8551764
Mostafa Arian Nejad

답변:


203

일부 더미 코드가 도움이 될 수 있습니다.

   private static NotificationCompat.Builder buildNotificationCommon(Context _context, .....) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(_context)
            .setWhen(System.currentTimeMillis()).......;
     //Vibration
        builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });

     //LED
        builder.setLights(Color.RED, 3000, 3000);

     //Ton
        builder.setSound(Uri.parse("uri://sadfasdfasdf.mp3"));

    return builder;
   }

AndroidManifest.xml파일의 진동에 대한 아래 권한 추가

<uses-permission android:name="android.permission.VIBRATE" />

114
+1 vibrate기능은 <uses-permission android:name="android.permission.VIBRATE" />권한이 필요합니다
ashakirov 2014 년

1
경우에 따라 Color.White 대신 0xffffffff와 같은 16 진수 색상 argb 형식을 사용해야합니다. 사용자 장치가 ARGB 매개 변수에 Color (RGB)를 사용할 가능성이 적고 잘못된 색상을 얻을 수 있기 때문입니다. 이것은 나와 함께 일어났습니다.
Beto Caldas 2014 년

55
이제 진동의 지연은 1000ms입니다. 첫 번째를 0으로 설정하면 즉시 꺼집니다. {delay, vibrate, sleep, vibrate, sleep} 패턴입니다.
Tom

11
<uses-permission android:name="android.permission.VIBRATE" />작업 에 추가 할 필요가 없습니다 .
이크발

1
누구나 API 26에서 setSound를 사용하는 방법을 알고 있습니까?
로드리고 Manguinho

61

TeeTracker의 답변에 대한 확장,

기본 알림 소리를 얻으려면 다음과 같이 할 수 있습니다.

NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notify)
            .setContentTitle("Device Connected")
            .setContentText("Click to monitor");

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);

이것은 당신에게 기본 알림 소리를 제공합니다.


35

알림 진동

mBuilder.setVibrate(new long[] { 1000, 1000});

소리

mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);

더 많은 사운드 옵션


2
시 진동 하나의 경우를 포함해야합니다 <uses-permission android:name="android.permission.VIBRATE" />귀하의 AndroidManifest.xml에
아론 야곱

이 진동은 얼마나 걸리나요? 아니면 한 번만 진동합니까?
Zapnologica

13

나에게 잘 작동합니다. 해 볼 수 있습니다.

 protected void displayNotification() {

        Log.i("Start", "notification");

      // Invoking the default notification service //
        NotificationCompat.Builder  mBuilder =
                new NotificationCompat.Builder(this);
        mBuilder.setAutoCancel(true);

        mBuilder.setContentTitle("New Message");
        mBuilder.setContentText("You have "+unMber_unRead_sms +" new message.");
        mBuilder.setTicker("New message from PayMe..");
        mBuilder.setSmallIcon(R.drawable.icon2);

      // Increase notification number every time a new notification arrives //
        mBuilder.setNumber(unMber_unRead_sms);

      // Creates an explicit intent for an Activity in your app //

        Intent resultIntent = new Intent(this, FreesmsLog.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(FreesmsLog.class);

      // Adds the Intent that starts the Activity to the top of the stack //
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);

      //  mBuilder.setOngoing(true);
        Notification note = mBuilder.build();
        note.defaults |= Notification.DEFAULT_VIBRATE;
        note.defaults |= Notification.DEFAULT_SOUND;

        mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      // notificationID allows you to update the notification later on. //
        mNotificationManager.notify(notificationID, mBuilder.build());

    }

10

이것은 시스템의 기본 진동 및 소리를 사용하여 알림을 호출하는 간단한 방법입니다.

private void sendNotification(String message, String tick, String title, boolean sound, boolean vibrate, int iconID) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);
    Notification notification = new Notification();

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);

    if (sound) {
        notification.defaults |= Notification.DEFAULT_SOUND;
    }

    if (vibrate) {
        notification.defaults |= Notification.DEFAULT_VIBRATE;
    }

    notificationBuilder.setDefaults(notification.defaults);
    notificationBuilder.setSmallIcon(iconID)
            .setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setTicker(tick)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

사용하려는 경우 진동 권한을 추가하십시오.

<uses-permission android:name="android.permission.VIBRATE"/>

행운을 빕니다,'.


누군가 전화를 걸 때 진동이 작동하지 않는 이유를 말해 줄 수 있습니까? 또는 우리는 심지어 전화에서 강제 진동 알림 통화에 만들 수 있습니다

그것은 나를 도왔습니다. notificationBuilder.setDefaults (notification.defaults);
Saveen 2017 년

@ user526206, 모르겠어요. 나는 그것을 테스트 한 적이 없습니다. 알림 동작이 없기 때문에 새 질문을 열 수 있습니다.
Maher Abuthraa

7

나는 다음 코드를 사용하고 있으며 잘 작동합니다.

private void sendNotification(String msg) {
    Log.d(TAG, "Preparing to send notification...: " + msg);
    mNotificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("GCM Notification")
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    Log.d(TAG, "Notification sent successfully.");
}

1

Kotlin의 경우 이것을 시도 할 수 있습니다.

var builder = NotificationCompat.Builder(this,CHANNEL_ID)<br/>
     .setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))<br/>
     .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)

1

// 알림 오디오 설정

builder.setDefaults(Notification.DEFAULT_VIBRATE);
//OR 
builder.setDefaults(Notification.DEFAULT_SOUND);

1

SDK 버전 26 이상을 지원하려면 NotificationChanel을 빌드하고 여기에서 진동 패턴과 소리를 설정해야합니다. Kotlin 코드 샘플이 있습니다.

    val vibrationPattern = longArrayOf(500)
    val soundUri = "<your sound uri>"

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager =    
                 getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val attr = AudioAttributes.Builder()
                        .setUsage(AudioAttributes.USAGE_ALARM)
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .build()
            val channelName: CharSequence = Constants.NOTIFICATION_CHANNEL_NAME
            val importance = NotificationManager.IMPORTANCE_HIGH
            val notificationChannel =
                NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID, channelName, importance)
                notificationChannel.enableLights(true)
                notificationChannel.lightColor = Color.RED
                notificationChannel.enableVibration(true)
                notificationChannel.setSound(soundUri, attr)
                notificationChannel.vibrationPattern = vibrationPattern
                notificationManager.createNotificationChannel(notificationChannel)
    }

그리고 이것은 빌더입니다.

 with(NotificationCompat.Builder(applicationContext, Constants.NOTIFICATION_CHANNEL_ID)) {
        setContentTitle("Some title")
        setContentText("Some content")
        setSmallIcon(R.drawable.ic_logo)
        setAutoCancel(true)    
        setVibrate(vibrationPattern)
        setSound(soundUri)
        setDefaults(Notification.DEFAULT_VIBRATE)
        setContentIntent(
            // this is an extension function of context you should build
            // your own pending intent and place it here
            createNotificationPendingIntent(
                Intent(applicationContext, target).apply {
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                }
            )
        )

        return build()
    }

여기에서AudioAttributes 자세한 내용을 읽을 수 있는 권리가 선택 되었는지 확인 하십시오 .

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.