How to address firebase notification to an app?

Asked

Viewed 375 times

0

I am developing an application that needs to receive notifications from the server PHP.

I was able to develop a code that sends the message, but it is not displayed in the device tray. I don’t think I am using the correct keys on json.

Code:

$fields = array(
    'to'=> 'USANDO A CHAVE DO SERVIDOR -TOKEN DA SEÇÃO CLOUDMESSAGING DO FIREBASE',   <-- È ISSO MESMO???

    array('notification' => array(
       array(
           'title' => 'Titulo Teste',
           'body' => 'Corpo da notificação'
       )
       )));

$headers = array(
    'Authorization: key=' . API_ACCESS_KEY,  <- USANDO A CHAVE DA API DA GUIA GERAL DO PROJETO. ESTÁ CERTO??
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
$result = curl_exec($ch);
curl_close($ch);

And the return is this:

{"multicast_id":6476377154595056432,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1547467018208139%00000000f9fd7ecd"}]} 

But no message is displayed in the notification tray of the devices that have the application installed.

When sending via the console Firebase, the message is normally displayed in the onMessageReceived(RemoteMessage remoteMessage) of my routine on Android.

  • 1

    The to serves to inform which group you want to send a certain notification. I made a code some time ago (https://packagist.org/packages/valdeirpsr/firebasemessaging-php) and it can help you. P.S.: You can delete the to

  • 'to'=> 'TOKEN DO DISPOSITIVO' as you can see here, is to trigger the notification to a specific device.

  • @Valdeir Psr its structure is too big for use in my project and I also don’t use Composer. I tried to omit the OT in the code as they said, but the message is not sent and the return and only the word to. I appreciate some more help. Had understood that only omitting the TO the message would go to the APP connected to API_ACCESS_KEY

1 answer

0

Whoa, that’s all right!?

You will need the following:

  1. Class to make a request to the server and save the mobile id
  2. Other Box to receive notification.

First do the Firebase Imports in build.Gradle (Module: app), assuming that you are already using firebase in your project, because there are other basic steps needed to work (those that firebase teaches you to configure when you create the project in the console):

implementation 'com.google.firebase:firebase-messaging:12.0.1'

You will need these following parameters in your manifest within the application tag (along with the activitys declaration).

<!--notificação -->
<service
    android:name=".FCM.FCMInstanceIdService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>
<service
    android:name=".FCM.FCMService" >
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

Next you will need to create the classes for the FCM (Firebase Cloud Messaging)

Fcminstanceidservice.java: to generate the device’s unique token. This write token, is to write to my own server, if do not use delete this method):

/**
 * Criado por Leonardo Figueiredo em 20/08/2018.
 */
public class FCMInstanceIdService extends FirebaseInstanceIdService {

public static String TAG = "FirebaseLog";
String refreshedToken;

@Override
public void onTokenRefresh() {
    super.onTokenRefresh();
    refreshedToken = FirebaseInstanceId.getInstance().getToken();
    gravaToken();
    Log.d(TAG, "Token: " + refreshedToken);
}

public void gravaToken() {
    TokenModel tokenModel = new TokenModel();
    tokenModel.setTokenDevice(refreshedToken);
    tokenModel.setSo("Android");

    Call<TokenModel> call = new RetrofitConfig().getApiCandidato().gravaToken(tokenModel.getTokenDevice(), tokenModel.getSo());
    call.enqueue(new Callback<TokenModel>()
    {
        @Override
        public void onResponse(Call<TokenModel> call, Response<TokenModel> response) {
            //sucesso
        }

        @Override
        public void onFailure(Call<TokenModel> call, Throwable t) {
            //falha
        }
    });
    }
}

Now you need the Fcmservice.java class: you are responsible for receiving and handling the notification.

/**
 * Criado por Leonardo Figueiredo em 20/08/2018.
 */
public class FCMService extends FirebaseMessagingService {

public static String TAG = "FirebaseLog";

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

    Log.v(TAG, "recebeu mensagem do firebase");

    //verifica se recebeu alguma notificacao
    if (remoteMessage.getNotification() != null) {
        String mensagem = remoteMessage.getNotification().getBody();

        Intent intent = new Intent(getBaseContext(), PrincipalActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, intent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext())
                .setContentTitle(String.valueOf(getResources().getString(R.string.app_name)))
                .setSmallIcon(R.drawable.ic_notificacao)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo_color))
                .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
                .setContentIntent(pendingIntent)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(mensagem))
                .setContentText(mensagem)
                .setAutoCancel(true);

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(99, builder.build());
        Log.d(TAG, "Menssagem: " + remoteMessage.getNotification().getBody());
    }
}
}

Now just go to your firebase console, go to the Zoom -> Cloud Messaging menu. If you want to send directly by your scrip, see this link step by step, so that Automatize and send by your script: https://gist.github.com/rolinger/d6500d65128db95f004041c2b636753a

Fill in the data and send it and be happy.

NOTE: Place a breakpoint in the Fcminstanceidservice class and check if it generated a hash, this is your device’s unique id (only happens the first time you install the App).

Before sending, place a breakpoint in the Fcmservice class, as this is where the message will arrive.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.