Android Notification

https://developer.android.com/guide/topics/ui/notifiers/notifications

Example https://github.com/android/user-interface-samples/tree/main/Notifications

ContextCompat.getSystemService(context, NotificationManager::class.java) as NotificationManage


fun createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val name = Res.channel_name
        val descriptionText = Res.channel_description
        val importance = NotificationManager.IMPORTANCE_DEFAULT
        val channel = NotificationChannel(Res.CHANNEL_ID, name, importance).apply {
            description = descriptionText
        }
        // Register the channel with the system
        val notificationManager: NotificationManager =
            //ContextCompat.getSystemService(context, Context.NOTIFICATION_SERVICE) as NotificationManager
            //Context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            ContextCompat.getSystemService(context, NotificationManager::class.java) as NotificationManager
            notificationManager.createNotificationChannel(channel)

    }
}


fun doNotify(textTitle:String, textContent:String)
{
    var builder = NotificationCompat.Builder(context, Res.CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_stat_name)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

    with(NotificationManagerCompat.from(context)) {
        // notificationId is a unique int for each notification that you must define
        notify(Random.nextInt(), builder.build())
    }
}

通知のボタン操作をboroadcastreceiverで受け取る #

https://developer.android.google.cn/guide/components/broadcasts#context-registered-recievers

manifestに

        <receiver android:name=".Receiver" android:exported="true">
            <intent-filter>
                <action android:name="アプリ.名称.SNOOZE" />
            </intent-filter>
        </receiver>

を追加しておいて、

class Receiver: BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        StringBuilder().apply {
            append("Action: ${intent.action}\n")
            append("URI: ${intent.toUri(Intent.URI_INTENT_SCHEME)}\n")
            toString().also { log ->
                Log.d("Receiver", log)
                //Toast.makeText(context, log, Toast.LENGTH_LONG).show()
            }
        }
        Log.d("Receiver", "Received")
    }
}

これが通常のActivittyとは異なるエントリーポイントになる。

Broadcastで受けたときにActivityを起動させる #

class Receiver: BroadcastReceiver() {
   override fun onReceive(context: Context, intent: Intent) {
       StringBuilder().apply {
           append("Action: ${intent.action}\n")
           append("URI: ${intent.toUri(Intent.URI_INTENT_SCHEME)}\n")
           toString().also { log ->
               Log.d("Receiver", log)
               //Toast.makeText(context, log, Toast.LENGTH_LONG).show()
           }
       }
       Log.d("Receiver", "Received")

       val i = Intent().also {
           it.setClassName("アプリ.名称", "アプリ.名称.MainActivity")
           it.flags = Intent.FLAG_ACTIVITY_NEW_TASK
           it.action = Res.ACTION_SNOOZE
       }
       context.startActivity(i)
   }
}

ActivityのonCreateで起動原因を調べられる。 #

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (intent != null) {
            intent.action?.let { Log.d("MainActivity", it) }
        }

普通に起動すると、 android.intent.action.MAIN がactionに入っている。

notifyのアクションで

 val resultIntent = Intent(context, Receiver::class.java).apply {
            action = Res.ACTION_SNOOZE
            //putExtra(EXTRA_NOTIFICATION_ID, 0)
        }

などとしておきは、 Res.ACTION_SNOOZEの文字列が actionとして受け取れる。 他にパラメータを入れたいときは putExtraなどで入れられる様子。

通知を消す #

NotificationManagerCompat.from(context).cancelAll()