'Firebase not working on my android app project

I am trying to use Firebase Cloud Messaging on an Android Project I inherited from my predecessor in my place of work.

For some unknown reason Firebase has refused to work on the project, it doesn't matter whether the app is in background or not.

However if I create fresh projects and implement Firebase it works flawlessly.

build.gradle (app)

apply plugin: 'com.android.application'

apply plugin: 'com.google.firebase.crashlytics'

apply plugin: 'com.google.firebase.firebase-perf'

android {
    compileSdkVersion 29
    buildToolsVersion '29.0.2'
    defaultConfig {
        applicationId "com.dmk.name_international"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 5
        versionName "1.0-beta-2"
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            debuggable false
            jniDebuggable false
            minifyEnabled true
            shrinkResources true //reduces apk size
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
            jniDebuggable true
            minifyEnabled false
            shrinkResources false //reduces apk size
        }
    }

    flavorDimensions "country"
    productFlavors {


        tanzania {
            dimension "country"
            applicationId "com.dmk.name_international"

        }

        ethiopia {
            dimension "country"
            applicationId "com.name.ethiopia"
        }

        drc {
            dimension "country"
            applicationId "com.name.drc"
        }

    }

    packagingOptions {
        exclude 'META-INF/LICENSE'
    }

    dexOptions {
        jumboMode true
    }

    lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in release builds,
        // but continue the build even when errors are found:
        abortOnError false
    }

    compileOptions {
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

repositories {
    mavenCentral()
    maven {
        url "https://jitpack.io"
    }

    maven { url 'https://maven.fabric.io/public' }
    jcenter()
    google()
}

configurations {
    cleanedAnnotations
    compile.exclude group: 'org.jetbrains' , module:'annotations'
}


dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'androidx.multidex:multidex:2.0.1'
    //Views and Anim libs
    implementation 'androidx.appcompat:appcompat:1.2.0-alpha02'
    implementation 'com.google.android.material:material:1.2.0-alpha04'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.makeramen:roundedimageview:2.3.0'
    implementation 'com.wang.avi:library:2.1.3'

    implementation 'net.cachapa.expandablelayout:expandablelayout:2.9.2'
    implementation 'com.github.florent37:expansionpanel:1.2.2'
    implementation 'com.ethanhua:skeleton:1.1.2'
    implementation 'io.supercharge:shimmerlayout:2.1.0'
    implementation 'com.github.smarteist:autoimageslider:1.3.3'


    //Glide for images
    implementation('com.github.bumptech.glide:glide:4.11.0');
    //video streaming
    implementation 'com.google.android.exoplayer:exoplayer-core:2.7.3'
    implementation 'com.google.android.exoplayer:exoplayer-hls:2.7.3'
    implementation 'com.google.android.exoplayer:exoplayer-ui:2.7.3'
    implementation 'com.google.android.exoplayer:exoplayer-dash:2.7.3'

    //Internet
    implementation 'com.loopj.android:android-async-http:1.4.10'
    implementation 'com.android.volley:volley:1.2.1'

    //utils
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'com.nineoldandroids:library:2.4.0+'
    implementation 'com.facebook.android:facebook-android-sdk:[5,6)'
    implementation 'com.github.instacart.truetime-android:library:3.3'


    //firebase
   // implementation 'com.google.firebase:firebase-core:17.2.2'
    implementation 'com.google.firebase:firebase-messaging:21.1.0'
    implementation 'com.google.firebase:firebase-firestore:21.3.1'
    implementation 'com.google.firebase:firebase-analytics:18.0.3'
    implementation 'com.google.firebase:firebase-crashlytics:17.4.1'


    //implementation 'com.google.firebase:firebase-crash:16.0.1'
    implementation 'com.google.firebase:firebase-perf:19.0.5'
    implementation 'com.google.firebase:firebase-config:19.1.0'


    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.github.mtotschnig:StickyListHeaders:2.7.1'

    //  implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation project(':appRate')
    implementation 'com.github.florent37:diagonallayout:1.0.9'

    //appsflyer
    implementation 'com.appsflyer:af-android-sdk:6.3.2'

}

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        // These docs use an open ended version so that our plugin
        // can be updated quickly in response to Android tooling updates6

        // We recommend changing it to the latest version from our changelog:
        // https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin
        classpath 'io.fabric.tools:gradle:1.+'

    }
}

apply plugin: 'com.google.gms.google-services'

build.gradle (project)


buildscript { 
    ext.kotlin_version = '1.3.10'

    repositories {
        jcenter()

        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.2'
        classpath 'com.google.gms:google-services:4.3.3'
        classpath 'com.google.firebase:firebase-plugins:1.1.5'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.1.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        }

}

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com" // Google's Maven repository
        }
        google()
        mavenCentral()
    }

}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Already added the following code to my AndroidManifest.xm file;

<service android:name=".fcm.MessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
</service>

MessagingService class handles messages received through Firebase Cloud Messaging. The onMessageReceived method in this class is never called.

MessagingService.java


public class MessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);

        new PrefUtils(this).setFCMToken(s);

        Looper.prepare();
        new SyncModel(this).registerDevice(s,true);

    }

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Data: " + remoteMessage.getData());
        Log.d(TAG, "Message data payload: " + new JSONObject(remoteMessage.getData()).toString());


        // Check if message contains a notification payload.
        String title = "name", message = "";
        int game_id = 0;
        String imageUrl = "";
        if (remoteMessage.getNotification() != null) {

            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());

            title = remoteMessage.getNotification().getTitle();
            message = remoteMessage.getNotification().getBody();


            if (message.contains("bet_id")) {

                try {
                    JSONObject jsonObject = new JSONObject(message);
                    //get bet id
                    // jsonObject.getString("bet_id");

                    message = jsonObject.getString("response");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            //save message to db
            InboxMessage im = new InboxMessage();
            im.text = message;
            im.title = title;
            im.date_sent = TrueTime.isInitialized() ? TrueTime.now().toString() : Calendar.getInstance().getTime().toString();
            im.image = imageUrl;

            //SugarRecord.save(im);
        }


        if (remoteMessage.getData().size() > 0) {

            try {
                JSONObject resp = new JSONObject(remoteMessage.getData());

                if (resp.has("game_id"))
                    game_id = resp.getInt("game_id");
                if (resp.has("imageUrl"))
                    imageUrl = resp.getString("imageUrl");

                if (resp.has("message"))
                    message = resp.getString("message");

                if (resp.has("title"))
                    title = resp.getString("title");


                //save message to db
                InboxMessage im = new InboxMessage();
                im.text = message;
                im.title = title;
                im.date_sent = TrueTime.isInitialized() ? TrueTime.now().toString() : Calendar.getInstance().getTime().toString();
                im.image = imageUrl;

                //SugarRecord.save(im);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        sendNotification(title, message, imageUrl, game_id);


        // 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.
    }
    // [END receive_message]

    private void sendNotification(String title, String messageBody, String imageUrl, int game_id) {


        Intent intent = new Intent(this, NotificationActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("game_id", game_id);
        intent.putExtra("message", messageBody);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        String NOTIFICATION_CHANNEL_ID = "Promo";
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notifications", NotificationManager.IMPORTANCE_MAX);

            // Configure the notification channel.
            notificationChannel.setDescription("Customised offers and Bonuses.");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.GREEN);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            notificationManager.createNotificationChannel(notificationChannel);
        }


        final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            notificationBuilder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
            notificationBuilder.setSmallIcon(R.drawable.android_icon_72);
            notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.android_icon_72));
        } else
            notificationBuilder.setSmallIcon(R.drawable.android_icon_72);

        notificationBuilder.setContentTitle(title);
        notificationBuilder.setContentText(messageBody);
        notificationBuilder.setColorized(true);

        notificationBuilder.setSubText("app.name.com");


        FutureTarget<Bitmap> futureTarget =
                Glide.with(getApplicationContext())
                        .asBitmap()
                        .load(imageUrl)
                        .submit(1024, 512);

        try {
            Bitmap bitmap = futureTarget.get();
            notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmap));

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }



        notificationBuilder.setPriority(Notification.PRIORITY_MAX);
        notificationBuilder.setAutoCancel(true);
        notificationBuilder.setSound(defaultSoundUri);
    //    notificationBuilder.setVibrate(new long[]{0, 1000, 500, 1000});
        notificationBuilder.setContentIntent(pendingIntent);


        notificationManager.notify(1 /* ID of notification */, notificationBuilder.build());

        // Do something with the Bitmap and then when you're done with it:
        Glide.with(getApplicationContext()).clear(futureTarget);

    }
}

NB

  1. On the dashboard, the message says it's been successfully sent but is never received by the device.

  2. I'm getting the device token from Firebase.

  3. The google-services.json exists in ProjectName > app and yes, the package name correspond with that in manifest.

How can I make the Notification messages appear on device?

Any help is highly appreciated. Thank you!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source