Nisa Efendioğlu

Firebase ile Bildirim Gönderme : (Android)

Profile picture

Nisa Efendioğlu

Post Image

Herkese merhabalar 🥳

Bu blog yazısında firebase kullanarak uygulamaya bildirim nasıl gönderilir ondan bahsedeceğim.

Bu işlem için ilk olarak Firebase adresi üzerinden bir hesap oluşturmanız gerekiyor. Kayıt/Giriş işlemleri sonrasında yukarıda bulunan menüden konsola git (Go to Console) seçeneğine tıklıyor ve Add Project seçeneği ile yeni bir proje oluşturuyoruz.

Buraya kadar ki aşamların hepsi firebase üzerinden bir proje oluşturma adımları olduğu için detaylı olarak anlatmadım. 🙂 Gelelim firebase ile push notifications işlemlerimize,

İlk olarak yapılması gereken Firebase Console üzerinden cloud messaging kısımına giriyoruz. Burada hangi platformda push notification entegresi yapılmak isteniyorsa o platform seçilerek devam edilir Biz bu aşamada Android yapacağımız için Android görseli olan ikona tıklamamız gerekmektedir. 🙂

Bu seçim işleminden sonra uygulamamız hakkında bazı bilgiler isteyecek sonrasında ise uygulamamız ile firebase arasında bağlantı sağlayacak olan google-services.json konfigürasyon dosyasını verecektir. Bu dosyayı uygulamanızın dosyasının içinde app paketi altında koymalısınız.

Sync Now demeyi unutmadan devam edelim. 🙂 Sırada bildirim işlemleri 😀

İlk olarak uygulamamızın uygulama modülü dizinindeki project/build.gradle dosyasına aşağıdaki kod parçacığını ekleyerek firebase bildirimleri için gerekli implementasyonu uygulamamıza dahil ediyoruz :

implementation 'com.google.firebase:firebase-messaging'

Ardından AndroidManifest.xml dosyamız içerisine şu satırları dahil edelim. 🙂

<service

android:name=”.MyFirebaseMessagingService”>

<intent-filter>

<action android:name=”com.google.firebase.MESSAGING_EVENT”/>

</intent-filter>

</service>

İşlemlerin çoğu tamam 😀 Şimdi Android Studio üzerinden kendi paketlerimiz içinde bir Kotlin/Java class’ı oluşturup Firebase Messaging Service’i özelleştirerek uygulamamız içerisinde kullanacağız. 🙂

MyFirebaseMessagingService class’ı bir Service class olduğu için (FirebaseMessagingService’den extends ettik çünkü.) kendisi otomatik çalışacaktır ve içindeki onTokenRefresh() methodu uygulama ilk kurulduğunda ve Token oluştuğu zaman otomatik olarak çağırılacak olan methoddur.

onTokenRefresh() methodu ise Token değiştiğinde otomatik olarak çalışır. Burada kullanılan token kullanıcının unique ID’si olmaktadır.

MyFirebaseMessagingService.class :

package com.google.firebase.quickstart.fcm.java;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.google.firebase.quickstart.fcm.R;

import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

/**
 * NOTE: There can only be one service in each app that receives FCM messages. If multiple
 * are declared in the Manifest then the first one will be chosen.
 *
 * In order to make this Java sample functional, you must remove the 
 * following from the Kotlin messaging
 * service in the AndroidManifest.xml:
 *
 * <intent-filter>
 *   <action android:name="com.google.firebase.MESSAGING_EVENT" />
 * </intent-filter>
 */
public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // [START_EXCLUDE]
        // There are two types of messages data messages and notification messages. Data messages
        // are handled
        // here in onMessageReceived whether the app is in the foreground or background. Data
        // messages are the type
        // traditionally used with GCM. Notification messages are only received here in
        // onMessageReceived when the app
        // is in the foreground. When the app is in the background an automatically generated
        // notification is displayed.
        // When the user taps on the notification they are returned to the app. Messages
        // containing both notification
        // and data payloads are treated as notification messages. The Firebase console always
        // sends notification
        // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
        // [END_EXCLUDE]

        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use WorkManager.
                scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }
    // [END receive_message]


    // [START on_new_token]
    /**
     * There are two scenarios when onNewToken is called:
     * 1) When a new token is generated on initial app startup
     * 2) Whenever an existing token is changed
     * Under #2, there are three scenarios when the existing token is changed:
     * A) App is restored to a new device
     * B) User uninstalls/reinstalls the app
     * C) User clears app data
     */
    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // FCM registration token to your app server.
        sendRegistrationToServer(token);
    }
    // [END on_new_token]

    /**
     * Schedule async work using WorkManager.
     */
    private void scheduleJob() {
        // [START dispatch_job]
        OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(MyWorker.class)
                .build();
        WorkManager.getInstance(this).beginWith(work).enqueue();
        // [END dispatch_job]
    }

    /**
     * Handle time allotted to BroadcastReceivers.
     */
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM registration token with any
     * server-side account maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.ic_stat_ic_notification)
                        .setContentTitle(getString(R.string.fcm_message))
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

Bu kısımları kendi isteğinize göre özelleştirirsiniz. 🥳 Ben burada nedenine nasılına değinmedim, çünkü direkt bu şekilde de kullanabilirsiniz. Daha detaylı bakmak ister ve özelleştirmek isterseniz firebase dokumanına bir göz atabilirsiniz. 🙂

Firebase Console üzerinden Push Notification Gönderilmesi :

Firebase üzerinden Push Notification gönderilmesi için öncelikle Firebase Console üzerinden Cloud Messaging sayfasına gidiyoruz. Burada send first message ekranı bizleri karşılıyor. Buraya tıklandığında aşağıdaki gibi bir ekran ile karşılaşmaktayız.

Burada göndermek istediğimiz bildirimi özelleştirerek, gerekli ayarları yaptıktan sonra send butonu ile bildirim gönderme işlemini tamamlıyoruz.

Dilersek direkt olarak uygulama paketine, belli bir topic ismine göre de uygulamaya bildirim gönderebilmekteyiz. Örneğin bir haber uygulamasında kullanıcı yalnızca spor ile ilgili haberlerin bildirimini almak istiyor ise yalnızca spor topic i ile o kullanıcıya bildirim göndeririz. Bunu koda nasıl dökeriz, gelin bakalım 🙂

FirebaseMessaging.getInstance().subscribeToTopic(“spor”);

Abonelikten çıkmak için ise;

FirebaseMessaging.getInstance().unsubscribeFromTopic(“spor”);

Herhangi bir topic olmadan push göndermek istenildiğinde ise;

FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (!task.isSuccessful()) {
Log.w(TAG, "Fetching FCM registration token failed", task.getException());
return;
}                  
  String token = task.getResult();
                    @SuppressLint({"StringFormatInvalid", "LocalSuppress"}) 
                    String msg = getString(R.string.app_name, token);
                    Log.d(TAG, msg);
                    Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
            });

veya direkt olarak FirebaseMessaging.getInstance().getToken() kodu ekleyebiliriz.

gibi gibi basit işlemler 😀

Ve ta ta taamm 🥳

Projenin github linki : https://github.com/nisaefendioglu/Firebase-Cloud-Messaging

Sorularınız olursa yorum kısmından veya bağlantılı hesaplarımdan sorabilirsiniz. Bug’sız günleriniz olsun. 🥳

Go back