Created
March 24, 2024 20:33
-
-
Save mustafayigitt/c5bb935c2c7a4ece15e7fb1dada74add to your computer and use it in GitHub Desktop.
basic notification
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ytapps.myapplication | |
import android.Manifest | |
import android.app.Notification | |
import android.app.NotificationChannel | |
import android.app.NotificationManager | |
import android.content.Context | |
import android.content.pm.PackageManager | |
import android.os.Build | |
import android.os.Bundle | |
import androidx.appcompat.app.AppCompatActivity | |
import androidx.core.app.ActivityCompat | |
import androidx.core.app.NotificationCompat | |
import kotlin.random.Random | |
class MainActivity : AppCompatActivity() { | |
val CHANNEL_ID = "ch" | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager | |
createNotificationChannel(manager) | |
if (ActivityCompat.checkSelfPermission( | |
this@MainActivity, | |
Manifest.permission.POST_NOTIFICATIONS | |
) != PackageManager.PERMISSION_GRANTED | |
) { | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { | |
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 100) | |
} | |
} | |
val notifs = listOf(createNotification(), createNotification(), createNotification()) | |
notifs.forEach { | |
manager.notify(Random.nextInt(), it) | |
} | |
} | |
override fun onRequestPermissionsResult( | |
requestCode: Int, | |
permissions: Array<out String>, | |
grantResults: IntArray | |
) { | |
super.onRequestPermissionsResult(requestCode, permissions, grantResults) | |
if (requestCode == 100 && grantResults.first() == PackageManager.PERMISSION_GRANTED) { | |
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager | |
val notifs = listOf(createNotification(), createNotification(), createNotification()) | |
notifs.forEach { | |
manager.notify(Random.nextInt(), it) | |
} | |
} | |
} | |
private fun createNotificationChannel(manager: NotificationManager) { | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { | |
val channel = NotificationChannel( | |
CHANNEL_ID, | |
"name", | |
NotificationManager.IMPORTANCE_DEFAULT | |
) | |
manager.createNotificationChannel(channel) | |
} | |
} | |
private fun createNotification(): Notification { | |
return NotificationCompat.Builder(this, CHANNEL_ID) | |
.setSmallIcon(R.drawable.ic_launcher_foreground) | |
.setContentTitle("textTitle") | |
.setContentText("textContent") | |
.setPriority(NotificationCompat.PRIORITY_DEFAULT) | |
.build() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment