I am making an android app that receives notifications. I can receive the notification when the app is closed or in the background, but I can't receive it when the app is open and even look like it isn't going through onMessageReceived Method. what do I need to add or edit?
Here is the manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="saleh.example.trail">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
<activity
android:name=".Products_List"
android:label="#string/title_activity_products__list"
android:theme="#style/AppTheme.NoActionBar"></activity>
<activity
android:name=".Categories"
android:label="#string/title_activity_categories"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".SignIn"
android:label="#string/title_activity_sign_in"
android:theme="#style/AppTheme.NoActionBar" />
<service android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firbase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/bisc" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
</application >
</manifest>
Also here is MyFirebaseMessagingService code:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("Noti: ", "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
Toast.makeText(this,"message", Toast.LENGTH_LONG).show();
} else {
// Handle message within 10 seconds
Toast.makeText(this,"No message", Toast.LENGTH_LONG).show();//handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
#Override
public void onNewToken(#NonNull String s) {
super.onNewToken(s);
Log.d("Token",s);
}
}
In FCM there are two kinds of message: Notification and Data. But the main difference is that Notifications are displayed in the notification tray, while Datas are not.
You must send data notification and show received message by notification manager.
this code can help you:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// String title = remoteMessage.getNotification().getTitle();
// String message = remoteMessage.getNotification().getBody();
createNotification(remoteMessage);
}
private void createNotification(RemoteMessage messageBody) {
PushModel pushModel=new PushModel() ;
// pushModel = new Gson().fromJson(messageBody,PushModel.class);
try {
pushModel.setBody(messageBody.getData().get("body"));
pushModel.setTitle(messageBody.getData().get("title"));
// pushModel = convertJsonToBaseApiModel(messageBody);
}catch (Exception e){
String s = e.getMessage();
}
Intent intent = new Intent(getApplicationContext(), SplashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent resultIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
AppController.getPreferenceModel().setNotifMessage(pushModel.getBody());
Intent intent1 = new Intent(this, SplashActivity.class);
PendingIntent resultIntents = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_ONE_SHOT);
String channelId = "Dialog";
Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_ansar_logo)
.setContentTitle(pushModel.getTitle())
.setContentText(pushModel.getBody())
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true)
// .addAction(R.drawable.filter_outline, "Hello", resultIntents)
// .addAction(R.drawable.ic_alert, "Call", resultIntent)
.setSound(notificationSoundURI)
.setPriority(Notification.PRIORITY_MAX)
.setWhen(0)
.setContentIntent(resultIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, mNotificationBuilder.build());
}
public static PushModel convertJsonToBaseApiModel(String json) {
String testTitle=json.substring(json.indexOf("title="),json.indexOf(","));
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setLenient()
.create();
Type listType = new TypeToken<PushModel>() {
}.getType();
PushModel pushModel = gson.fromJson(json, listType);
return pushModel;
}
Related
I have added shaA-1 key and sha-256 key also and also have all the dependency test mode is working fine.In the test mode app is on background and without background is working fine.
public class MainActivity extends AppCompatActivity {
EditText etToken;
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etToken = findViewById(R.id.etToken);
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
if (!task.isSuccessful()) {
System.out.println("Fetching FCM registration token failed");
return;
}
// Get new FCM registration token
String token = task.getResult();
// Log and toast
System.out.println(token);
Toast.makeText(MainActivity.this, "Your device registration token is" + token
, Toast.LENGTH_SHORT).show();
etToken.setText(token);
}
});
}
}
Firebase activity
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// ...
System.out.println("From: " + remoteMessage.getFrom());
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
System.out.println("Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
sendNotification(remoteMessage.getFrom(), remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String from, String body) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(MyFirebaseMessagingService.this.getApplicationContext(), from + " -> " + body,Toast.LENGTH_SHORT).show();
}
});
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = "My channel ID";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("My new notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
Here is the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Newpsuh"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
what should I change in this code.In the test mode app is on background and without background is working fine.
it's been weeks since i have this problem. i can already generate the FCM token and subscribe topics.
the problem that i am having is when i click the notification, nothing is happening it is not even going to the application and i still can't get the body and title of the notification. i know that the notification do not have a relationship with the actual application that i have, i already followed the documentation on handling the receive messages but still nothing is happening.
here is the link that i followed. https://firebase.google.com/docs/cloud-messaging/android/receive
Here is the code that i have.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
scheduleJob();
} else {
// Handle message within 10 seconds
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
and here is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.eperformax.eplife">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyFirebaseMessagingService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
i already saw some related question here but nothing solves my problem. i just followed the documentation and still this is happening.
Can anyone help me this is really stressing me out. Any help would be really appreciated.
I have a problem and maybe a lot of people happens, well when I try to start activity defined in showNotification method in MyFireBaseMessagingService Class
Important: I config my aplication with shared preferences, IntroActivity(Splash) is showed just one time
Flow Initial: IntroActivity(Splash) -> MainActivity (In default Fragment Option in Navigation Drawer Menu)
Second Time run Application: MainActivity (In Default Fragment Option in Navigation Drawer Menu)
I show you my code, I'll really appreciate your help because I need fix this problem, if you need more information, just tell me.
Case I (Correct flow)
When I have application in background, the notification is displayed on taskbar, after I click the notification in top bar, the application is open in the specified activity DetailNoticiaEventoActivity with correct information.
Case II (Problem flow)
But when I close the application and finish it, the notification is displayed on taskbar, but when I click it, the application is open in MainActivity, and not showing the activity DetailNoticiaEventoActivity in first instance how I wanted
Case III (Problem flow)
Sometimes even though the application is in the background, the notification redirects me to the MainActivity
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pe.edu.usmp.fiausmp">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!-- SPLASH ACTIVITY -->
<activity
android:name="pe.edu.usmp.fiausmp.Activities.IntroActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- END SPLASH ACTIVITY -->
<!-- MAINACTIVITY WITH NAV DRAWER -->
<activity android:name="pe.edu.usmp.fiausmp.Activities.MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<!-- END MAINACTIVITY WITH NAV DRAWER -->
<!-- ACTIVITY SHOWED BY NOTIFICATION METHOD -->
<activity android:name="pe.edu.usmp.fiausmp.Activities.DetalleNoticiaEventoActivity"
android:theme="#style/AppTheme.NoActionBar"
android:configChanges="orientation|keyboardHidden|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<!-- END ACTIVITY SHOWED BY NOTIFICATION METHOD -->
<!-- FIREBASE CLASS-->
<service android:name="pe.edu.usmp.fiausmp.Listeners.MyFireBaseMessagingService">
<intent-filter>
<action android:name= "com.google.firebase.MESSAGING_EVENT"></action>
</intent-filter>
</service>
<service android:name="pe.edu.usmp.fiausmp.Listeners.MyFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"></action>
</intent-filter>
</service>
<!-- END FIREBASE CLASS-->
</application>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"
/>
</manifest>
MyFireBaseMessagingService - showNotificationMethod()
This is my full class, I start a activity with Intent and set PendindIntent with this one. I use getNotification() for show notification on any device, and I use getData() for custom information like Ticker, BigTextStyle and Sound.
NOTE: The commented lines, reflects the solutions you tested with the opinions and suggestions of this publication
public class MyFireBaseMessagingService extends FirebaseMessagingService{
private static final String TAG = "FIA USMP";
int contador = 0;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage == null){
return;
}
Log.e(TAG, "From: " + remoteMessage.getFrom());
Log.e(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
Log.e(TAG, "Notification Message Data: " + remoteMessage.getData());
if (remoteMessage.getData().size() > 0){
JSONObject json = new JSONObject(remoteMessage.getData());
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(), json);
}
}
//This method is only generating push notification
private void sendNotification(String title, String messageBody, JSONObject json) {
int cod_not_eve = 0;
String cod_mod = "";
String titulo = "";
String resumen = "";
String detalle = "";
try {
cod_not_eve = Integer.parseInt(json.getString("cod_not_eve"));
cod_mod = json.getString("cod_mod");
titulo = json.getString("titulo");
resumen = json.getString("resumen");
detalle = json.getString("detalle");
}catch (JSONException e){
Log.e(TAG, "JSONException: " + e.getMessage());
}catch (Exception e){
Log.e(TAG, "Exception2: " + e.getMessage());
}
Intent intent = new Intent(this, DetalleNoticiaEventoActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("cod_not_eve", cod_not_eve);
intent.putExtra("cod_mod", cod_mod);
//PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
// PendingIntent.FLAG_ONE_SHOT);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
//PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
// PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
//.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher))
.setContentTitle(title)
.setContentText(messageBody)
//.setStyle(new NotificationCompat.BigTextStyle().bigText(detalle))
.setAutoCancel(true)
//.setVibrate(new long[] {0, 1000, 200,1000 })
//.setLights(Color.parseColor("#00BCD4"), 500, 500)
//.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
//.setTicker(titulo);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(contador, notificationBuilder.build());
Log.d("","MyFireBaseMessagingService.sendNotification.contador"+contador);
contador++;
}
}
Intent intent = new Intent(this, DetalleNoticiaEventoActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
I am having an issue with FireBase Cloud Messaging in which I get the Token from the device and send the notification test through the Google Firebase notification console getting notification to the mobile.
But am failing to get notification from AWS SNS ? Please let me know any further information that would be helpful. Thanks.
MyFirebaseMessagingService.java
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "FROM:" + remoteMessage.getFrom());
//check msz contains data
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data: " + remoteMessage.getData());
}
//check msz contains notification
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
Log.d(TAG, "From: " + remoteMessage.getData());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
}
}
////Display notification
private void sendNotification(String body) {
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0/*Request code*/, intent, PendingIntent.FLAG_ONE_SHOT);
//set sound for notification
Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notifiBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("NewProject")
.setContentText(body)
.setAutoCancel(true)
.setSound(notificationSound)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0/*Id of notification*/, notifiBuilder.build());
}
}
**manifest**
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
MyFirebaseInstanceIdService.java
private static final String TAG="MyFirebaseInstanceIdService";
#Override
public void onTokenRefresh() {
//get updated token
String refreshedtoken= FirebaseInstanceId.getInstance().getToken();
Log.d(TAG,"New Token:" + refreshedtoken);
What I've done:
I've done with the notification part, which is displaying multiple notification in notification tray without overriding it.
What I want to achieve:
I want to remove three dots(...) which are displayed after the 7th notification in data payload of notification tray. Just like in the 2nd image there are no continuation dots after 7th notification in WhatsApp. I've done lots of research but didn't found any feasible solution.
Image 1
Image 2
Below is my code:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.fcmdemo">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/icon_btn_volume"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<receiver android:name="NotificationActionReceiver">
<intent-filter>
<action android:name="CONFIRM" />
<action android:name="CANCEL" />
</intent-filter>
</receiver>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/icon_btn_volume" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
</application>
</manifest>
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
public static ArrayList<String> notifications = new ArrayList<>();
private String remoteMSG;
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Log data to Log Cat
Log.e(TAG, "From: " + remoteMessage.getFrom());
Log.e(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
remoteMSG = remoteMessage.getNotification().getBody();
notifications.add(remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody) {
int i;
//onDismiss Intent
Intent intent = new Intent(this, NotificationActionReceiver.class);
PendingIntent broadcastIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0);
//OnClick Listener
startWFApplication().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, startWFApplication(),
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon_btn_volume)
.setContentTitle("Title")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationCompat.InboxStyle inboxStyle =
new NotificationCompat.InboxStyle();
// Sets a title for the Inbox in expanded layout
inboxStyle.setBigContentTitle("Title - Notification");
inboxStyle.setSummaryText("You have " + notifications.size() + " Notifications.");
// Moves events into the expanded layout
//notifications.add(messageBody);
for (i = 0; i < notifications.size(); i++) {
inboxStyle.addLine(notifications.get(i));
}
// Moves the expanded layout object into the notification object.
notificationBuilder.setStyle(inboxStyle);
NotificationManager notificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
notificationBuilder.setDeleteIntent(broadcastIntent);
}
public static Intent startWFApplication() {
Intent launchIntent = new Intent();
launchIntent.setComponent(new ComponentName("com.fcmdemo", "com.fcmdemo.MyFirebaseMessagingService"));
return launchIntent;
}
#Override
public void handleIntent(Intent intent) {
super.handleIntent(intent);
Log.e(TAG, "handleIntent" + remoteMSG);
}
}
Finally I found the solution. I've just put the condition before adding it.
for (i = 0; i < notifications.size(); i++) {
if (i <= 6) {
inboxStyle.addLine(notifications.get(i));
inboxStyle.setSummaryText("You have " + notifications.size() + " Notifications.");
} else {
inboxStyle.setSummaryText("You have " + notifications.size() + " Notifications.");
}
}