4

I want to start a specific activity automatically after receiving fcm push notification.it works fine with on clicking but I want to start it automatically after the notification is received.Here is my code

My FirebaseMessagingService method where I am triggering the code

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

private NotificationUtils notificationUtils;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.e(TAG, "From: " + remoteMessage.getFrom());
//changes for notification on 9/11/2017
//        if(remoteMessage.getNotification().getBody()!=null) {
       // Log.e(TAG, "Message Body: " + remoteMessage.getNotification().getBody());
    //}
    //showNotificationMessage(remoteMessage.getNotification().getBody());
//        String click_action=remoteMessage.getNotification().getClickAction();
   // Intent i=new Intent(click_action);
 ////////////////////////////////////////
        if (remoteMessage == null)
        return;

    // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
        Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());

        handleNotification(remoteMessage.getNotification().getBody());
    }

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "AllCallsData Payload: " + remoteMessage.getData().toString());

        try {
            JSONObject json = new JSONObject(remoteMessage.getData().toString());
            Handler mHandler;
            //mHandler = new Handler() {
                handleDataMessage(json);
            //};
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
}

private void handleNotification(String message) {
    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
        // app is in foreground, broadcast the push message
        Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
        pushNotification.putExtra("message", message);
        LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

        // play notification sound
        NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
        notificationUtils.playNotificationSound();
        //Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.);
        //Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        //r.play();
    }else{
        // If the app is in background, firebase itself handles the notification
    }
}

    private void handleDataMessage (JSONObject json){

        Log.e(TAG, "push json: " + json.toString());

        try {
            JSONObject data = json.getJSONObject("data");

            String title = data.getString("title");
            String message = data.getString("message");
            boolean isBackground = data.getBoolean("is_background");
            //String imageUrl = data.getString("image");
            String timestamp = data.getString("timestamp");

            JSONObject payload = data.getJSONObject("payload");
            OpenTokConfig.SESSION_ID = payload.getString("session_id");
            OpenTokConfig.API_KEY = payload.getString("api_key");
            OpenTokConfig.TOKEN = payload.getString("token_id");

            Log.e(TAG, "title: " + title);
            Log.e(TAG, "message: " + message);
            Log.e(TAG, "isBackground: " + isBackground);

            //Log.e(TAG, "payload: " + payload.toString());
            //Log.e(TAG, "imageUrl: " + imageUrl);
            Log.e(TAG, "timestamp: " + timestamp);
            Intent i = new Intent(Config.CLICK_ACTION);
            showNotificationMessage(getApplicationContext(), title, message, timestamp, i);


            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
                // app is in foreground, broadcast the push message
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", message);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

                // play notification sound
                NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
                notificationUtils.playNotificationSound();
                Common.call_recvd = true;
            } else {
                // app is in background, show the notification in notification tray
                Intent resultIntent = new Intent(getApplicationContext(), RegistrationActivity.class);
                resultIntent.putExtra("message", message);

                // check for image attachment
           /* if (TextUtils.isEmpty(imageUrl)) {
                showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
            } else {
                // image is present, show notification with image
                showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
            }*/
            }
        } catch (JSONException e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }


/**
 * Showing notification with text only
 */
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
    //startActivity(intent);
}

/**
 * Showing notification with text and image
 */
private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
}

}

MyNotification Utils class code

public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) {
    // Check for empty push message
    if (TextUtils.isEmpty(message))
        return;


    // notification icon
    final int icon = R.mipmap.ic_launcher;

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    final PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    mContext,
                    0,
                    intent,
                    PendingIntent.FLAG_CANCEL_CURRENT
            );

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            mContext);

    final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
            + "://" + mContext.getPackageName() + "/raw/notification");

    if (!TextUtils.isEmpty(imageUrl)) {

        if (imageUrl != null && imageUrl.length() > 4 && Patterns.WEB_URL.matcher(imageUrl).matches()) {

            Bitmap bitmap = getBitmapFromURL(imageUrl);

            if (bitmap != null) {
                showBigNotification(bitmap, mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
            } else {
                showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
            }
        }
    } else {
        showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
        playNotificationSound();
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
user8601021
  • 219
  • 3
  • 18

3 Answers3

0

You can achieve this using broadcast receiver,so when you get notification simply send the broadcast and on receiving broadcast you can write code related to start activity.

send broacast using this.

Intent intentNotification = new Intent();
intentNotification.setAction("com.from.notification");
sendBroadcast(intentNotification);

register your broadcast receiver using this :

getActivity().registerReceiver(broadcastReceiver,
                new IntentFilter("com.from.notification"));

on receive broadcast :

private BroadcastReceiver broadcastReceiver;
broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // do your stuff related to start activity
            }
        };
Nilam Vaddoriya
  • 433
  • 2
  • 10
  • Check it i have updated my answer and let me know if you have any doubt – Nilam Vaddoriya Nov 20 '17 at 07:41
  • maybe this is right but before trying I want to ask,I have my onReceive in another activity where I am receiving the fcm token and sending with registration form while the activity I want to open once I receive the notification is different.So do i put 2 broadcast receivers in 2 activity classes? – user8601021 Nov 20 '17 at 08:39
  • No,you don't need to put it into 2 class,only put into onMessageReceive() method. – Nilam Vaddoriya Nov 20 '17 at 08:42
  • sorry but it still doesnt start the activity automatically – user8601021 Nov 20 '17 at 09:04
  • I put ur code below the intent declaration in FireBaseMessagingService and I also tried it in NotificationUtils class.the code works as before.I can click and go to the specified activity but not automatically – user8601021 Nov 20 '17 at 10:58
  • only send broadcast related code is in onMessageReceive() method,and to register and receive broadcast related code is in your any activity from where in broadcast receive method you can write a code related to activity transaction;. – Nilam Vaddoriya Nov 20 '17 at 12:45
  • i have put a intent filter and that name is stored in the string CLICK_ACTION which diverts to that activity on click.Regarding that broadcast receiver code i will try once again tomorrow sorry I have to leave now.wil let u know – user8601021 Nov 20 '17 at 13:16
  • can you send full code about that with class name?? – Ramesh Bhati Sep 01 '22 at 04:35
  • This is wrong. Runtime-registered receivers only work while the app is running. Not to mention the memory leak from that non-static inner class (which, based on `getActivity()`, is on a `Fragment`). – Ryan M May 10 '23 at 23:38
-1

automatically start an activity after receiving FCM notification in Kotlin.

override fun onMessageReceived(remoteMessage: RemoteMessage) {
    super.onMessageReceived(remoteMessage)
    val notification = remoteMessage.notification
    if (notification != null) {
        val intent = Intent(this, SecondActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(intent)
    }
}
Aftab Alam
  • 1,969
  • 17
  • 17
  • [This won't work on Android 10 or later](https://developer.android.com/guide/components/activities/background-starts). – Ryan M May 10 '23 at 23:39
-3

When you receive notification,

Intent notificationIntent = new Intent(context, YourActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(notificationIntent);

But you have to manage what to do when app is in background, foreground or killed state.

Dhruv Patel
  • 1,529
  • 1
  • 18
  • 27