I am too late to answer this question but finally, I have achieved this with some android native code and of course flutter code. So, let starts from scratch step by step
1.) Go to your build.gradle file (PATH android>app>buid.gradle
). Add the firebase messaging dependency and after that sync the file from android studio
implementation 'com.google.firebase:firebase-messaging'
2.) Make a new file name MyApplication.java in the MainActivity file path (PATH android>app>src>main>kotlin>com>yourpackage>MyApplication.java
)
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
import io.flutter.plugins.pathprovider.PathProviderPlugin;
public class MyApplication extends FlutterApplication implements PluginRegistry.PluginRegistrantCallback {
@Override
public void onCreate() {
super.onCreate();
this.createChannel();
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}
@Override
public void registerWith(PluginRegistry registry) {
io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
PathProviderPlugin.registerWith(registry.registrarFor("io.flutter.plugins.pathprovider.PathProviderPlugin"));
}
private void createChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String name = getString(R.string.default_notification_channel_id);
NotificationChannel channel = new NotificationChannel(name, "default", NotificationManager.IMPORTANCE_HIGH);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
}
}
3.) Go to your android app manifest file (PATH android>app>src>main>AndroidManifest.xml
) and add replace the <application android:name with ".MyApplication"
tag with this
<application
android:name=".MyApplication" //replace your name with .MyApplication
android:label="helpwise"
android:icon="@mipmap/ic_launcher">
4.) Now you need to add the firebase messaging dependency in the flutter project. So add in the pubspec.yaml
firebase_messaging: ^6.0.9
5.) Add the firebase code in your main.dart file
Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
if (message.containsKey('data')) {
final dynamic data = message['data'];
print('Notification data is ');
print(message['data']);
}
if (message.containsKey('notification')) {
// Handle notification message
final dynamic notification = message['notification'];
}
}
class SelectMailbox extends StatefulWidget {
static const routeName = '/mailbox-screen';
@override
_SelectMailboxState createState() => _SelectMailboxState();
}
class _SelectMailboxState extends State<SelectMailbox> {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
@override
void initState() {
_firebaseMessaging.getToken().then((token) async{
SharedPreferences preferences = await SharedPreferences.getInstance();
final String userData = preferences.get('userData');
final String authToken=jsonDecode(userData)['token'];
print("Device token is $token"); //I will use this token to send notif.
await http.post("https://your_domain/mobile/save-token",
headers: {"Content-Type": "application/json"},
body: jsonEncode({"device_token": token,"type":"android","token":authToken}));
});
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
//
}, onBackgroundMessage: Platform.isAndroid?myBackgroundMessageHandler:null,
onResume: (Map<String, dynamic> message) async {
print("onBackground Message $message");
_selectIdsNotification(message['data']['thread_id'],message['data']['mailbox_id'],14,message['data']['mailboxType'],"All",context);
}, onLaunch: (Map<String, dynamic> message) async {
print("onLaunch Message $message");
_selectIdsNotification(message['data']['thread_id'],message['data']['mailbox_id'],14,message['data']['mailboxType'],"All",context);
});
super.initState();
}
_selectIdsNotification(threadID,mailboxId,subBox,mailboxType,mailboxTab,myContext) async {
// YOU CAN ADD THE LOGIC OF DIFFERENT PAGE ROUTE ACCORDING TO DATA PASS FROM NOTIFICATION in my case i could use the mailboxType
Navigator.push(
myContext,
MaterialPageRoute(
builder: (context) => ThreadDetail(threadID, mailboxType,notificationMailboxId: mailboxId),
),
);
}
6.) Again go to your AndoridManifest.file and add the intent filter code inside the activity tag and metadata tag code after the activity close tag
<application
android:name=".MyApplication"
android:label="helpwise"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<-- ADD THIS INTENT FILTER IN YOUR CODE -->
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<-- ADD THIS META DATA TAG IN YOUR CODE -->
<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
</application>
7.) Now go to the android value folder PATH(android>app>src>main>res>values>strings.xml
). If you do not see the file of strings.xml then create a file on the same path with the strings.xml file and add the code below
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="default_notification_channel_id">default_notification_channel_id</string>
</resources>
10.) That's its guys. Now, you need to restart the app and call the firebase messaging notification API to the device token.
ar axios = require('axios');
var data = JSON.stringify(
{
"to": "your_mobile_device_token",
"data": {
"mailbox_id": "11111",
"thread_id": "1111",
"mailboxType": "email",
"click_action": "FLUTTER_NOTIFICATION_CLICK"
},
"priority": "high",
"notification": {
"body": "Hi, You have received new Message",
"title": "Flutter",
"image": "your_image_cdn_path"
},
"click_action": "FLUTTER_NOTIFICATION_CLICK"
});
var config = {
method: 'post',
url: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Authorization': 'key=your_firebase_server_key',
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});