How to create the token by using the FCM in android.
//Add the application package name and SHA during add application on FCM console
//Make the FirebaseMessagingService
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
Notification notification;
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) {
// TODO(developer): Handle FCM messages here.
Log.d(TAG, "Data: " + remoteMessage.getData());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Map<String, String> data = remoteMessage.getData();
//, data.get("title")
sendNotification(this,data.get("body"),data.get("imei"));
}
}
//Getting the normal notification here
@RequiresApi(api = Build.VERSION_CODES.O)
private void sendNotification(Context context, String title, String time) {
try {
if (!title.equals("") || title != null) {
int icon = R.mipmap.app_icon;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = getString(R.string.CHANNEL_ID);
int imp=NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(channelId, title, imp);
// mChannel.setDescription(title);
mChannel.setLightColor(Color.CYAN);
mChannel.canShowBadge();
mChannel.setShowBadge(true);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notificationManager.createNotificationChannel(mChannel);
Intent notificationIntent = new Intent(context, "your acctivity name");
notificationIntent.putExtra(Constant.NOTIFICATION_RECEIVED, true);
notificationIntent.putExtra(Constant.TYPE, time);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
/*
Notification.BigPictureStyle notiStyle = new Notification.BigPictureStyle();
notiStyle.setBigContentTitle(title);
notiStyle.setSummaryText(title);
*/
notification = new Notification.Builder(this, "")
.setContentTitle(title)
//.setContentText(title)
.setNumber(5)
.setSmallIcon(icon)
.setAutoCancel(true)
.setChannelId(channelId)
.setVisibility(View.VISIBLE)
.setContentIntent(intent)
.setCategory(Notification.CATEGORY_PROMO)
.setPriority(Notification.PRIORITY_HIGH).build();
// .setStyle(notiStyle).build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(1, notification);
} else {
Intent notificationIntent = new Intent(context, "your acctivity name");
notificationIntent.putExtra(Constant.NOTIFICATION_RECEIVED, true);
notificationIntent.putExtra(Constant.TYPE, time);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
/* NotificationCompat.BigPictureStyle notiStyle = new NotificationCompat.BigPictureStyle();
notiStyle.setBigContentTitle(title);
notiStyle.setSummaryText(title);*/
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle(title)
//.setContentText(title)
.setSmallIcon(icon)
.setContentIntent(intent)
.setCategory(Notification.CATEGORY_PROMO)
.setPriority(Notification.PRIORITY_HIGH)
.setVisibility(View.VISIBLE).build();
//.setStyle(notiStyle).build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(0, notification);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
@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
// Instance ID token to your app server.
sendRegistrationToServer(token);
}
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* @param token The new token.
*/
private void sendRegistrationToServer(String token) {
Log.i(TAG, "sendRegistrationToServer: "+token);
}
}
//Add this method on main activity for getting token in android
private void getToken() {
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w("", "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
mToken = task.getResult().getToken();
}
});
}
//Add the fcm lib in app gradle.
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-iid:17.1.1'
implementation 'com.google.firebase:firebase-messaging:17.5.0'
//Add the some line in manifest file.
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/app_logo" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />
<!-- [END fcm_default_icon] -->
<!-- [START fcm_default_channel] -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
<!-- [END fcm_default_channel] -->
<service
android:name=".fcm.FirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
//Add the application package name and SHA during add application on FCM console
//Make the FirebaseMessagingService
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
Notification notification;
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) {
// TODO(developer): Handle FCM messages here.
Log.d(TAG, "Data: " + remoteMessage.getData());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Map<String, String> data = remoteMessage.getData();
//, data.get("title")
sendNotification(this,data.get("body"),data.get("imei"));
}
}
//Getting the normal notification here
@RequiresApi(api = Build.VERSION_CODES.O)
private void sendNotification(Context context, String title, String time) {
try {
if (!title.equals("") || title != null) {
int icon = R.mipmap.app_icon;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = getString(R.string.CHANNEL_ID);
int imp=NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(channelId, title, imp);
// mChannel.setDescription(title);
mChannel.setLightColor(Color.CYAN);
mChannel.canShowBadge();
mChannel.setShowBadge(true);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notificationManager.createNotificationChannel(mChannel);
Intent notificationIntent = new Intent(context, "your acctivity name");
notificationIntent.putExtra(Constant.NOTIFICATION_RECEIVED, true);
notificationIntent.putExtra(Constant.TYPE, time);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
/*
Notification.BigPictureStyle notiStyle = new Notification.BigPictureStyle();
notiStyle.setBigContentTitle(title);
notiStyle.setSummaryText(title);
*/
notification = new Notification.Builder(this, "")
.setContentTitle(title)
//.setContentText(title)
.setNumber(5)
.setSmallIcon(icon)
.setAutoCancel(true)
.setChannelId(channelId)
.setVisibility(View.VISIBLE)
.setContentIntent(intent)
.setCategory(Notification.CATEGORY_PROMO)
.setPriority(Notification.PRIORITY_HIGH).build();
// .setStyle(notiStyle).build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(1, notification);
} else {
Intent notificationIntent = new Intent(context, "your acctivity name");
notificationIntent.putExtra(Constant.NOTIFICATION_RECEIVED, true);
notificationIntent.putExtra(Constant.TYPE, time);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
/* NotificationCompat.BigPictureStyle notiStyle = new NotificationCompat.BigPictureStyle();
notiStyle.setBigContentTitle(title);
notiStyle.setSummaryText(title);*/
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle(title)
//.setContentText(title)
.setSmallIcon(icon)
.setContentIntent(intent)
.setCategory(Notification.CATEGORY_PROMO)
.setPriority(Notification.PRIORITY_HIGH)
.setVisibility(View.VISIBLE).build();
//.setStyle(notiStyle).build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(0, notification);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
@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
// Instance ID token to your app server.
sendRegistrationToServer(token);
}
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* @param token The new token.
*/
private void sendRegistrationToServer(String token) {
Log.i(TAG, "sendRegistrationToServer: "+token);
}
}
//Add this method on main activity for getting token in android
private void getToken() {
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w("", "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
mToken = task.getResult().getToken();
}
});
}
//Add the fcm lib in app gradle.
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-iid:17.1.1'
implementation 'com.google.firebase:firebase-messaging:17.5.0'
//Add the some line in manifest file.
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/app_logo" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />
<!-- [END fcm_default_icon] -->
<!-- [START fcm_default_channel] -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
<!-- [END fcm_default_channel] -->
<service
android:name=".fcm.FirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
No comments:
Post a Comment