Not opening specific activity on notification click when the app is in background/not running
The notification-click starts specified activity only when the app is opened up and the notification-click is performed. If the app is in background/not running and the notification-click is performed, the application's MainActivity opens up. In short, it is like the app opens normally following the activity stack instead of opening the specified activity in the PendingIntent.
Firebase Instance Id Service:
package com.example.tamzid.pushnotification;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class MyAndroidFirebaseInstanceIdService extends
FirebaseInstanceIdService {
private static final String TAG = "MyAndroidFCMIIDService";
#Override
public void onTokenRefresh() {
//Get hold of the registration token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//Log the token
Log.d(TAG, "Refreshed token: " + refreshedToken);
}
private void sendRegistrationToServer(String token) {
//Implement this method if you want to store the token on your server
}
}
Firebase Message Service:
package com.example.tamzid.pushnotification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyAndroidFirebaseMsgService extends FirebaseMessagingService
{
private static final String TAG = "MyAndroidFCMService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Log data to Log Cat
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " +
remoteMessage.getNotification().getBody());
//create notification
createNotification(remoteMessage.getNotification().getBody());
}
private void createNotification( String messageBody) {
Intent intent = new Intent( this , ResultActivity. class );
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent resultIntent = PendingIntent.getActivity( this , 0,
intent,
PendingIntent.FLAG_ONE_SHOT);
Uri notificationSoundURI =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotificationBuilder = new
NotificationCompat.Builder( this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Android Tutorial Point FCM Tutorial")
.setContentText(messageBody)
.setAutoCancel( true )
.setSound(notificationSoundURI)
.setContentIntent(resultIntent);
NotificationManager notificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mNotificationBuilder.build());
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tamzid.pushnotification">
<application
android:name="android.support.multidex.MultiDexApplication"
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>
<activity android:name=".ResultActivity"></activity>
<service android:name=".MyAndroidFirebaseMsgService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".MyAndroidFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"
/>
</intent-filter>
</service>
</application>
</manifest>
Try using remoteMessage.getData() instead of remoteMessage.getNotification()
Use remoteMessage.getNotification(): if message contains a
notification payload.
Use remoteMessage.getData():if message contains
a data payload.
Update onMessageReceived() as below:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0)
{
//create notification
createNotification(remoteMessage.getData().toString());
}
}
Related
I am not receiving push notification for my app. I have included the manifest files, the MainActivity file, the MyFireBaseMessagingService file and the build.gradle file and the googl-services.json. I really am stumped on what the issue could be. I go to Firebase composer to write message but nothing is received. I can hard code values in strings file and I receive a notification but I wanted something more dynamic. That is why I am trying to figure out how to send push notifications from FCM but I seem to be missing something or inputting something incorrectly.
MainAcitivity file
package com.example.testaaedapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import java.net.URI;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageButton logoButton;
private ImageView blueButton, greenButton, orangeButton, yellowButton, redButton, darkBlueButton;
public Button callButton;
private final String CHANNEL_ID = "Alerts";
private final int notificationId = 001;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logoButton = findViewById(R.id.imageButton);
logoButton.setOnClickListener(this);
blueButton = findViewById(R.id.bluepuzzlepiece);
blueButton.setOnClickListener(this);
redButton = findViewById(R.id.redpuzzlepiece);
redButton.setOnClickListener(this);
greenButton = findViewById(R.id.greenpuzzlepiece);
greenButton.setOnClickListener(this);
orangeButton = findViewById(R.id.orangepuzzlepiece);
orangeButton.setOnClickListener(this);
yellowButton = findViewById(R.id.yellowpuzzlepiece);
yellowButton.setOnClickListener(this);
darkBlueButton = findViewById(R.id.darkbluepuzzlepiece);
darkBlueButton.setOnClickListener(this);
callButton = findViewById(R.id.button);
callButton.setOnClickListener(this);
displayNotification();
// Get token
// [START retrieve_current_token]
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
String token = task.getResult().getToken();
// Log and toast
String msg = getString(R.string.msg_token_fmt, token);
Log.d(TAG, msg);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
// [END retrieve_current_token]
}
int requestCode = 0;
public void onClick(View view) {
if (view.getId() == R.id.button && ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
Log.d("STATE", "Call Button DOES NOT WORK");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, requestCode);
return;
} else if (view.getId() == R.id.button && ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
// else if (view.getId() == R.id.button && ActivityCompat.checkSelfPermission(MainActivity.this,
// Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
Log.d("STATE", "Call Button DOES WORK");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:480-240-9255"));
startActivity(callIntent);
} else {
switch (view.getId()) {
case R.id.imageButton:
setContentView(R.layout.activity_main);
break;
case R.id.bluepuzzlepiece:
break;
case R.id.redpuzzlepiece:
Intent blogIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.aaed.org/blog"));
startActivity(blogIntent);
break;
case R.id.greenpuzzlepiece:
Intent videoIntent = new Intent(Intent.ACTION_VIEW);
videoIntent.setData(Uri.parse("https://www.youtube.com/channel/UCUwPShLvnCOTeQILvAtneOw"));
startActivity(videoIntent);
break;
case R.id.yellowpuzzlepiece:
Intent secondActivity = new Intent(this, SecondActivity.class);
startActivity(secondActivity);
break;
case R.id.orangepuzzlepiece:
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.aaed.org"));
startActivity(webIntent);
break;
case R.id.darkbluepuzzlepiece:
Intent schoolIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.aaed.org/online-course-content"));
startActivity(schoolIntent);
}
}
}
public void displayNotification () {
createNotificationChannel();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_puzzlepieces)
.setContentTitle("Test Message")
.setContentText("This is text")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(getString((R.string.another_string))));
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(notificationId, builder.build());
}
public void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
/
/ Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == requestCode)
{
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:480-240-9255"));
startActivity(callIntent);
}
}
MyFirebaseMessagingService file
package com.example.testaaedapp;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import com.example.testaaedapp.MainActivity;
import com.example.testaaedapp.R;
import com.google.firebase.messaging.FirebaseMessagingService;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
// [START on_new_token]
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
#Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(token);
}
// [END on_new_token]
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testaaedapp">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<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=".MapsActivity"
android:label="#string/title_activity_maps"></activity>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="AAED" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_puzzlepieces" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
<activity
android:name=".MainActivity"
android:label="Autism Academy"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:label="Locations"></activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<!-- [START firebase_service] -->
<service
android:name=".MyFirebaseMessagingService"
android:exported="false"
android:enabled="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- [END firebase_service] -->
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
</manifest>
I've had a similar issue. I've tried everything - in my opinion the main reason is that all the services are, sooner or later, being killed by the system. The only way is to make sure to deliver the notification to the system tray not to the application. To do that you need to use Data message notifications.
There are 2 types of FCM notifications: Notification message and Data message.
Data messages are delivered to system tray and are always display - even if service is not running.
Notification message looks like:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
}
}
and triggers method OnMessageReceaved() of FirebaseMessagingService. Many devices (especially Huawei and Xiaomi) try to do everything to kill background services to prevent battery drain. So the FirebaseMessagingService isn't the best way to handle notifications.
Second type is Data message:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}
This type is handled by the system tray, so you don't need any of service running to get the notification. Its much more convenient method, but as far i know, it can't be achieved with the console.
You would probably need server API to send Data message.
Read this for more details.
I send push notification to android phone.
Almost phones are receive and show notification except one phone(Samsung Galaxy Note 5).
The phone shows notification icon and goes at the same time.
You can see this issue followed url (refer 7sec and 22sec):
https://youtu.be/J6UZm_6mqP0
Here is AndroidMenifest.xml of my app
<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">
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_notification" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id" />
<activity
android:name=".MainActivity"
android:configChanges="keyboard|keyboardHidden|orientation|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FCMInstanceService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
Where do i start to solve for this problem?
--More--
MyFirebaseMessagingService.java
package com.smartivt.smartivtmessenger;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.firebase.messaging.RemoteMessage;
import java.util.List;
public class MyFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
private static final String TAG = "FirebaseMessaging";
private final String CHANNEL_ID = "DEFAULT_CHANNEL";
private final String CHANNEL_NAME = "Default Channel";
private final String GROUP_NAME = "MESSAGE_GROUP";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
NotificationManager notiMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if ( remoteMessage.getData().get("title") != null ) {
Log.d(TAG, "onMessageReceived: " + remoteMessage.getData().get("title"));
Log.d(TAG, "onMessageReceived: " + remoteMessage.getData().get("body"));
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {
Notification.Builder notify = new Notification.Builder(getApplicationContext(), CHANNEL_ID);
notify.setSmallIcon(R.drawable.ic_stat_notification);
notify.setContentTitle(remoteMessage.getData().get("title"));
notify.setContentText(remoteMessage.getData().get("body"));
notify.setAutoCancel(true);
notiMgr.notify(NotificationID.getID(), notify.build());
/*
Intent badgeIntent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
badgeIntent.putExtra("badge_count", 5);
badgeIntent.putExtra("badge_count_package_name", getPackageName());
badgeIntent.putExtra("badge_count_class_name", getLauncherClassName());
sendBroadcast(badgeIntent);
*/
Log.d(TAG, "update badge: " + getPackageName() + ", " + getLauncherClassName());
}
else {
Notification.Builder notify = new Notification.Builder(getApplicationContext());
notify.setSmallIcon(R.drawable.ic_stat_notification);
notify.setContentTitle(remoteMessage.getData().get("title"));
notify.setContentText(remoteMessage.getData().get("body"));
notify.setAutoCancel(true);
int id = NotificationID.getID();
Log.d(TAG, "id: " + id);
notiMgr.notify(id, notify.build());
}
}
else if ( remoteMessage.getNotification() != null ) {
Log.d(TAG, "onMessageReceived2: " + remoteMessage.getNotification().getTitle());
Log.d(TAG, "onMessageReceived2: " + remoteMessage.getNotification().getBody());
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {
Notification.Builder notify = new Notification.Builder(getApplicationContext(), CHANNEL_ID);
notify.setSmallIcon(R.drawable.ic_stat_notification);
notify.setContentTitle(remoteMessage.getNotification().getTitle());
notify.setContentText(remoteMessage.getNotification().getBody());
notify.setAutoCancel(true);
notiMgr.notify(NotificationID.getID(), notify.build());
}
else {
Notification.Builder notify = new Notification.Builder(getApplicationContext());
notify.setSmallIcon(R.drawable.ic_stat_notification);
notify.setContentTitle(remoteMessage.getNotification().getTitle());
notify.setContentText(remoteMessage.getNotification().getBody());
notify.setAutoCancel(true);
notiMgr.notify(NotificationID.getID(), notify.build());
}
}
}
#Nullable
private String getLauncherClassName () {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PackageManager pm = getApplicationContext().getPackageManager();
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resolveInfos) {
String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
if ( pkgName.equalsIgnoreCase(getPackageName())) {
return resolveInfo.activityInfo.name;
}
}
return null;
}
}
You don't need two services now.....
Check this topic:
FirebaseInstanceIdService is deprecated now.
You dont need this.
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
Use it like this.
AndroidManifest.xml
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static int NOTIFICATION_ID = 1;
#Override
public void onNewToken(String s) {
super.onNewToken(s);
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Code to create the Notification
}
}
gradle build
implementation 'com.google.firebase:firebase-core:16.0.3'
implementation 'com.google.firebase:firebase-messaging:17.3.0'
I'm trying firebase push notification. I did everything it said in the tutorial, but it isn't working.
FirebaseMessagingService:
package com.example.firebasenf.firebasenf;
import com.google.firebase.messaging.FirebaseMessagingService;/
public class MyFirebaseMessagingService extends FirebaseMessagingService {
}
FirebaseInstanceIdService:
package com.example.firebasenf.firebasenf;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
}
Manifest:
<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>
you need to add some methods to your code :
FirebaseMessagingService:
package com.example.firebasenf.firebasenf;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage){
Intent intent = new Intent(this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setContentTitle("Application Title");
notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
FirebaseInstanceIdService :
package com.example.firebasenf.firebasenf;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String REG_TOKEN = "REG_TOKEN";
#Override
public void onTokenRefresh(){
String recent_token = FirebaseInstanceId.getInstance().getToken();
Log.d(REG_TOKEN,recent_token);
}
}
you need to override onMessageReceived in MyFirebaseMessagingService class to do some actions when notification is pushed.
doc
By overriding the method FirebaseMessagingService.onMessageReceived,
you can perform actions based on the received RemoteMessage object and
get the message data
#Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
Log.d(TAG, "From: " + "Notification Received");
// TODO(developer): Handle FCM messages here.
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());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "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.
//You may want show notification
}
keep in mind onMessageReceived will only triggered if the app in foreground
When your app is in the background, Android directs notification
messages to the system tray. A user tap on the notification opens the
app launcher by default.
I'm having an issue with Firebase notifications. I set up it as the docs but it's not working. Below, you can see my code. Although I think everything is right.
Here's my NotificationsService
public class NotificationsService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String TAG = "Notification";
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());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "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.
}
}
And the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.usefashion.useapp">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.NoActionBar">
<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=".NotificationsService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".InstanceIdService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
It would be great if anyone could help me. I have an InstanceIdService too but its not the part of this question.
Edit 1:
I realized that when I send a notification by console, this message is showed in debug:
E/FirebaseInstanceId: Error resolving target intent service, skipping classname enforcement. Resolved service was: com.taplane.triviaquiz/com.msi.logocore.helpers.thirdparty.firebase.FirebaseServiceListener
What is it?
hers's my fcm services:
=> public class MyFirebaseInstanceIdServices extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "FireBase token: " + refreshedToken);
Prefs.setFirebaseToken(getApplicationContext(), refreshedToken);
}
}
=> public class MyFirebaseMessagingServices extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getData() + " Message Body");
Map<String, String> notiMessage = remoteMessage.getData();
String type = notiMessage.get("type");
String title = notiMessage.get("title");
String message = notiMessage.get("message");
String orderId = notiMessage.get("order_id");
sendNotification(type, title, message, orderId);
}
//This method is only generating push notification
private void sendNotification(String type, String title, String message, String orderId) {
if (Prefs.getIsLogin(this)) {
Intent intent = null;
if (type.equals("order")) {
intent = new Intent(this, OrderConfirmationActivity.class);
intent.putExtra(Constant.ORDER_ID, orderId);
intent.putExtra("FromNoti", true);
} else {
intent = new Intent(this, HomeActivity.class);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_marker);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(bitmap)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
}
=> In Manifest file:
<service android:name="com.labagel.fcm.MyFirebaseMessagingServices">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name="com.labagel.fcm.MyFirebaseInstanceIdServices">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
I'm trying to setup a system where an Android mobile phone receives notification from a server: for this task we have chosen Firebase.
While the application is in background everything works fine: after I push a message from the firebase console a notification appears on the system tray and, after the message is clicked by the user, an Intent with extra data is sent to the Activity.
My problem is uniquely when the application is already in foreground. The firebase notification is pretty clear: if the application is in foreground, no matter which type of message is sent by the server, OnMessageReceived is never called... so why it fails with my simple app? Some notes to help you solve this issue:
we're working with Android Studio 2.1.2;
"it.bagozi.ada.tutorial.firebase" contains both classes (as you might deduce from the pacakge declaration);
Below you can find all the source code used:
Main Activity
package it.bagozi.ada.tutorial.firebase;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private TextView notification;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.notification = (TextView) this.findViewById(R.id.notification_setter);
Intent i = this.getIntent();
Log.e(TAG, "Intent from Activity caller: " + i);
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}
}
}
FirebaseNotificationService
package it.bagozi.ada.tutorial.firebase;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class FirebaseNotificationService extends FirebaseMessagingService {
private static final String TAG = FirebaseNotificationService.class.getSimpleName();
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
Log.e(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.e(TAG, "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.
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="it.bagozi.ada.tutorial.firebase">
<service android:name=".FirebaseNotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
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>
</application>
</manifest>
Make the service declaration in your manifest a child of the "application" tag!