6
votes

I currently working on flutter notification using firebase messaging, i couldn't receive any notification. I send the notification via server using curl, however i can get it work in native android app (Android Studio) but not in flutter, any help would be appreciated. Below is my code.

Flutter Notification code

class FirebaseNotifications {
FirebaseMessaging _firebaseMessaging;

void setUpFirebase() {
_firebaseMessaging = FirebaseMessaging();
firebaseCloudMessaging_Listeners();
}

void firebaseCloudMessaging_Listeners() {
if (Platform.isIOS) iOS_Permission();

_firebaseMessaging.getToken().then((token) {
  print(token);
});

_firebaseMessaging.configure(
  onMessage: (Map<String, dynamic> message) async {
    print('on message $message');
  },
  onResume: (Map<String, dynamic> message) async {
    print('on resume $message');
  },
  onLaunch: (Map<String, dynamic> message) async {
    print('on launch $message');
  },
);
}

void iOS_Permission() {
_firebaseMessaging.requestNotificationPermissions(
    IosNotificationSettings(sound: true, badge: true, alert: true));
_firebaseMessaging.onIosSettingsRegistered
    .listen((IosNotificationSettings settings) {
  print("Settings registered: $settings");
});
}
}

Android Studio code

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Map<String, String> params = remoteMessage.getData();

    JSONObject object = new JSONObject(params);

    showNotification(remoteMessage);
}

private void showNotification(RemoteMessage remoteMessage) { 
Map data = remoteMessage.getData();

String mesg = "New Notification";

Intent intent;
    PendingIntent pendingIntent;
    NotificationCompat.Builder builder;

    Intent i = new Intent(this,MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(id, name, importance);
        mChannel.setDescription(description);
        mChannel.enableLights(true);
        mChannel.setLightColor(Color.GREEN);
        mChannel.enableVibration(true);
        mChannel.setVibrationPattern(new long[]{0, 250, 250, 250});
        mNotificationManager.createNotificationChannel(mChannel);

        builder = new NotificationCompat.Builder(this, id);

        intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        builder.setContentTitle(data.get("title").toString())  // required
                //.setStyle(new 
 NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification()
.getBod 
y().toString()))
                .setStyle(new 
NotificationCompat.BigTextStyle().bigText(mesg)) //custom data
                .setSmallIcon(R.drawable.ic_stat_notification_icon4) // 
required

                .setContentText(mesg) // custom data
                .setWhen(System.currentTimeMillis())
                .setDefaults(Notification.DEFAULT_ALL)

.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setVibrate(new long[]{0, 250, 250, 250});
    }
}

Server side code

function sendtoUser($sendingTarget, $acc_name, $type_message, 
$type_of_transaction, $check_amount)
{

#API access key from Google API's Console
$API_ACCESS_KEY = "adazxc";
$registrationIds = $sendingTarget;
#prep the bundle

$fields = array(
    'to'        => $registrationIds,
    'data' => array(
        'title' => 'my title',
        'keyValue' => true,
        'receiverName' => $acc_name,
        'transType' => $type_of_transaction,
        'totalAmount' => $check_amount
    ),
);

$headers = array(
    'Authorization: key=' . $API_ACCESS_KEY,
    'Content-Type: application/json'
);
#Send Reponse To FireBase Server
$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, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
}

EDIT

I somehow can receive notification but i noticed that my status bar not receiving the notification but it is printed in the console, however, when i close the app i can get the notification. So how do i able to receive notification in both situation?

4
@androidnewbielearnerI have the same problem, you saw solve? - Edeson Bizerril

4 Answers

4
votes

data tag only for transferring more information to app, like where it has to redirect, image etc.. you have to add notification tag to display notification on status bar.

its seems you havent added notification content, please refer below sample message and configure same, it'll work

{
   "notification": {
      "body": "body",
      "title": "title"
   },
   "priority": "high",
   "data": {
      "click_action": "FLUTTER_NOTIFICATION_CLICK",
      "id": "1",
      "status": "done",
      "image": "https://ibin.co/2t1lLdpfS06F.png",
   },
   "to": <fcm_token>
}
2
votes

Some checks (Version numbers may change):

  • Add google-services.json (Download from firebase console) to android/app/

In android/build.gradle:

  • Add google() to repositories
  • Add classpath 'com.google.gms:google-services:4.2.0' to dependencies

In android/app/build.gradle:

  • Add implementation 'com.google.firebase:firebase-messaging:18.0.0' to dependencies
  • Add apply plugin: 'com.google.gms.google-services' at the end
  • Have the applicationId the same like package_name in the google-services.jon
1
votes

For what it's worth, I had an issue with receiving onMessage notifications today (didn't try onResume or onLaunch) when it was working fine yesterday. No errors in the Functions logs and tokens were all the same.

Try restarting your device -- this seems to be the most consistent way to fix this if your functions were previously working.

Also, if the messaging seems slow at first, this may be due to cold starting when you aren't using the functions for a while (see this SO question for a bit more information).

-2
votes

You may miss manual configuration for android (as well as ios if required), refer below link

http://myhexaville.com/2018/04/09/flutter-push-notifications-with-firebase-cloud-messaging/