0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

通知音と振動パターンを変更する

0
Posted at

CoroutineWorker を利用した通知処理で、通知音と振動パターンの変更方法をメモします。

先に音声ファイルを以下の場所に配置してください。

app/src/main/res/raw/notify_sample_sound.wav

通知音設定と振動パターンの変更

通知と振動パターンは NotificationChannel に設定することで変更できます。

val soundUri = Uri.parse(
    "android.resource://${applicationContext.packageName}/${R.raw.notify_sound}"
)

val audioAttributes = AudioAttributes.Builder()
    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
    .build()

val channelId = "sample_v2"
val channel = NotificationChannel(
    channelId,
    "通知",
    NotificationManager.IMPORTANCE_HIGH
).apply {
    setSound(soundUri, audioAttributes) // 通知オンの設定
    enableVibration(true)
    vibrationPattern =  longArrayOf(0, 100, 100, 300)
    // 振動の設定
    // 0ms待機、100ms振動、100ms停止、300ms振動する
}

全体のサンプルコード

class NotifyWorker(
    context: Context,
    workerParams: WorkerParameters
) : CoroutineWorker(context, workerParams) {

    override suspend fun doWork(): Result {

        val channelId = "sample_v2"
        val soundUri = (ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + applicationContext.packageName + "/" + R.raw.notify_sound).toUri()

        val audioAttributes = AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
            .build()

        val channel = NotificationChannel(
            channelId,
            "通知",
            NotificationManager.IMPORTANCE_HIGH
        ).apply {
            setSound(soundUri, audioAttributes)

            enableVibration(true)
            vibrationPattern = longArrayOf (0, 100, 100, 300)
        }

        val manager = applicationContext.getSystemService(
            NotificationManager::class.java
        )

        manager.createNotificationChannel(channel)

        val notification = NotificationCompat.Builder(
            applicationContext,
            channelId
        )
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle("タイトル")
            .setContentText("テスト通知")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .build()

        NotificationManagerCompat
            .from(applicationContext)
            .notify(1, notification)

        return Result.success()
    }
}

ハマりやすいポイント

NotificationChannel は一度作ると設定が保存されます。一度ビルドすると音、振動などはAndroid側に保存され、その後コードを変更しても反映されません。通知処理を変更するたびにchannelIdも合わせて変更しましょう

val channelId = "sample_v2"
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?