2

I'm using fcm to send notifications with data payload (I'm excluding notification object as I want the user to get the notifications whether if the app is in foreground/background or killed).

I'm able to get the notifications and navigate the user to a particular activity when clicked on notification. But, I'm not being able to get the values from the getIntent extras. Every time I try to get the values I get null values. I'm unable to figure where I have gone wrong.

FCM Messaging Service class

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMessagingServ";

NotificationManager notificationManager;



@Override
public void onNewToken(String token) {
    super.onNewToken(token);
    Log.e(TAG, "onNewToken: "+token );
    if(PrefManager.isVendorLoggedIn(MyFirebaseMessagingService.this))
            sendNewTokenToServer(token);
}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    showNotification(remoteMessage);
}


private void showNotification(RemoteMessage remoteMessage){
    String orderID="";
    Map<String,String> dataMap = remoteMessage.getData();
    orderID = dataMap.get("order_id");


    String title="New Order";
    String message="Click here to view the Details";
    String click_action=dataMap.get("click_action");



    Intent intent=new Intent(click_action);
    intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
    intent.putExtra(StringConstants.CURRENT_ORDER_ID,orderID);
    intent.putExtra(StringConstants.BUZ_ID,dataMap.get("business_id"));
    intent.putExtra("TITLE",title);
    intent.putExtra("BODY",message);


    NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this);
    notificationBuilder.setContentTitle(title);
    notificationBuilder.setContentText(message);
    notificationBuilder.setSmallIcon(R.drawable.splash_logo);
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setContentIntent(pendingIntent);
    notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(8,notificationBuilder.build());
}

private void sendNoti(RemoteMessage remoteMessage){

    String click_action=remoteMessage.getData().get("click_action");
    Intent intent=new Intent(click_action);
    //Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT|PendingIntent.FLAG_UPDATE_CURRENT);

    String channelId = "101";
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.splash_logo)
                    .setContentTitle("New Order receieved!!")
                    .setContentText("Click to view details")
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

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

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

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

private void sendNewTokenToServer(String token){
    PrefManager prefManager = new PrefManager(MyFirebaseMessagingService.this);
    String url = Constants.BASE_URL+"vendor/add-refresh-token";
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("vendor_id",prefManager.getVendorId(getApplicationContext()));
        jsonObject.put("token",token);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    CustomJsonRequest customJsonRequest = new CustomJsonRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    customJsonRequest.setPriority(Request.Priority.HIGH);
    ReatchAll helper = ReatchAll.getInstance();
    helper.addToRequestQueue(customJsonRequest,"UPDATE_TOKEN");
}}

Target Activity class(which matches the intent filter)

public class VendorCurrentOrderActivity extends AppCompatActivity {

private static final String TAG = "VendorCurrentOrderActiv";
Context context;
ReatchAll helper = ReatchAll.getInstance();
CustomProgressDialog customProgressDialog;
PrefManager prefManager;


String orderId,buzId;
OrderedItemsAdapter orderedItemsAdapter;
ArrayList<OrderedItem> orderedItemArrayList;

RecyclerView itemsRcv;
ImageView backArrow;
FontTextView acceptOrder,rejectOrder;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_vendor_current_order);
    context = VendorCurrentOrderActivity.this;
    customProgressDialog = new CustomProgressDialog(context);
    prefManager = new PrefManager(context);

    backArrow =(ImageView)findViewById(R.id.back_arrow);
    backArrow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });

    initViews();

    orderId = getIntent().getExtras().getString(StringConstants.CURRENT_ORDER_ID);
    buzId = getIntent().getExtras().getString(StringConstants.BUZ_ID);
    Log.e(TAG, "onCreate: "+orderId);
    Log.e(TAG, "onCreate: NOTI DATA "+getIntent().getExtras().getString("TITLE")+" "+getIntent().getExtras().getString("BODY") );
    customProgressDialog.showDialog();
    getOrderDetails();

   // onNewIntent(getIntent());
}}

Manifest

 <activity android:name=".Vendor.Orders.VendorCurrentOrderActivity"
        android:launchMode="singleTask"
        android:taskAffinity=""
        android:excludeFromRecents="true"
        android:exported="true">
        <intent-filter>
            <action android:name="NEW_ORDER" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
halfer
  • 19,824
  • 17
  • 99
  • 186
rsk
  • 46
  • 1
  • 8

2 Answers2

1

As you are sending data via Intent created by you. Instead of getExtras. Try getStringExtra or getIntExtra. because getExtras will give you data only when notification is created by android system when app is in background and onMessageRecieved not being called.

Zaid Mirza
  • 3,540
  • 2
  • 24
  • 40
0

In the Manifest you need to put MyFirebaseMessagingService as a service

<service
    android:name=".MyFirebaseMessagingService ">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
Axel López
  • 266
  • 1
  • 5
  • 13