Skip to content

Instantly share code, notes, and snippets.

@g123k
Created August 22, 2022 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save g123k/4765ead3707cdab28839d4ab94298f8e to your computer and use it in GitHub Desktop.
Save g123k/4765ead3707cdab28839d4ab94298f8e to your computer and use it in GitHub Desktop.
Envoyer des notifications sur Android 13 (android.permission.POST_NOTIFICATIONS)
// Code utilisé dans la vidéo https://youtu.be/qD2v_eESxzw
class MainActivity : AppCompatActivity() {
@SuppressLint("UnsafeOptInUsageError")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.button).setOnClickListener {
askPermission()
}
}
private fun generateNotification() {
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channelId = "devcafe_channel"
createChannel(notificationManager, channelId)
val notification = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Notification")
.setContentText("Bonjour à tout le monde")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build()
notificationManager.notify(System.currentTimeMillis().toInt(), notification)
}
@Suppress("SameParameterValue")
private fun createChannel(
notificationManager: NotificationManager,
channelId: String
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (notificationManager.getNotificationChannel(channelId) == null) {
val channel = NotificationChannel(
channelId,
"Channel DevCafé",
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = "C'est mal de hardcoder"
}
notificationManager.createNotificationChannel(channel)
}
}
}
private fun askPermission() {
when {
ContextCompat.checkSelfPermission(
this, POST_NOTIFICATIONS
) == PackageManager.PERMISSION_GRANTED -> {
// C'est ok :)
generateNotification()
}
ActivityCompat.shouldShowRequestPermissionRationale(
this,
POST_NOTIFICATIONS
) -> {
// Ouvrir les paramètres
startActivity(Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
})
}
else -> {
// The registered ActivityResultCallback gets the result of this request
requestPermissionLauncher.launch(
POST_NOTIFICATIONS
)
}
}
}
private val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
generateNotification()
} else {
// TODO
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment