3

I built a chat application using firebase cloud messaging and firebase functions. But I have two problems currently. 1. When the app is in open and a new message comes in, the app will automatically move to the main activity of the application. 2. And secondly, I want notifications to be received only when it is in the background.

How do I achieve this?

Below is my onMessageReceived

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            showNotification(remoteMessage.getData().get("name"), (remoteMessage.getData().get("click_action")), remoteMessage.getData().get("title"));
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {

        }
    }

    private void showNotification(String name, String click_action, String title) {
        Intent intent;

        if (click_action.equals("Download")) {
            intent = new Intent(this, Download.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else if (click_action.equals("Student_SystemsDevt")) {
            intent = new Intent(this, Student_SystemsDevt.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }
        else {
            intent = new Intent(this, LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }

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

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(title)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText(name)
                .setAutoCancel(true)
                .setStyle(new NotificationCompat.BigTextStyle())
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

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

My Manifest File

<application
    android:name=".GTUCONLINE"
    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=".LoginActivity"
        android:screenOrientation="portrait"
        android:theme="@style/MyTheme" />
    <activity android:name=".MainActivity">
    </activity>
    <activity
        android:name=".ChoiceActivity"
        android:screenOrientation="portrait"
        android:theme="@style/MyTheme" />
    <activity
        android:name=".WelcomeActivity"
        android:screenOrientation="portrait"
        android:theme="@style/MyTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
        android:theme="@style/Base.Theme.AppCompat" />
    <activity
        android:name=".StudentSignUp"
        android:screenOrientation="portrait"
        android:theme="@style/MyTheme" />
    <activity
        android:name=".LecturerSignUp"
        android:screenOrientation="portrait" />
    <activity android:name=".ProgrammeActivity" />

    <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>

    <activity
        android:name=".TopicActivity"
        android:theme="@style/MyTheme" />
    <activity android:name=".MIS" />
    <activity android:name=".GB" />
    <activity android:name=".FIN" />
    <activity android:name=".ENGINEERINGM" />
    <activity android:name=".BDM" />
    <activity android:name=".SCM" />
    <activity android:name=".TE" />
    <activity android:name=".TM" />
    <activity android:name=".BET" />
    <activity android:name=".ICT" />
    <activity android:name=".T" />
    <activity android:name=".IT" />
    <activity android:name=".AM" />
    <activity android:name=".OGM" />
    <activity android:name=".I" />
    <activity android:name=".PEF" />
    <activity android:name=".QM" />
    <activity android:name=".EPM" />
    <activity android:name=".PM" />
    <activity android:name=".HM" />
    <activity android:name=".StudentsList">
        <intent-filter>
            <action android:name="StudentsList" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity android:name=".LecturersList" />
    <activity android:name=".AdminActivity" />
    <activity
        android:name=".ChatActivity"
        android:parentActivityName=".StudentsList" />
    <activity android:name=".LecturerMainActivity" />
    <activity
        android:name=".Download"
        android:parentActivityName=".MIS">
        <intent-filter>
            <action android:name="Download" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MIS_Information"
        android:parentActivityName=".MIS" />
    <activity android:name=".Terms" />
    <activity
        android:name=".Admin_Login"
        android:parentActivityName=".LoginActivity" />
    <activity
        android:name=".Manipulation"
        android:parentActivityName=".Admin_Login" />
    <activity android:name=".Admins" />
    <activity
        android:name=".SystemsDevt"
        android:parentActivityName=".MIS" />
    <activity
        android:name=".SysGroupChat"
        android:parentActivityName=".SystemsDevt" />
    <activity
        android:name=".EntSystems"
        android:parentActivityName=".MIS" />
    <activity android:name=".DownloadEnt">
        <intent-filter>
            <action android:name="DownloadEnt" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity android:name=".student_mis" />
    <activity
        android:name=".Student_SystemsDevt"
        android:parentActivityName=".student_mis">
        <intent-filter>
            <action android:name="Student_SystemsDevt" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Student_EntSys"
        android:parentActivityName=".student_mis" />
    <activity
        android:name=".SystemsDevt_Add"
        android:parentActivityName=".SystemsDevt" />
    <activity android:name=".EntSystemsAdd" />
    <activity android:name=".EntSystemsInfo" />
    <activity
        android:name=".DatabaseSystems"
        android:parentActivityName=".MIS" />
    <activity android:name=".DownloadDatabaseSys" />
    <activity
        android:name=".Student_DatabaseSystems"
        android:parentActivityName=".student_mis" />
    <activity android:name=".DatabaseInfo" />
    <activity
        android:name=".DatabaseAdd"
        android:parentActivityName=".DatabaseSystems" />
    <activity
        android:name=".IntroToOil"
        android:parentActivityName=".GB" />
    <activity
        android:name=".DownloadIntro"
        android:parentActivityName=".IntroToOil" />
    <activity
        android:name=".IntroToOilInfo"
        android:parentActivityName=".IntroToOil" />
    <activity
        android:name=".IntroToOilAdd"
        android:parentActivityName=".IntroToOil" />
    <activity android:name=".student_gb" />
    <activity android:name=".StudentIntro" />
    <activity android:name=".MIS_students_new"
        android:parentActivityName=".SystemsDevt">

    </activity>
</application>
ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56

2 Answers2

1

1- Actually onMessageReceived is only triggered when your application is in foreground as described enter link description here. So if you don't override onMessageReceived, you will not receive push when your app is in foreground

2- According to fcm docs, when your app is in background, onMessageReceived is not triggered but

the data payload is delivered in the extras of the intent of your launcher Activity.

It explains why your push redirects to your main activity (your launcher).

So far, you can handle the redirection from the intent.

You can also specify the activity where it sould be redirected like enter link description here:

{
  "to":"some_device_token",
  "content_available": true,
  "notification": {
    "title": "hello",
    "body": "test message",
    "click_action": "OPEN_ACTIVITY_1"
  },
  "data": {
    "extra":"juice"
  }
}

don't forget intent filter for the desired activity:

<intent-filter>
   <action android:name="OPEN_ACTIVITY_1" />
   <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
maheryhaja
  • 1,617
  • 11
  • 18
0

Also add Tasks permission in manifest.

private boolean isAppForeground() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null) {
            return false;
        }
        final String packageName = getPackageName();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
                return true;
            }
        }
        return false;
    } 

 if(isAppForeground()){
   // Handle notification silently without displaying in notification tray
 }else{
    // Do your regular stuff

   // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            showNotification(remoteMessage.getData().get("name"), (remoteMessage.getData().get("click_action")), remoteMessage.getData().get("title"));
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {

        }
 }
Arpit bandil
  • 204
  • 2
  • 9