🙂 İNSANLARIN EN HAYIRLISI INSANLARA FAYDALI OLANDIR 🙂

Ramazan HABER / Android Yeni / Firebase Cloud Messaging Değer Göndermek ve Almak

Firebase Cloud Messaging Değer Göndermek ve Almak

----------------------------------------------DEĞER GÖNDERMEK İÇİN------------------------------------------------------

1-) Android Yeni - build.gradle(Module: app)

 

dependencies {
 ...  

    // pojo retrofit
    
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    
androidTestImplementation 'junit:junit:4.12'

...
}

 

2-) ServiceGenerator.java

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ServiceGenerator {
    
public static String baseUrl= "https://fcm.googleapis.com/" ; // baseaddress
    
public  static Retrofit retrofit;
    
private static Retrofit.Builder builder= new Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create());
    
private  static OkHttpClient.Builder httpClient=new OkHttpClient().newBuilder();
    
public  static <S> S createService (Class<S> serviceClass){
        
builder.client(httpClient.build());
        
retrofit=builder.build();
        
return  retrofit.create(serviceClass);
    }
}

3-) DataDeger.java

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class DataDeger {
    
@SerializedName("click_action")
    
@Expose
    
private String clickAction;
    
@SerializedName("departman")
    
@Expose
    
private String departman;
    
public String getClickAction() {
        
return clickAction;
    }
    
public void setClickAction(String clickAction) {
        
this.clickAction = clickAction;
    }
    
public String getDepartman() {
        
return departman;
    }
    
public void setDepartman(String departman) {
        
this.departman = departman;
    }
}

4-) NotificationDeger.java

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class NotificationDeger { // com.example.user.rmospersonel_TARGET_NOTIFICATION
    
@SerializedName("body")
    
@Expose
    
private String body;
    
@SerializedName("title")
    
@Expose
    
private String title;
    
@SerializedName("sound")
    
@Expose
    
private String sound;
    
public String getBody() {
        
return body;
    }
    
public void setBody(String body) {
        
this.body = body;
    }
    
public String getTitle() {
        
return title;
    }
    
public void setTitle(String title) {
        
this.title = title;
    }
    
public String getSound() {
        
return sound;
    }
    
public void setSound(String sound) {
        
this.sound = sound;
    }
}

5-) NotificationRoot.java

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class NotificationRoot {
    
@SerializedName("to")
    
@Expose
    
private String to;
    
@SerializedName("notification")
    
@Expose
    
private NotificationDeger notification;
    
@SerializedName("data")
    
@Expose
    
private DataDeger data;
    
public String getTo() {
        
return to;
    }
    
public void setTo(String to) {
        
this.to = to;
    }
    
public NotificationDeger getNotification() {
        
return notification;
    }
    
public void setNotification(NotificationDeger notification) {
        
this.notification = notification;
    }
    
public DataDeger getData() {
        
return data;
    }
    
public void setData(DataDeger data) {
        
this.data = data;
    }
}

6-) interface NotificationService

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;
public interface NotificationService {
    
@Headers({
            
"Accept: application/json",
            
"Content-Type: application/json",
            
"Authorization: key=AAAAHCFereg:APA91bHahxFnsuOcCfSMhyLxsU6N2YOAJVTYd3pVXS1lX80QFQxHrvkzDWg_NEoxcC7axc0X8o39WTyvZX93ZvGWqknJIrZ2lL3Ex3972MW9WPiqMUME6WJez6ufHd3FR6eGAGO3pKjO"
    
})
    
@POST("fcm/send")
    Call<ResponseBody> TokenPost(
@Body NotificationRoot liste);
}

7-) AndroidManifest.xml  : hangi aktivityi açacaksa click_action belirtiyoruz. Notifationa tıklayınca

<uses-permission android:name="android.permission.INTERNET" />
<
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<
uses-permission android:name="android.permission.WAKE_LOCK" />
<
uses-permission android:name="android.permission.VIBRATE" />
<
uses-permission android:name="android.permission.GET_ACCOUNTS" />
<
uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<
uses-permission android:name="android.permission.WRITE_SETTINGS" />
<
permission android:name="com.rmossystems.user.rmospersonel.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<
uses-permission android:name="com.rmossystems.user.rmospersonel.permission.C2D_MESSAGE" />

 

 

<activity>

...

 <intent-filter>
        <
action android:name="com.example.user.rmospersonel_TARGET_NOTIFICATION" />
        <
category android:name="android.intent.category.DEFAULT" />
    </
intent-filter>

...
</
activity>

8-) Veriyi Göndermek için

NotificationRoot notiDeger;
NotificationDeger
child;
DataDeger
dataDeger;

 

btnTokenDenemeGonder.setOnClickListener(new View.OnClickListener() {
    
@Override
    
public void onClick(View v) {
        
        
dataDeger=new DataDeger();
        
dataDeger.setClickAction("com.example.user.rmospersonel_TARGET_NOTIFICATION");
        
dataDeger.setDepartman("teknik");
        
child = new NotificationDeger();
        
child.setBody(txtIcerik.getText() + "");
        
child.setTitle(txtBaslik.getText() + "");
        
child.setSound("noti.mp3");
        
notiDeger = new NotificationRoot();
        
notiDeger.setTo(txtCihazToken.getText() + "");
        
notiDeger.setNotification(child);

        
notiDeger.setData(dataDeger);

        
notificationService = ServiceGenerator.createService(NotificationService.class);
        
pushCall = notificationService.TokenPost(notiDeger);
        
pushCall.enqueue(pushCallback);
    }
});

 

// post token
NotificationService notificationService;
Call<ResponseBody>
pushCall;
public Callback<ResponseBody> pushCallback = new Callback<ResponseBody>() {
    
@Override
    
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        
if (response != null & response.isSuccessful()) {
            Toast.
makeText(TokenDenemeGonder.this, "Başarılı", Toast.LENGTH_SHORT).show();
        }
else {
            Toast.
makeText(TokenDenemeGonder.this, "Yüklenemedi...!" + response.message(), Toast.LENGTH_SHORT).show();
        }
    }

    
@Override
    
public void onFailure(Call<ResponseBody> call, Throwable t) {
        Toast.
makeText(TokenDenemeGonder.this, "Yüklenemediki...!" + t.getMessage(), Toast.LENGTH_SHORT).show();
    }
};

 

 

----------------------------------------------DEĞER ALMAK İÇİN------------------------------------------------------

1-) Android Yeni - AndroidManifest.xml

<application>

...

<service android:name=".R_FCM.MyFirebaseInstanceIDService">
    <
intent-filter>
        <
action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
    </
intent-filter>
</
service>
<
service android:name=".R_FCM.MyFirebaseMessagingService">
    <
intent-filter>
        <
action android:name="com.google.firebase.MESSAGING_EVENT" />
    </
intent-filter>
</
service>

...

</application>

 

2-) build.gradle(Project: ...)

dependencies {

...
    
   classpath 'com.google.gms:google-services:4.3.5'

...
    
}

3-) build.gradle(Module: app)

repositories {
    maven { url
'https://maven.google.com' }
}

 

dependencies {

...

 //FCM İÇİN

    implementation platform('com.google.firebase:firebase-bom:26.4.0')

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

    implementation 'com.google.firebase:firebase-analytics'
    
// Testing dependencies
    
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    
androidTestImplementation 'com.android.support.test:runner:1.0.2'
    
androidTestImplementation 'com.android.support.test:rules:1.0.2'
    
androidTestImplementation 'com.android.support:support-annotations:27.1.1'

 

...

}

apply plugin: 'com.google.gms.google-services'

 

4-)  MyFirebaseInstanceIDService.java

 

import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    
private static final String TAG = "MyFirebaseIIDService";
    
@Override
    
public void onTokenRefresh() {
        String refreshedToken = FirebaseInstanceId.
getInstance().getToken();
        Log.
d(TAG, "Refreshed token: " + refreshedToken);
        sendRegistrationToServer(refreshedToken);
    }
    
private void sendRegistrationToServer(String token) {
    }
}

 

5-) MyFirebaseMessagingService.java

 

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.example.user.rmospersonel.R;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    
private static final String TAG = "MyFirebaseMsgService";
    
public static int notiId = 0;

    
@Override
    
public void onMessageReceived(RemoteMessage remoteMessage) {
        
if (remoteMessage.getData().size() > 0) { // Data mesajı içeriyor mu
            
Log.d(TAG, "Mesaj data içeriği: " + remoteMessage.getData());
        }
        
if (remoteMessage.getNotification() != null) { //Notification mesajı içeriyor mu
            
Log.d(TAG, "Mesaj Notification Başlığı: " + remoteMessage.getNotification().getTitle() + " " + "Mesaj Notification İçeriği: " + remoteMessage.getNotification().getBody());
            String departman =
"teknik";
            
if (remoteMessage.getData().get("departman") != null) {
                departman = remoteMessage.getData().get(
"departman").toString();
            }
            sendNotification(
                    remoteMessage.getNotification().getTitle(),
                    remoteMessage.getNotification().getBody(),
                    remoteMessage.getNotification().getClickAction(),
                    departman, remoteMessage.getNotification().getSound());
        }
    }
    
private void sendNotification(String messageTitle, String messageBody, String click_action, String departman, String sound) {
        
try {
            
notiId++;
            Intent intent =
new Intent(click_action);
            SharedPreferences.Editor editor = getSharedPreferences(
"ariza", MODE_PRIVATE).edit();
            editor.putString(
"ariza", "ariza");
            editor.apply();
            intent.putExtra(
"departman", departman);
            PendingIntent pendingIntent = PendingIntent.
getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.Builder builder =
new NotificationCompat.Builder(this);
            builder.setContentTitle(messageTitle);
            builder.setChannelId(
"ChannelId");
            builder.setContentText(messageBody);
            builder.setLights(Color.
RED, 3000, 3000);
            builder.setAutoCancel(
true);
            builder.setVibrate(
new long[]{1000, 1000});
            Uri alarmSound = Uri.
parse(sound);
            builder.setSound(alarmSound);
            builder.setSmallIcon(R.drawable.
a);
            builder.setContentIntent(pendingIntent);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.
NOTIFICATION_SERVICE);
            
if (Build.VERSION.SDK_INT > 25) {
                NotificationChannel channel =
new NotificationChannel("ChannelId",
                        
"Rmos Bildirimler",
                        NotificationManager.
IMPORTANCE_DEFAULT);
                channel.setDescription(
"Rmos Bildirimler");
                channel.enableVibration(
true);
                channel.enableLights(
true);
                notificationManager.createNotificationChannel(channel);
            }
            notificationManager.notify(
notiId, builder.build());
        }
catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

----------------------------------------------TOKEN ALMAK İÇİN------------------------------------------------------

     public void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

 

 

FirebaseMessaging.getInstance().getToken()

                .addOnCompleteListener(new OnCompleteListener<String>() {

                    @Override

                    public void onComplete(@NonNull Task<String> task) {

                        if (!task.isSuccessful()) {

                            Log.w("token22", "Fetching FCM registration token failed", task.getException());

                            return;

                        }

 

                        String token = task.getResult();

 

                        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

                        ClipData clip = ClipData.newPlainText("label", token);

                        clipboard.setPrimaryClip(clip);

 

 

                        Toast.makeText(getApplicationContext(), token, Toast.LENGTH_SHORT).show();

                    }

                });

} 

----------------------------------------------POSTMAN DEĞER GÖNDERMEK İÇİN------------------------------------------------------

HEADERS KISMINA ->

 

1-) Android Yeni - Authorization YAZ VE KARŞISINA AŞAĞIDAKİNİ YAZ

 

 key=AAAAx3B8Zl0:APA91bHBcl0VAvMmtp15DRelocfRNHPgBVjrgc7_kcfpexSvTcUhDEAIxxPnJm9PJsCWlPx738-wlQNrWWQjs2rIqBpDyLakSvs_ji_xyNSw9P-x2o9nwpJOjnabnPiwxoC-DWaD1cZF

 

2-) Content-Type YAZ VE KARŞISINA AŞAĞIDAKİNİ YAZ

 

application/json

 

BODY KISMINA -> raw -> JSON(aplication/json) -> seçtikten sonra

 

3-) AŞAĞIDAKİ ADRESE POST YAP ->

 

https://fcm.googleapis.com/fcm/send adresine POST yap aşağıdaki veriyi

 

{

 "to" : "cfD6yZTP1fc:APA91bHJqzDCRQ2cfuWzFfH4HGRRSALa-4HnzTnUZc46s11-av8Mp2-lmn2yTjfhAl5GQFc4twCctiiWJpelYY4ahstFZ8Ui5zawQP8-9Y1gRtAV250AxOXkR7C_LRjeCKNfJq_NEI0E",

  "notification" : {

     "body" : "İÇERİK",

     "title": "BAŞLIK",

     "sound" : "noti.mp3"

 },

 "data" : {

     "click_action" : "MainActivity",

     "departman": "teknik"

     

 }

}

 

 

 

2-) retrofitte timeout süresi ayarlama -> ServiceGenerator.java -> son hali bunu kullan

 

package com.webpos.ramazan.rmos.rmossay.WebServis;
import com.webpos.ramazan.rmos.rmossay.MainActivity;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ServiceGenerator {
    
public static String baseUrl = MainActivity.MyWebServis;
    
public static Retrofit retrofit;
    
private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create());
    
private static OkHttpClient.Builder httpClient = new OkHttpClient().newBuilder();
    
public static <S> S createService(Class<S> serviceClass) {

        
httpClient.connectTimeout(30, TimeUnit.SECONDS);
        
httpClient.readTimeout(30, TimeUnit.SECONDS);
        
httpClient.writeTimeout(30, TimeUnit.SECONDS);

        
builder.client(httpClient.build());
        
retrofit = builder.build();
        
return retrofit.create(serviceClass);
    }
}

 

 

 

 

 2021 Şubat 07 Pazar
 851