Fire base onMessageReceived isn't working at all - android

I've looked over all the answers I could find, the particular function of code isn't working even in foreground. I tried changing the manifest, changing the code, all i get in the logger are these 2 of these things:
D/FA: Logging event (FE): notification_receive(_nr), ...
This is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/avatar"
android:label="#string/app_name"
android:roundIcon="#drawable/avatar"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<activity android:name=".StartActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"/>
<service android:name=".GettingDeviceTokenService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".NotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
And here is the notification service:
public class NotificationService extends FirebaseMessagingService {
public static int NOTIFICATION_ID = 1;
private static final String CHANNEL_ID = "1";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("+++", remoteMessage.toString());
if (remoteMessage.getData().size() > 0) {
Log.d("dataa", "Data Payload: " + remoteMessage.getData().toString());
}
}
This is the app gradle file
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.example.xghos.Wrenchy"
minSdkVersion 21
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'net.hockeyapp.android:HockeySDK:5.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.google.firebase:firebase-core:16.0.1'
implementation 'com.google.firebase:firebase-messaging:17.3.0'
implementation 'com.ethanhua:skeleton:1.1.1'
implementation 'io.supercharge:shimmerlayout:2.1.0'
implementation "com.daimajia.swipelayout:library:1.2.0#aar"
}
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '26.1.0'
}
}
}
}
apply plugin: 'com.google.gms.google-services'
and the GettingDeviceTokenService:
package com.example.xghos.Wrenchy;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class GettingDeviceTokenService extends FirebaseMessagingService {
#Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.d("DeviceToken ==> ", s);
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
}
}
EDIT: the problem was solved by changing the intent filter of the GettingDeviceTokenService from
<action android:name="com.google.firebase.MESSAGING_EVENT" />
to
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />

You should consider difference between data message and display message.
Display message has payload with key notification and are automatically displayed when app is in background and also call onMessageReceived() if app is already in foreground.
Data message has payload key data . They always invoke onMessageReceived()

You have registered NotificationService service in your manifest. Since latest update for firebase notifications, the same service will handle new token and received messages. In your case you should register in manifest only GettingDeviceTokenService because you override both methods and remove NotificationService.

Try this way. It worked for me Perfectly.
1. Create a Service
public class YourService extends FirebaseMessagingService {
public static int NOTIFICATION_ID = 1;
#Override
public void onNewToken(String s) {
super.onNewToken(s);
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this, "2")
.setSmallIcon(R.drawable.your_icon)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (NOTIFICATION_ID > 1073741824) {
NOTIFICATION_ID = 0;
}
Objects.requireNonNull(notificationManager).notify(NOTIFICATION_ID++, mNotifyBuilder.build());
}
}
Now add this to Manifest
<service
android:name=".YourService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>

Related

Android Broadcast Receiver is showing permission error even it is set

I am having trouble setting up Broadcastreceiver on SMS Receive. I have set all permissions but still it is giving the following permission error
.../system_process W/BroadcastQueue: Permission Denial: receiving
Intent { act=android.provider.Telephony.SMS_RECEIVED flg=0x19000010
(has extras) } to me.jatinsoni.broadcastreceiver/.MyBroadcastReceiver
requires android.permission.RECEIVE_SMS due to sender
com.android.phone (uid 1001)
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcastreceiver">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<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>
<receiver
android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<category android:name="android.intent.category.APP_MESSAGING"/>
</intent-filter>
</receiver>
</application>
</manifest>
MyBroadcastReceiver
...
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Broadcast Receiver Triggered!", Toast.LENGTH_SHORT).show();
Log.d("BroadcastReceiver", "Broadcast Receiver Triggered!");
}
}
Gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.broadcastreceiver"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
In Android 6 and above defining the permission in the manifest, not enough, you need to ask for the permission at runtime.
You can use this function in your activity class:
final int REQ_PERMISSION_SMS = 1;
private void requestSmsPermission() {
String permission = Manifest.permission.RECEIVE_SMS;
int grant = ContextCompat.checkSelfPermission(this, permission);
if ( grant != PackageManager.PERMISSION_GRANTED) {
String[] permission_list = new String[1];
permission_list[0] = permission;
ActivityCompat.requestPermissions(this, permission_list, REQ_PERMISSION_SMS);
}
}
And also you can add the following callback for the check that, does user allows you to receive SMS or not:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case REQ_PERMISSION_SMS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//user allow you to recieve sms
} else {
//user don't allow you to recieve sms
}
}
}
}

onMessageReceived not fired when app in foreground

I'm following this tutorial to receive push notifications on my android device.
I can send push notifications from the Firebase console - and I can also see the Firebase event in logcat but my onMessageReceived is never fired. My app is running in the foreground.
Here is the output in logcat after I send a notification:
12-31 12:23:54.741 9453-11132/com.example.app D/FA: Logging event (FE): notification_receive(_nr), Bundle[{firebase_event_origin(_o)=fcm, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=407943440756026938, message_device_time(_ndt)=0, message_name(_nmn)=Label Arse, message_time(_nmt)=1514723034, message_id(_nmid)=3115372290763926350}]
12-31 12:23:54.784 9453-11132/com.example.app V/FA: Connecting to remote service
12-31 12:23:54.797 9453-11132/com.example.app D/FA: Logging event (FE): notification_foreground(_nf), Bundle[{firebase_event_origin(_o)=fcm, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=407943440756026938, message_device_time(_ndt)=0, message_name(_nmn)=Label Arse, message_time(_nmt)=1514723034, message_id(_nmid)=3115372290763926350}]
12-31 12:23:54.828 9453-11132/com.example.app V/FA: Connection attempt already in progress
12-31 12:23:54.829 9453-11132/com.example.app D/FA: Connected to remote service
12-31 12:23:54.829 9453-11132/com.example.app V/FA: Processing queued up service tasks: 2
12-31 12:23:59.875 9453-11132/com.example.app V/FA: Inactivity, disconnecting from the service
MyFirebaseMessageingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
}
}
FirebaseIDService.java
public class FirebaseIDService extends FirebaseInstanceIdService {
private static final String TAG = "FirebaseIDService";
#Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:hardwareAccelerated="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:windowSoftInputMode="stateHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".services.MyFirebaseMessagingService"
android:enabled="true"
android:exported="true" />
<service
android:name=".services.FirebaseIDService"
android:enabled="true"
android:exported="true"></service>
</application>
</manifest>
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "com.example.app"
minSdkVersion 17
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
java.srcDirs = ['src/main/java', 'src/main/java/services']
}
}
}
repositories {
maven { url "https://jitpack.io" }
}
dependencies {
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.google.firebase:firebase-messaging:11.8.0'
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.volley:volley:1.1.0'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.github.PhilJay:MPAndroidChart:v2.1.6'
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:25.4.0'
compile 'com.google.firebase:firebase-appindexing:11.8.0'
compile files('libs/glide-full-4.3.1.jar')
}
apply plugin: 'com.google.gms.google-services'
as per google firebase messaging guide
try replacing your service tag in the manifest file with :
<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>
in the onMessageReceived() refer here you can get the notification / data payload :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " +
remoteMessage.getNotification().getBody());
}
}
}

Wrong 3rd argument type. Found: 'android.content.Intent', required: 'android.content.Intent

I can't solve this 'intent'problem!
When notification received my phone stop working with a message "System UI Stoped"
I'm using Android Studio 3.0.1
FirebaseMessagingService File>
Here I'm getting an error for "PendingIntend.FLAG_ONE_SHOT" line. The "intent" has and red underlind and asking for an arry!
package firebase.com.firebasecloudmessaging;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.app.LoaderManager.LoaderCallbacks;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public MyFirebaseMessagingService() {
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody)
{
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.drawable.ic_stat_name);
notificationBuilder.setContentTitle("LiveCricket");
notificationBuilder.setContentText(messageBody);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(defaultSoundUri);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
Manifest File>
Please check this file also,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="firebase.com.firebasecloudmessaging">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<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"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
FirebaseInstanceId File>
This file is not showing any error!
package firebase.com.firebasecloudmessaging;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import static android.content.ContentValues.TAG;
public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
// 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(refreshedToken);
}
private void sendRegistrationToServer(String token)
{
}
}
Build.gradle(Project)>
Please check the gradle file!
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath 'com.google.gms:google-services:3.1.0'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Build.gradle(App level)>
Please check the gradle file!
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "firebase.com.firebasecloudmessaging"
minSdkVersion 18
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint- layout:1.0.2'
implementation 'com.google.firebase:firebase-messaging:11.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
apply plugin: 'com.google.gms.google-services'

FCM Firebase daily limit (I am able to send only one in a day)

I am using the Firebase Console to send notifications.
I am testing my app so my app is installed only in my phone.
I am able to send only one notification to my app in a day, the rest of the notifications are showing as Completed, but not delivered.
My selected options are => User segment > app > and my app package name.
Is there a limit in the free plan?
build.gradle (PROJECT)
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
build.gradle (MODULE)
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "com.example.myfirstapp"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.google.firebase:firebase-core:9.0.1'
compile 'com.google.firebase:firebase-messaging:9.0.1'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp" >
<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/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=".TokenService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<service
android:name=".FCMMessageReceiverService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
TOKEN SERVICE
public class TokenService extends FirebaseInstanceIdService {
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d("notification", refreshedToken);
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
}
}
FCMMessageReceiverService
package com.example.myfirstapp;
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 FCMMessageReceiverService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.w("fcm", "received notification");
sendNotification(remoteMessage.getNotification().getTitle());
}
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 , intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageBody)
.setAutoCancel(false)
.setSound(defaultSoundUri);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());
}
}
I believe for testing purpose, there is an initial limit with multiple devices, and instances. the rest is fine.

FirebaseInstanceIdService getToken returning null

Im trying to add FCM notifications to my app, but for some reason
FirebaseInstanceId.getInstance().getToken();
is returning null.
Since im not getting any stacktrace my best guess is that FirebaseInstanceIdService is not working
Google Play Services version: 9.6.1
Firebase-messaging version : 9.6.1
added json config file from FirebaseConsole (Tried single file with 2 clients inside it, one for debug and one for release build) and 2 files each for respective build
Iw applied google services plugin at the bottom of my modules gradle script
Included google services in projects root gradle script
Created 2 services from the officail docs:
public class MyFirebaseInsanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
PreferencesHelper.putSharedPreferencesString(Constants.User.PUSH_NOTIFICATIONS, refreshedToken);
Log.e("TOKEN", "Token: " + FirebaseInstanceId.getInstance().getToken());
}
}
And the manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.fc.test">
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="fctest"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="${appName}${appNameSuffix}"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:node="replace">
<service
android:name="com.fc.test.MyFirebaseInsanceIDService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name="com.fc.test.MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity
android:name="com.fc.test.view.splash.Splash"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.CenterAnimation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
root Gradle:
buildscript {
repositories {
jcenter()
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
//noinspection GradleDynamicVersion
classpath 'io.fabric.tools:gradle:1.+'
classpath 'com.google.gms:google-services:3.0.0'
}
}
allprojects {
repositories {
jcenter()
maven { url "http://dl.bintray.com/drummer-aidan/maven" }
maven { url "https://maven.fabric.io/public" }
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
maven { url "https://jitpack.io" }
}
}
ext {
buildToolsVersion = '24.0.1'
compileSdkVersion = 24
minSdkVersion = 15
targetSdkVersion = 24
supportLibraryVersion = '24.2.1'
}
and the main part of the modules Gradle
dependencies {
final PLAY_SERVICES_VERSION = '9.6.1'
final SUPPORT_LIBRARY_VERSION = '24.2.1'
final RETROFIT_VERSION = '2.1.0'
final DAGGER_VERSION = '2.5'
final DEXMAKER_VERSION = '1.4'
final HAMCREST_VERSION = '1.3'
final ESPRESSO_VERSION = '2.2.1'
final RUNNER_VERSION = '0.4'
final BUTTERKNIFE_VERSION = '8.1.0'
def daggerCompiler = "com.google.dagger:dagger-compiler:$DAGGER_VERSION"
def jUnit = "junit:junit:4.12"
def mockito = "org.mockito:mockito-core:1.10.19"
// App Dependencies
compile "com.google.android.gms:play-services-gcm:$PLAY_SERVICES_VERSION"
compile "com.google.firebase:firebase-messaging:$PLAY_SERVICES_VERSION"
compile "com.android.support:appcompat-v7:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:recyclerview-v7:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:cardview-v7:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:design:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:support-annotations:$SUPPORT_LIBRARY_VERSION"
compile "com.android.support:support-v4:$SUPPORT_LIBRARY_VERSION"
compile "com.squareup.retrofit2:retrofit:$RETROFIT_VERSION"
compile "com.squareup.retrofit2:converter-gson:$RETROFIT_VERSION"
compile "com.squareup.retrofit2:adapter-rxjava:$RETROFIT_VERSION"
compile "com.jakewharton:butterknife:$BUTTERKNIFE_VERSION"
compile('com.crashlytics.sdk.android:crashlytics:2.6.5#aar') {
transitive = true;
}
}
apply plugin: 'com.google.gms.google-services
Note that im using tools:node="replace" in my root application tag.
Is it possible that FirebaseInstanceIdService is not added to the manifest since it has the same intent filter as mine FirebaseInstanceService and thus not being called?
So my question here would be is there something wrong it the official docs or in my implementation that should cause the Instance token to be null?
After digging up thru old implementations of FCM and generated manifests, I can now say that manifest merger is the problem.
Solution for this problem is adding these classes to the apps manifest manualy
<activity
android:name="com.google.android.gms.common.api.GoogleApiActivity"
android:exported="false"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<service
android:name="com.google.firebase.messaging.FirebaseMessagingService"
android:exported="true" >
<intent-filter android:priority="-500" >
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<receiver
android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.fc.debug" />
</intent-filter>
</receiver>
<receiver
android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver"
android:exported="false" />
<!--
-->
<service
android:name="com.google.firebase.iid.FirebaseInstanceIdService"
android:exported="true" >
<intent-filter android:priority="-500" >
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<provider
android:name="com.google.firebase.provider.FirebaseInitProvider"
android:authorities="com.fc.debug.firebaseinitprovider"
android:exported="false"
android:initOrder="100" />
<receiver
android:name="com.google.android.gms.measurement.AppMeasurementReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="com.google.android.gms.measurement.UPLOAD" />
</intent-filter>
</receiver>
<service
android:name="com.google.android.gms.measurement.AppMeasurementService"
android:enabled="true"
android:exported="false" />
While I was doing the migration I had a problem, it was that I didn't receive any Notification. To solve this and If you have your GCM working, don't forget to include your sender ID when you get the Firebase Token. To consult this ID you have to navigate to your Firebase project and click Project Name. Click the Setting icon and select "Project Setting" menu Select "Could Messaging" tab and use sender ID on the page.
And when says to code this:
token = FirebaseInstanceId.getInstance().getToken();
You have to use this:
token = FirebaseInstanceId.getInstance().getToken("YOUR_SENDER_ID", "FCM");
It works for me, I hope this helps you ;)
This worked for me:
String token = FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken();
First genarate "google-services.json" and Add this file in your android studio Like this projectFolder/APP/google-services.json
Add classpath to top level build.gradle
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
Add following plugin and dependencies in app’s build.gradle
apply plugin: 'com.google.gms.google-services'
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.0.0'
compile 'com.google.firebase:firebase-core:9.4.0'
compile 'com.google.firebase:firebase-messaging:9.4.0'
}
Add following Firebase services in your java files
FirebaseIDService.java
package com.galleonsoft.firebase.push;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class FirebaseIDService extends FirebaseInstanceIdService {
private static final String TAG = "FirebaseIDService";
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}
}
MyFirebaseMessagingService.java
package com.galleonsoft.firebase.push;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMEssagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
}
}
Add service in your AndroidMainifest.xml file
<service android:name=".MyFirebaseMEssagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service android:name=".FirebaseIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>

Categories

Resources