Kotlin'de push bildirim göndermek için genellikle Firebase Cloud Messaging (FCM) kullanılır. FCM, kullanıcılara push bildirimleri göndermek için popüler bir çözümdür. Aşağıda, Kotlin'de FCM kullanarak push bildirim göndermek için temel bir örnek bulabilirsiniz.
1. Firebase Projesi Oluşturma ve Android Projesine Entegrasyon
- Firebase Console'a gidin ve yeni bir proje oluşturun.
- Android projenizi Firebase'e ekleyin ve `google-services.json` dosyasını indirip projenizin `app` dizinine yerleştirin.
- `build.gradle` dosyalarınıza Firebase ve FCM bağımlılıklarını ekleyin:
**Proje seviyesindeki `build.gradle` dosyası:**
```gradle
buildscript {
dependencies {
// Firebase için Google Services eklentisi
classpath 'com.google.gms:google-services:4.3.10'
}
}
```
**Uygulama seviyesindeki `build.gradle` dosyası:**
```gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'com.google.gms.google-services'
dependencies {
// Firebase Cloud Messaging bağımlılığı
implementation 'com.google.firebase:firebase-messaging:23.0.0'
implementation platform('com.google.firebase:firebase-bom:29.0.0')
implementation 'com.google.firebase:firebase-analytics-ktx'
}
```
2. FirebaseMessagingService Sınıfı Oluşturma
Push bildirimlerini almak için bir `FirebaseMessagingService` sınıfı oluşturmalısınız. Bu sınıf, bildirimler geldiğinde tetiklenir.
```kotlin
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
// Bildirim geldiğinde bu metod tetiklenir
remoteMessage.notification?.let {
val title = it.title
val body = it.body
// Bildirimi göster
showNotification(title, body)
}
}
private fun showNotification(title: String?, message: String?) {
// Bildirimi göstermek için NotificationManager kullanılır
// Bu kısımda bildirim oluşturma işlemleri yapılır
}
override fun onNewToken(token: String) {
// Yeni bir token alındığında bu metod tetiklenir
// Token'i sunucunuza gönderebilirsiniz
}
}
```
3. AndroidManifest.xml Dosyasına Servis ve İzinleri Ekleme
`AndroidManifest.xml` dosyanıza `FirebaseMessagingService` sınıfını ve gerekli izinleri ekleyin:
```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourapp">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.YourApp">
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
```
4. Push Bildirim Gönderme
Push bildirimleri göndermek için Firebase Console'u kullanabilir veya sunucu tarafında FCM API'sini kullanarak bildirim gönderebilirsiniz. Aşağıda, FCM API'sini kullanarak bildirim göndermek için bir örnek bulabilirsiniz:
```kotlin
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
fun sendPushNotification(token: String, title: String, message: String) {
val mediaType = "application/json; charset=utf-8".toMediaType()
val json = """
{
"to": "$token",
"notification": {
"title": "$title",
"body": "$message"
}
}
""".trimIndent()
val body = json.toRequestBody(mediaType)
val request = Request.Builder()
.url("https://fcm.googleapis.com/fcm/send")
.post(body)
.addHeader("Authorization", "key=YOUR_SERVER_KEY")
.addHeader("Content-Type", "application/json")
.build()
val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// Hata durumunda
}
override fun onResponse(call: Call, response: Response) {
// Başarılı durumda
}
})
}
```
5. Bildirim Gösterme
`showNotification` metodunu doldurarak bildirimi gösterebilirsiniz:
```kotlin
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
private fun showNotification(title: String?, message: String?) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// NotificationChannel oluşturma (Android O ve üzeri için)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
"YOUR_CHANNEL_ID",
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT
)
notificationManager.createNotificationChannel(channel)
}
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val notificationBuilder = NotificationCompat.Builder(this, "YOUR_CHANNEL_ID")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
notificationManager.notify(0, notificationBuilder.build())
}
```
Sonuç
Bu adımları takip ederek Kotlin'de Firebase Cloud Messaging kullanarak push bildirim gönderebilir ve alabilirsiniz. Firebase Console üzerinden veya sunucu tarafında FCM API'sini kullanarak bildirimler gönderebilirsiniz.
Hiç yorum yok:
Yorum Gönder