how to implement the push notification in android - 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":""
}
}

Related

GetActiveNotifications returns null

I have a messenger application and now I'm doing push notifications part. I'm using FCM (Firebase Cloud Messaging)for this. Now I have a problem. For example introduce 2 users (user1 and user2). If user1 writes me, I'm getting notification with FCM and show it. When user2 writes me, I'm creating new notification for it. But when user1 writes me again and I don't removed my user1 notification, I need to update the notification, else create new. I think you understand me. Now I am stuck at update part, because every time I'm create a new notification on message income.
I searched and found something. It says I have to use NotificationListenerService for this and use getActiveNotifications() for getting all active notifications in status bar.
So I tried something, but I'm getting null. I enabled this application in Notification Access, so I think this is not the problem.
I registered my services in manifest file.
Here is my code, where I created my FCM service. If I done something wrong in my code, please fix it.
public class FireBaseService extends FirebaseMessagingService {
private static final String TAG = "FireBaseMessagingServiceTag";
#SuppressLint("LongLogTag")
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Handle FCM messages here.
Intent service = new Intent(FireBaseService.this, NotificationService.class);
startService(service);
//I think I'm doing wrong here.
NotificationService notificationService = new NotificationService();
StatusBarNotification[] activeNotifications = notificationService.getActiveNotifications();
Log.d(TAG, "Array: " + Arrays.toString(activeNotifications));
//show notification
}
}
And here is the NotificationService class.
public class NotificationService extends NotificationListenerService {
#Override
public IBinder onBind(Intent intent) {
return super.onBind(intent);
}
#Override
public void onListenerConnected() {
super.onListenerConnected();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn){
// Implement what you want here
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn){
// Implement what you want here
}
#Override
public StatusBarNotification[] getActiveNotifications() {
return super.getActiveNotifications();
}
}
So this is all I done. Can you help me? Thank you and please fix my code, if I done something wrong instead of giving bad vote to my question.
Here is the notification part.
private void showNotification(String title, String body) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "com.example.fcmnotification.FireBaseService";
if(notificationManager != null) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID, "NotificationManager",
NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setDescription("My Channel");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher_notification)
.setContentTitle(title)
.setContentText(body)
.setContentInfo("info");
notificationManager.notify(new Random().nextInt(), notificationBuilder.build());
}
}
You don't need a NotificationListenerService. Just get the active notifications from the NotificationManager
NotificationManager nm = (NotificationManager)ctx.getSystemService(Activity.NOTIFICATION_SERVICE);
StatusBarNotification[] statusNotifs = null;
try {
statusNotifs = nm.getActiveNotifications();
} catch (Throwable t) {
// it can crash
}
if (statusNotifs != null) for (StatusBarNotification n : statusNotifs) {
Notification notif = n.getNotification();
try {
String ntext = notif.extras.getCharSequence(Notification.EXTRA_TEXT).toString();
// do something
} catch (Throwable t) {
// can crash
}
}

How to automatically open app when receive push notification?

I want to automatically open app when receive push notification.
I've tried but it still does not work as I expected.
This code below is work when the app is active or in MainActivity, but it's not work when the app in the background or just show notification on tray.
Did I miss something?
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getNotification() != null) {
if (PreferencesUtil.getInstance(this).isLoggedIn()) {
sendNotification(remoteMessage.getData().get("order_id"));
}
}
}
public void sendNotification(String messageBody) {
NotificationManager notificationManager = null;
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder;
notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Notification")
.setSmallIcon(R.mipmap.icon_notif)
.setContentText(messageBody)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_LIGHTS );
//add sound
try {
Uri sound = Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.siren);
Ringtone ringtone = RingtoneManager.getRingtone(this, sound);
ringtone.play();
notificationBuilder.setSound(sound);
} catch (Exception e) {
e.printStackTrace();
}
//vibrate
long[] v = {1000, 1000, 1000, 1000, 1000};
notificationBuilder.setVibrate(v);
notificationManager.notify(0, notificationBuilder.build());
Intent i = new Intent(this, NotificationActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
}
This is something need to handle from backend,
Here is a sample payload you are using right now,
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
}
}
Which will only give you control to manipulate and do some action when your app will be in foreground otherwise just raise notification.
In details you can check here.
Now, To always get control over your notification, you need payload like following,
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}
The difference is you need to send data payload instead of notification poayload from backend.
int requestID = (int) System.currentTimeMillis();
Intent notificationIntent = new Intent(getApplicationContext(), NotificationActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, requestID,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
And add PendingIntent like this
notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Notification")
.setSmallIcon(R.mipmap.icon_notif)
.setContentText(messageBody)
.setContentIntent(contentIntent);
.setPriority(NotificationCompat.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_LIGHTS );
Firstly, the concept of "application" in Android is slightly an extended one.
An application - technically a process - can have multiple activities, services, content providers and/or broadcast listeners. If at least one of them is running, the application is up and running (the process).
So, what you have to identify is how do you want to "start the application".
Ok... here's what you can try out:
Create an intent with action=MAIN and category=LAUNCHER
Get the PackageManager from the current context using context.getPackageManager
packageManager.queryIntentActivity(<intent>, 0) where intent has category=LAUNCHER, action=MAIN or packageManager.resolveActivity(<intent>, 0) to get the first activity with main/launcher
Get the ActivityInfo you're interested in
From the ActivityInfo, get the packageName and name
Finally, create another intent with with category=LAUNCHER, action=MAIN, componentName = new ComponentName(packageName, name) and setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
Finally, context.startActivity(newIntent)
I give complete example of this type of situation. Where i'll send a msg to a number (whether my app is completely killed or is in background or is in foreground ) according to received data payload
{
"registration_ids":["cMcyU3CaSlCkjPh8C0qo-n:APA91bFwOhNAwYp5vEEztv_yD_vo1fWt7TsiKZQ8ZvIWx8CUKZa8CNVLAalxmV0FK-zwYgZnwdAnnVaHjUHYpqC89raTLXxAfUWc2wZu94QWCnv14zW4b_DwDUMBpDo3ybP3qf5Y5KM2"],
"data": {
"number": "6299018534",
"msg": "Hii i am sidharth"
}
}
When you send this type data notification from your server then this will receive in onMessageReceived whether your app is in background or foreground.
So, Android code looks like this:
public class NotificationServices extends FirebaseMessagingService {
#Override
public void onMessageReceived(#NonNull RemoteMessage message) {
super.onMessageReceived(message);
if(message.getData().size()>0){
String number = null,msg = null;
if(message.getData().get("number") !=null){
number= message.getData().get("number");
}
if(message.getData().get("msg") !=null){
msg= message.getData().get("msg");
}
sendSms(number,msg);
}
}
#Override
public void onNewToken(#NonNull String token) {
super.onNewToken(token);
}
private void sendSms(String phone,String sms){
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phone,null,sms,null,null);
}
}
Happy coding :)

How to send Notification from FirebaseMessagingService in Android

There are lot of questions already available on SO about this topic and I am not saying that I am doing something unique.
In my FirebaseMessagingService, I am sending Broadcast to show Notification when data message is received.
Here is my code:
public class MessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Message data payload: " + remoteMessage.getData());
String topic = remoteMessage.getData().get(AppConstants.Notification.TOPIC);
if(topic != null) {
switch (topic) {
case FirebaseUtils.TopicMessaging.TOPIC_TASK:
String assignedTo = remoteMessage.getData().get(AppConstants.Notification.ASSIGNED_TO);
//String empId = remoteMessage.getData().get(AppConstants.Notification.EMP_ID);
//String assignedBy = remoteMessage.getData().get(AppConstants.Notification.ASSIGNED_BY);
String title = remoteMessage.getData().get(AppConstants.Notification.TITLE);
String body = remoteMessage.getData().get(AppConstants.Notification.BODY);
if (assignedTo.equals(FotApplication.Employee.Id)) {
//sendNotification(body, title);
Intent intent = new Intent("MY_INTENT_FILTER");
intent.putExtra(AppConstants.Notification.ASSIGNED_TO, assignedTo);
intent.putExtra(AppConstants.Notification.TITLE, title);
intent.putExtra(AppConstants.Notification.BODY, body);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
}
break;
}
}
}
In AndroidManifest.xml
<receiver
android:name=".NotificationReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="MY_INTENT_FILTER"/>
</intent-filter>
</receiver>
NotificationReceiver
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent != null){
String body = null, title = null;
if(intent.hasExtra(AppConstants.Notification.BODY)){
body = intent.getStringExtra(AppConstants.Notification.BODY);
}
if(intent.hasExtra(AppConstants.Notification.TITLE)){
title = intent.getStringExtra(AppConstants.Notification.TITLE);
}
if(body != null && title != null) {
sendNotification(context, body, title);
}
}
}
private void sendNotification(Context context, String message, String title) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
NotificationChannel channel;
if (Build.VERSION.SDK_INT >= 26) {
channel = new NotificationChannel("default",
"Task",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Task Channel");
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, "default")
.setSmallIcon(R.drawable.ic_notification_new)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setVibrate(new long[]{0, 500})
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
notificationManager.notify(0, notificationBuilder.build());
}
}
}
NOTE I have tried everything from sending notification from FCM Json to receive it in FirebaseMessagingService but when App is closed (closed mean neither in Foreground nor Background) then notifications did not show up. Though data message is delivered to System tray.
The last thing I am trying to do is sending Broadcast but that's not working as well. Might be my bad. I have gone through several links and implemented every solution but that Notification thing haven't shown up anywhere. Don't know how big giants (WhatsApp, Facebook, Microsoft, Google) are doing it.
How to Send BroadCast from one app to another app
Why is my broadcast receiver not working
Broadcast and Broadcast receiver
FCM Messaging Concept
Firebase cloud messaging notification not received by device
enter link description here
Is there any workaround then let me know!

Customize firebase notification

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

Get Firebase notification when app is in background (with only data-payload using REST client)

I want to receive notification when the app is in background with the data-payload only. I don't want to send any notification parameters like "notification" : {"sound": "default"}
Here is my code to receive the message and build notification.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String URL_KEY = "url";
private static final String TITLE_KEY = "title";
private static final String BODY_KEY = "body";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getNotification() != null) { //Here I made the dumb mistake
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
// Notification Data initialization
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// String notificationTitle = remoteMessage.getNotification().getTitle();
String notificationTitle = remoteMessage.getData().get(TITLE_KEY);
// String notificationBody = remoteMessage.getNotification().getBody();
String notificationBody = remoteMessage.getData().get(BODY_KEY);
String receivedUrl = remoteMessage.getData().get(URL_KEY);
// BuildNotificaiton
Intent internetIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(receivedUrl))
.setComponent(new ComponentName("com.example.suvajit.webview", "com.example.suvajit.webview.MainActivity"))
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
Random generator = new Random();
PendingIntent btn1Intent = PendingIntent.getActivity(this, generator.nextInt(), internetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle(notificationTitle)
.setContentText(notificationBody)
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(defaultSoundUri)
.setAutoCancel(true)
.addAction(R.mipmap.ic_launcher, "Previous", btn1Intent) // #0
.addAction(R.mipmap.ic_launcher, "Pause", null) // #1
.addAction(R.mipmap.ic_launcher, "Next", null) // #2
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
}
This is my manifest:
<service android:name="com.example.suvajit.webview.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name="com.example.suvajit.webview.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
And I'm sending notification using ARC
But when I'm sending only data payload notification is not received even if the app is in foreground.
{ "data": {
"url": "https://www.google.com",
"body" : "This is your message",
"title": "v-comply",
}
"to" : "dOa...hXIWnms"
}
When I'm sending sound or any thing else as notification parameter and the app is in foreground the notification is working as it should but when its in background its showing only my project name , the data part is not received I guess.
{ "data": {
"url": "https://www.google.com",
"body" : "This is your message",
"title": "v-comply",
},
"notification" : {
"sound": "default"
},
"to" : "dOa...hXIWnms"
}
Below there are two screenshots of notification when app in background and in foreground respectively.
How can I make it work to get notifications when my app is in background with only data-payload? Or am I doing something wrong? Someone please give a solution or guide me.
This was a very dumb and silly mistake which I have made. I was only sending data payload , but I was checking remoteMessage.getNotification() != null which means it doesen't run my code if there is nothing in my notification data. The condition should be like this
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getData().size() > 0) {
//Do stuffs to show notification with data payload only
}
}
After all my notification is working as expected.
This is for other users.
If someone wants to have both notification and data payload check separately they can include both conditions like this.
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getData().size() > 0) {
//Do stuffs with data payload only
}
if (remoteMessage.getNotification() != null) {
//Do stuffs with notificaiton data
}
}

Categories

Resources