Customize firebase notification - android

I have an Chat app in which a user is subscribed to an topic and each group is a topic. Whenever an message is sent in the group. An notification is sent to that topic.
There are two problems that I am facing.
When the sender sends the message in the group, a notification message is sent to the topic. But before the user gets the notification from firebase, He closes the application or the app goes in the background. So According to the firebase documentations, the notification is sent to the notification tray and not the onMessageReceived callback.
The notification that is received from the firebase is added to the tray. How can the users other than the sender get the notification Id so that i can be cancelled when it required. How can this notification be customised?
Is there a way to keep an active listener for receiving the notification when the app is in the background or terminated.
Please help

You might wan to take a look this.At first I always have problem reading the doc due to english not my primary language. It very confuse but just follow the step you will get more understading.
For your first question you do not need to use both notification and data message. If you use so it will prevent onMessageReceived() get call if the app is in foreground or force close. Trust me just remove the notification{notification:"data"} but keep {data:"something"} while sending to firebase. It will always trigger onMessageReceived().
For you second question after you follow the step above you won't get any notification display on your status bar. Here you can check wether this user is the sender, if it wasn't the sender then you can just show your custom notification inside onMessageReceived().

You can push notification to your app for user engaging with fire base by sending notification,when your app is closed,on basis of some parameters go to fire base .
Make sure Your Project is Added in Fire base first before doing this at all:otherwise add your project in fire base with package name,fingerprint and google_services.json file in app folder of your project .
Fire base Cloud Messaging
it will push notification to your app, if its closed then it let the user to open the app via notification pressed, and if you wants to show notification to the user to direct to another apps of the same account , when the app will be in use both will happened with this code:
Create you first class MyFirebaseMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String NOTIFICATION_ID_EXTRA = "notificationId";
private static final String IMAGE_URL_EXTRA = "imageUrl";
private static final String ADMIN_CHANNEL_ID ="admin_channel";
private NotificationManager notificationManager;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size()>0){
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse(remoteMessage.getData().get("applink")));
PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(this,
0 /* Request code */, notificationIntent,
PendingIntent.FLAG_ONE_SHOT);
int notificationId = new Random().nextInt(60000);
Bitmap bitmap = getBitmapfromUrl(remoteMessage.getData().get("imageurl"));
Intent likeIntent = new Intent(this,LikeService.class);
likeIntent.putExtra(NOTIFICATION_ID_EXTRA,notificationId);
likeIntent.putExtra(IMAGE_URL_EXTRA,remoteMessage.getData().get("message"));
PendingIntent likePendingIntent = PendingIntent.getService(this,
notificationId+1,likeIntent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
setupChannels();
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
.setLargeIcon(bitmap)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getData().get("title"))
.setStyle(new NotificationCompat.BigPictureStyle()
.setSummaryText(remoteMessage.getData().get("message"))
.bigPicture(bitmap))/*Notification with Image*/
.setContentText(remoteMessage.getData().get("message"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.addAction(R.drawable.icon,
getString(R.string.notification_add_to_cart_button),likePendingIntent)
.setContentIntent(pendingIntent);
notificationManager.notify(notificationId, notificationBuilder.build());
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void setupChannels(){
CharSequence adminChannelName = getString(R.string.notifications_admin_channel_name);
String adminChannelDescription = getString(R.string.notifications_admin_channel_description);
NotificationChannel adminChannel;
adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_LOW);
adminChannel.setDescription(adminChannelDescription);
adminChannel.enableLights(true);
adminChannel.setLightColor(Color.RED);
adminChannel.enableVibration(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(adminChannel);
}
}
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Create another class FirebaseIDService to get instance id service of fire base
public class FirebaseIDService extends FirebaseInstanceIdService {
public static final String FIREBASE_TOKEN = "firebase token";
#Override
public void onTokenRefresh() {
super.onTokenRefresh();
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
preferences.edit().putString(FIREBASE_TOKEN, refreshedToken).apply();
}
Make class Name LikeService
public class LikeService extends Service {
private static final String NOTIFICATION_ID_EXTRA = "notificationId";
private static final String IMAGE_URL_EXTRA = "imageUrl";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
To Support Notification at Oreo with firebase dont forget to create Channels and this channels initialize in your First Launcher Activity.
in oncreate of your project first launcher activity include these channels;
String channelId = "1";
String channel2 = "2";
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId,
"Channel 1", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("This is BNT");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel);
NotificationChannel notificationChannel2 = new NotificationChannel(channel2,
"Channel 2",NotificationManager.IMPORTANCE_MIN);
notificationChannel.setDescription("This is bTV");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel2);
}
Now you have to put your Firebase service class in Mainfest under application tag:
<service android:name=".activities.services.MyFirebaseMessagingService"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
</intent-filter>
</service>
<service android:name=".activities.services.FirebaseIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
Now run your app on your device before push notification with fire base make sure your code is integrated correctly then run app: and go to fire base cloud messaging:
put data as in photo according to your app: when its closed:
if your app is in use then your data written in advance option will show, its data about your promotional app of the same account, don use another account app here,
make sure your key should be like in above class as onMessagede Recieved in MyFirebaseMessagingService class
like
title ,message,applink,imageurl

Related

Firebase Cloud Messaging: Test Message Coming But real Published Message not come

I am using FireBase Cloud Messaging. When I published Message from Console Message coming and Notification Shown. Everything was ok. But, When I used To Come Test Message from the console, It also coming with the help of new token. But, After that When I publish real message (not Test), now the published message not come, only coming the test message. So is there any problem in my codes?
My codes as follows :
public class FirebaseCloudNotification extends FirebaseMessagingService {
#Override
public void onNewToken(#NonNull String s) {
super.onNewToken(s);
}
private static final String TAG = "FirebaseMessaging";
private static final String CHANNEL_ID = "com.alquran.tafhimul_quran.FireBaseChannelId";
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if(remoteMessage.getNotification()!=null)
if( remoteMessage.getNotification().getTitle()!=null&& remoteMessage.getNotification().getBody()!=null)
showNotificationCompat(this, _StartActivitySuraList.class,remoteMessage.getNotification().getClickAction() , remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(), 555 );
}
public void showNotificationCompat(final Context context, Class<?> cls,String clickAction, String title, String content, final int REQUEST_CODE)
{
Intent intent = new Intent(context, cls);
String t =title+"#"+content;
intent.putExtra("fireBaseNotification", t);
intent.setAction("From.Firebase.Notification");
intent.setData((Uri.parse("####://"+t)));
PendingIntent pendingIntent = PendingIntent.getActivity(context, new Random().nextInt() /* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);
String channelId = CHANNEL_ID;
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.inapp4)
.setContentTitle(title)
.setContentText(content)
.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_HIGH);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(3 /* ID of notification */, notificationBuilder.build());
}
From Firebase Cloud Messaging Console I have to remove all test token, (as it is it removed my test device). Then Everything is fine.
For removing all test token you have to click on Test Message (blue ) Button.

What "channelId" should I pass to the constructor of NotificationCompat.Builder?

I am trying to write a simple notification application. All it does is notify a notication whenever the button is clicked.
I write my app step by step according to this tutorial.
I don't understand what channel id I should pass to the constructor in order that the app will work. Now the app doesn't do anything (it's not collapses either). I guess that the problem is in the initialization of the variable NotificationCompat.Builder notifyBuilder. I didn't know what to pass so I just passed an arbitary string "0".
My questions are what should I pass to the constructor of NotificationCompat.Builder and will it make the app to work?
Here's the MainActivity:
public class MainActivity extends AppCompatActivity {
private Button mNotifyButton;
private static final int NOTIFICATION_ID = 0;
private static final String NOTIFICATION_ID_STRING = "0";
private NotificationManager mNotifyManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNotifyButton = (Button) findViewById(R.id.notificationButton);
}
public void sendNotification(View view) {
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder notifyBuilder
=new NotificationCompat.Builder(this, NOTIFICATION_ID_STRING)
.setContentTitle("You've been notified!")
.setContentText("This is your notification text.")
.setSmallIcon(R.drawable.ic_android);
Notification myNotification = notifyBuilder.build();
mNotifyManager.notify(NOTIFICATION_ID, myNotification);
}
}
private static final int NOTIFICATION_ID = 0;
This one identifies your notification. If you send multiple notifications with the same ID, the old notification will be replaced by the newer one. So, if want to display several notifications at once, you need multiple IDs.
private static final String NOTIFICATION_ID_STRING = "0";
This one is the ID of the channel. It tells which channel should be used to send that notification. You can assign any String. You just need to ensure that you use the same String for a specific channel. And if you want to create more channels, you need to use a different String for them.
About channel
In recent versions of Android (Android Oreo onwards), you can have different channels to send Notifications. This way, you allow your user to customize which notification he wants to receive.
For example, you have a shopping app. Then, you can have some channels such as:
My Orders (to notify about the orders)
Promotions (to notify about promotions.. this one, the user will probably want to disable).
Miscellaneous (to any other type of notification).
Before sending a notification on that channel, you should create it:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Orders Notification";
String description = "Notifications about my order";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_ID_STRING, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
Then, you can send notifications via:
NotificationCompat.Builder notifyBuilder
= new NotificationCompat.Builder(this, name.toString())
You can check all channes an app have via:
Settings -> Apps -> App you want to check -> Notifications
Some apps have just one channel. Other apps may have more than one channel.
Returning to your question
So, returning to you example, NOTIFICATION_ID_STRING can be any string. You just need to use "0" everytime you want to send a message on that specific channel.
And, if you create a new channel, use a new string "channel1", for example.
However, you must create a channel before sending a notification on it:
// This ID can be the value you want.
private static final int NOTIFICATION_ID = 0;
// This ID can be the value you want.
private static final String NOTIFICATION_ID_STRING = "My Notifications";
public void sendNotification(View view) {
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//Create the channel. Android will automatically check if the channel already exists
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_ID_STRING, "My Channel Name", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("My notification channel description");
mNotifyManager.createNotificationChannel(channel);
}
NotificationCompat.Builder notifyBuilder
= new NotificationCompat.Builder(this, NOTIFICATION_ID_STRING)
.setContentTitle("You've been notified!")
.setContentText("This is your notification text.")
.setSmallIcon(R.drawable.ic_android);
Notification myNotification = notifyBuilder.build();
mNotifyManager.notify(NOTIFICATION_ID, myNotification);
}
You can find more information about them HERE

android Notification - how to not show in foreground

hey all i got a tough problem and need advice. I have constructed a notification manually after recieving a FCM data payload. This is how the notification gets created both in foreground and background since its a data payload:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
String msg = remoteMessage.getData().get("message");
sendNotification(msg);
}
private PendingIntent createIntent(String msg) {
Intent intent = new Intent(this, SportsActivity.class);
Bundle b = new Bundle();
b.putString(Constants.KEY_GO_TO_TAB, Constants.KEY_DASHBOARD_HOCKEY_SCORE_TAB);
intent.putExtras(b);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
return pendingIntent;
}
private void sendNotification( String messageBody) {
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
android.support.v4.app.NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(messageBody))
.setContentText(messageBody)
.setColor(ContextCompat.getColor(this, R.color.hockey_brand))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(createIntent(messageBody));
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
it seems to function fine. The issue im having is i want the notification to NOT SHOW in when the app is in the foreground. is there not a way to do this without scanning the activity task ? as this requires a permission
i've read this article but this how to know you've went from foreground to background. also android.permission.GET_TASKS is deprecated and REAL_GET_TASKS permission is not for third party either. I simply want to know at any given time that the user is either in foreground or background so i know if i should show a notification or not. I wonder if firebase itself has something. When you send a "Notification payload" from the firebase console if the app is not in the foreground is does not show in the notification panel so there should be a way to do this.
Alternatively you can choose not to show your notification when your app is in foreground by implementing Application.ActivityLifecycleCallbacks
in your Application.
Then you can check if your app is in foreground or background.
Source

Update Push Notification Android

I am implementing push notifications on Android. The problem comes when I want to update my notifications. I would like to stack up notifications so that if a notification is visible I simply update it and do this.
mNotifyBuilder.setContentText(currentText)
.setNumber(++numMessages);
But every time I receive a notification ++numMessages is set back to 0 before being summed up. I need it to sum up from where it was left if there is a notification on the screen. Here is the code:
//Class is extending GcmListenerService
public class GCMPushReceiverService extends GcmListenerService {
//variables for message 1,on receiving job applications
String name;
String lastname;
String jobtypename;
String kasualjobdatetimepostedat;
String kasualjobcount;
int numMessages;
//This method will be called on every new message received
#Override
public void onMessageReceived(String from, Bundle data) {
//Getting the message from the bundle
String message = data.getString("message");
String messageid = data.getString("messageid");
if(messageid.compareTo("1")==0){
name=data.getString("firstname");
lastname=data.getString("lastname");
jobtypename=data.getString("jobtype");
kasualjobdatetimepostedat=data.getString("kasualjobdatetimepostedat");
}
else
{
kasualjobcount=data.getString("kasualjobcount");
}
//Displaying a notification with the message
sendNotification(message, messageid);
}
//This method is generating a notification and displaying the notification
private void sendNotification(String message,String messageid) {
Intent intent = new Intent(this, Main_Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
int requestCode = 0;
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Log.d("notificationid", String.valueOf(messageid));
if(messageid.compareTo("2")==0) {//messages to do with jobs around 2
String messageionkasualjobscount="There are "+kasualjobcount+" new jobs around you";
NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this);
noBuilder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("KasualJobs2")
.setContentText(messageionkasualjobscount)
.setAutoCancel(true)
.setContentIntent(pendingIntent).setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(2, noBuilder.build()); //messageid = ID of notification
}else{//messages to with users applying for job 1
String messageionkasualjobapplication=name+ " "+ lastname+" has applied for the "+jobtypename+" you posted on "+kasualjobdatetimepostedat;
NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this);
noBuilder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("KasualJobs1")
.setContentText(messageionkasualjobapplication)
.setAutoCancel(true).setNumber(++numMessages)
.setContentIntent(pendingIntent).setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, noBuilder.build()); //messageid = ID of notification
}
}
}
In general, you should not expect your field values to persist across multiple calls to onMessageReceived, since the service might have been killed by the OS to free up memory.
I suggest storing your messages in a database. Whenever you receive a new message, insert it into the database, and delete it when the user reads it. Then you can easily query how many unread messages there are.
I suggest you to use FCM instead of GCM (because GCM will no longer used).
And to update notifications use sqlite database for storing the notifications with date & time. clear the notification when read & also delete it from database.

how to implement the push notification in android

I am doing lots of Research on push notification but i don't understand how to implement in android 1.6. I want to ask what is the requirements for this? which type of information we get from the server end either in tags form or just information? what will be the input or output regarding this.Which input i give to the server and which output comes from the server.
is there any device id to be require for this? Please suggest me Thanks .
This is the link to documentation given by the Google. They named the concept of PushNotification as C2DM (Cloud To Device Messaging)
You can get a clear description by visiting the given link. I'll give you some short answere for your questions.
You can't implement this in Android 1.6. You need 2.2 or higher
version
As PushNotification, we get only alerts, not the full details message.
As input for the third party server, should have the device registration ID with the C2DM.
Yes, there should be a device id to identify the device to activate the service. You can get it at the initial phase where your Android app try to connect with the C2DM
In Firebase we can push notification with multiple pieces of information to the specific or multiple devices for that we need to implement some code from the android side, first, we need to set up the firebase configuration in your app, I will cover how to redirect push notification to specific or default a screen in the mobile application.
Two ways to open the application screen
By default when you only need to open the application(Like splash screen).
Redirect to the specific screen in the application.
By default when you only need to open the application(Like splash screen)
Create a class Named "FirebaseMessagingService" and extends "FirebaseMessagingService"
Code to implement
public class FirebaseMessagingService extends FirebaseMessagingService
{
#Override
public void onNewToken(String token)
{
sendRegistrationToServer(token);
}
public void onMessageReceived(RemoteMessage remoteMessage)
{
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
Uri imageUrl = remoteMessage.getNotification().getImageUrl();
String actionItem = remoteMessage.getNotification().getClickAction();
if (imageUrl == null)
{
MyNotificationManager.getmInstance(getApplicationContext()).displayNotificationAction(title, body,actionItem);
}
else
{
MyNotificationManager.getmInstance(getApplicationContext()).displayImageNotification(title, body, imageUrl);
}
}
private void sendRegistrationToServer(String token)
{
// TODO: Implement this method to send a token to your app server.
}
}
Create Notification Manager class to manage the display method with different parameters
public class MyNotificationManager
{
private Context mCtx;
private static MyNotificationManager mInstance;
private MyNotificationManager(Context context)
{
createNotificationChannel();
mCtx = context;
}
public static synchronized MyNotificationManager getmInstance(Context context)
{
if (mInstance == null)
{
mInstance = new MyNotificationManager(context);
}
return mInstance;
}
public void createNotificationChannel()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("1", "Testing the Notification", importance);
channel.setDescription("We are testing the notification");
}
}
public void displayNotification(String title, String body)
{
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx, Constant.CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_notification)
.setColor(ContextCompat.getColor(mCtx, R.color.colorPrimary))
.setContentTitle(title)
.setContentText(body);
Intent intent = new Intent(mCtx, SplashActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager != null)
{
mNotificationManager.notify(1, mBuilder.build());
}
}
public void displayImageNotification(String title, String body, Uri imageUrl)
{
NotificationCompat.Builder notification = null;
NotificationManager mNotificationManager = null;
try
{
notification = new NotificationCompat.Builder(mCtx, Constant.CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_notification)
.setContentTitle(title)
.setAutoCancel(true)
.setColor(ContextCompat.getColor(mCtx, R.color.colorPrimary))
.setLargeIcon(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? Picasso.with(mCtx).load(imageUrl).get() : Picasso.with(mCtx).load(R.mipmap.ic_notification).get())
.setContentText(body)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(Picasso.with(mCtx).load(imageUrl).get())
.bigLargeIcon(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? Picasso.with(mCtx).load(imageUrl).get() : Picasso.with(mCtx).load(R.mipmap.ic_notification).get()));
Intent intent = new Intent(mCtx, SplashActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
mNotificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager != null)
{
notification.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(1, notification.build());
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}
Now just trigger the notification through Firebase console or send through API like:-
{
"to": "device_token",
"priority": "high",
"notification": {
"body": "Happy Coding",
"title": "All things are difficult before they are easy.",
"image":""
},
"data": {
"image":""
}
}
2.Redirect to the specific screen in the application.
Open the AndroidManifest.xml and in activity tag you need to define ...
....
<activity
android:name=".activity.SpedificActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="SpedificActivityNotification" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
....
now call the API
{
"to": "device_token",
"priority": "high",
"notification": {
"body": "Happy Coding",
"title": "All things are difficult before they are easy.",
"click_action": "SpedificActivityNotification",
"image":""
},
"data": {
"image":""
}
}

Categories

Resources