palak patel
palak patel

Reputation: 21

how to receive custom data from push notification when app is in background in android

 @Override
public void onMessageReceived(RemoteMessage remoteMessage)
{

    if (remoteMessage.getData().size() > 0)
    {
        Log.e(TAG, "Message body:" + remoteMessage.getNotification().getBody());

        for (Map.Entry<String, String> entry : remoteMessage.getData().entrySet())
        {
            String key = entry.getKey();
            String value = entry.getValue();
            data.add(value);
            Log.e(TAG, "key, " + key + " value " + value);

        }

        post_id = data.get(0);
        lang = data.get(1);
        link = data.get(2);

        Log.e("post_id",post_id);
        Log.e("lang",lang);
        Log.e("link",link);
    }

    sendNotification(remoteMessage.getNotification().getBody());

}

when app is in background this method never called and therefore i cant receive any data when app is in background

Any help will be appreciated...

Upvotes: 0

Views: 790

Answers (3)

Diaa Saada
Diaa Saada

Reputation: 1056

when sending the data add these two attributes 'ttl' => 3600, 'content_available' => true

e.g.

return Curl::to('https://fcm.googleapis.com/fcm/send')
            ->withHeader('Authorization: key=' . env('FIREBASE_KEY'))
            ->withHeader('Content-Type: application/json')
            ->withData(['to' => $firebase_token, 'data' => $data, 'ttl' => 3600,  'content_available' => true ])
            ->asJson(true)
            ->post();

this helped me before.

then this should work

int someArg = Integer.parseInt(remoteMessage.getData().get(AdminCommands.KEY_SOME_ARG ));

Upvotes: 0

Nurlan Shukurov
Nurlan Shukurov

Reputation: 51

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

    if (remoteMessage.getData() != null)
        sendNotification(remoteMessage);
}

Upvotes: 0

nhatpv
nhatpv

Reputation: 93

You should implement onMessageReceived() in service. So when your application in background, it's still receive this call back normal. Firebase supported all of this.

in AndroidManifest.xml declare

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

in Java code:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    //do receive data
}

Upvotes: 1

Related Questions