Missing default Notification Channel metadata in AndroidManifest in Flutter - android

I am using firebase_messaging: ^5.0.1 package to achieve push notifications, everything is working fine in IOS whereas coming to the android when my mobile application running background I am receiving a notification but it is not navigating to the respective screens, it just opens the default screen. How to achieve navigation to that particular screen.
PS: I implemented click_action functionality that's the reason it's working fine in iOS but Android it shows the below message
W/FirebaseMessaging( 8260): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
Here is my AndroidManifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.check">
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<application
android:name="io.flutter.app.FlutterApplication"
android:label="Cargill FC"
android:icon="#mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:allowBackup="false"
android:fullBackupContent="false"
android:windowSoftInputMode="adjustResize">
<!-- This keeps the window background of the activity showing
until Flutter renders its first frame. It can be removed if
there is no splash screen (such as the default splash screen
defined in #style/LaunchTheme). -->
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Push notificatio code:
#override
void initState() {
super.initState();
tabController = new TabController(length: 2, vsync: this);
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
onFirebaseMessage(message);
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
_firebaseMessaging.requestNotificationPermissions(const IosNotificationSettings(sound: true, badge: true, alert: true));
_firebaseMessaging.onIosSettingsRegistered.listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
});
_firebaseMessaging.getToken().then(registerFirebaseTokenForUser);
}
Here onMessage is the only thing working perfectly in Android. I want to achieve the same when it is running background.

For those who are not able to find "string.xml", you can find it under: android>app>src>main>res>values. It is not the same as styles.xml. If you do not have one yet, you can create one:
Right click "values" folder,
Click New/Values Resource File
Copy, and paste the following text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="default_notification_channel_id" translatable="false">fcm_default_channel</string>
</resources>

Maksim has a pretty solid answer here including links to the official docs. You need to add a the following meta-data tag in you Manifest:
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
And in string.xml you can declare default_notification_channel_id in the following way:
<string name=“default_notification_channel_id”>Channel ID</string>
Then you must provide an attribute with that specific id when sending push notifications.
EDIT
It is possible to have multiple meta-data tags in your AndroidManifest.xml:
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>

Adding FLUTTER_NOTIFICATION_CLICK is required to be sent, for onResume and onLunch to be executed.
{
"notification": {...},
"click_action": "FLUTTER_NOTIFICATION_CLICK"
}
For my golang server, this meant adding the AndroidConfig
message := &messaging.Message{
Topic: topic,
Notification: &messaging.Notification{/* */}
Data: data,
APNS: &messaging.APNSConfig{/* */}
Android: &messaging.AndroidConfig{
Notification: &messaging.AndroidNotification{
ClickAction: "FLUTTER_NOTIFICATION_CLICK",
},
},
}

1- At first, add this meta code after </activity> tag in AndroidManifest.xml which located in path <flutter project path>/android/app/src/main/AndroidManifest.xml
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/notification_channel_id" />
Note: If you set this meta inside <activity> the code will not work.
2- Modify file (or create new file if not exists) in this path <flutter project path>/android/app/src/main/res/values/string.xml to be like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="default_notification_channel_id" translatable="false">fcm_default_channel</string>
</resources>
This will solve the problem Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
But after that, you need to create this channel in Android, to do that go to file <flutter project path>//android/app/src/main/kotlin/com/examble/project_name/Application.kt and add this function:
private fun createChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel
val name = getString(R.string.default_notification_channel_id)
val channel = NotificationChannel(name, "default", NotificationManager.IMPORTANCE_HIGH)
val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
Then call it from onCreate() function:
override fun onCreate() {
super.onCreate()
createChannel()
.........
}

Adding 'click_action': 'FLUTTER_NOTIFICATION_CLICK' to my notification's data solved this for me

If your flutter version is greater than 1.12 you don't need to create any file like Application.java or Application.kt just add the below meta value to you AndroidManifest file
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="high_importance_channel" />
Reference: https://firebase.flutter.dev/docs/messaging/overview/

Related

AndroidManifest build error when using flutter_local_notification: Flutter

I am working on a Flutter Application where I want to use the flutter_local_notifications with Firebase Cloud Messaging. When I added the following code to my main.dart-
#pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
await setupFlutterNotifications();
showFlutterNotification(message);
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
print('Handling a background message ${message.messageId}');
}
/// Create a [AndroidNotificationChannel] for heads up notifications
late AndroidNotificationChannel channel;
bool isFlutterLocalNotificationsInitialized = false;
Future<void> setupFlutterNotifications() async {
if (isFlutterLocalNotificationsInitialized) {
return;
}
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
'This channel is used for important notifications.', // description
importance: Importance.high,
);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
/// Create an Android Notification Channel.
///
/// We use this channel in the `AndroidManifest.xml` file to override the
/// default FCM channel to enable heads up notifications.
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
/// Update the iOS foreground notification presentation options to allow
/// heads up notifications.
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
isFlutterLocalNotificationsInitialized = true;
}
void showFlutterNotification(RemoteMessage message) {
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
if (notification != null && android != null && !kIsWeb) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channel.description,
icon: 'launch_background',
),
),
);
}
}
/// Initialize the [FlutterLocalNotificationsPlugin] package.
late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await Firebase.initializeApp();
// Set the background messaging handler early on, as a named top-level function
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
if (!kIsWeb) {
await setupFlutterNotifications();
}
I got an error-
android:exported needs to be explicitly specified for element <receiver#com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver>. Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined.
I read several posts and found out that I have to add android:exported="true" in AndroidManifest.xml. After adding-
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.blog_app">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:label="blog_app"
android:name="${applicationName}"
android:icon="#mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
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">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="#style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
But, I am still getting the same error after adding the exported property to the Manifest file. There is only MainActivity and no other component. Please help!
Did you check this ->
android:exported needs to be explicitly specified for element <receiver#com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver>
Flutter: Targeting S+ (version 31 and above) requires that an explicit value for android:exported be defined when intent filters are present]
there's also a video for same problem
https://www.youtube.com/watch?v=fma_umbAe6A
and a snippet
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver"
android:exported="true">
</receiver>
Hope it helps you

FirebaseMessagingService onMessageReceived not call when app is killed or app not launch

In normal case app is alive i received the notification and i display it.
{
"to" : "xxxx",
"notification": {
"body": "Hello",
"title" : "Hello world notification"
},
"data" : {
"data1" : "dddddd",
"data2" : "mmm"
}
}
<service
android:name=".notifications.MyFirebaseMessagingService"
android:directBootAware="true"
android:exported="false"
android:enabled="true"
android:stopWithTask="false"
>
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
Since severals days i search a solution to receive notification FCM when my app is not alive.
I try to
FirebaseMessagingService / stopWithTask
Create other service to manage FirebaseMessagingService
etc.
But i don't found a good way and good practice and technical solution.
Finally it not possible to receive notification when app if not alive?
what is the good way to keep app in background and not really killed app when the user swipe?
(i use API 29)
add this code in your Manifest file OnMessageRecive not call if App is background
refer this document
https://firebase.google.com/docs/cloud-messaging/android/topic-messaging
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_ic_notification" />
Well FYI, this method doesn't gets called when the app is in background or killed because The notifications are handled by Device OS when the app is in background or killed.
So if you do not want the notifications to be handled by Device OS and wants this method to be executed even in background and killed state then follow this:
First of all, make FCM service like this by removing all unwanted codes
<service android:name=".push.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Importantly, Make changes in your fcm json payload like this by removing notification object to make OnReceivedMethod work.
{
"to" : "xxxx",
"data" : {
"bodyText": "Hello",
"titleText" : "Hello world notification",
"data1" : "dddddd",
"data2" : "mmm",
}
}

Flutter onBackgroundMessage android myimage notification not working

Flutter firebase background notification I pushed the image notification but it's showing only text but if app open it's working fine but app terminated or minimize it's showing only default notification I tried everything but it doesn't work I referred this also https://pub.dev/packages/firebase_messaging no use.
check this image
background notification not showing that image?
Application.kt
package YOUR PACKAGE
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
import io.flutter.view.FlutterMain
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService
import com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin
class Application : FlutterApplication(), PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
FlutterFirebaseMessagingService.setPluginRegistrant(this);
FlutterMain.startInitialization(this)
}
override fun registerWith(registry: PluginRegistry?) {
if (!registry!!.hasPlugin("io.flutter.plugins.firebasemessaging")) {
FirebaseMessagingPlugin.registerWith(registry!!.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
}
if (!registry!!.hasPlugin("com.dexterous.flutterlocalnotifications")) {
FlutterLocalNotificationsPlugin.registerWith(registry!!.registrarFor("com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin"));
}
}
}
MainActivity.kt
package YOUR PACKAGE
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="YOUR PACKAGE"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:name=".Application"
android:label="APP_NAME"
android:icon="#drawable/home_logo"
tools:replace="android:label">
<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">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="#style/NormalTheme"
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<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 below to ensure we get the payload when tapping on a notification -->
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
main.dart
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print('on message $message');
showNotification(message);
},
onBackgroundMessage: Platform.isIOS
? null
: myBackgroundMessageHandler,
onResume: (Map<String, dynamic> message) async {
print('on resume $message');
showNotification(message);
},
onLaunch: (Map<String, dynamic> message) async {
print('on launch $message');
showNotification(message);
},
);
myBackgroundMessageHandler method in same main.dart
static Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
final notification = message['notification'];
final data = message['data'];
print(notification);
}
Firebase send notification json Rest API
#header:
Content-Type:application/json
Authorization:key=YOUR FIREBASE SERVER KEY
#body -> raw
{
"notification":{
"title":"Plan Expired",
"body":"Your plan has expired please upgrade your plan today"
},
"data": {
"image":"https://i.ytimg.com/vi/zZ72Ujn8Rfw/maxresdefault.jpg"
},
"to":"NOTIFICATION TOKEN"
}
To show images you may need to use image tag inside notification in your Firebase send notification json Rest API. The below code worked for me.
{
"notification":{
"title":"Plan Expired",
"body":"Your plan has expired please upgrade your plan today",
"image":"https://imgsv.imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg"
}
"to":"NOTIFICATION_TOKEN"
}

Flutter: Schedule notification not working

I am developing a app using Flutter.
To show notification I an using flutter_local_notifications package.
I am getting notification, but schedule notification is not working.
Similar question was asked here How do I schedule a notification in Flutter?, but my receiver is already inside the application tag.
Here is my manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.folk.gayatrimonitor">
<!-- The INTERNET permission is required for development. Specifically,
flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<application
android:name="io.flutter.app.FlutterApplication"
android:label="gayatri_monitor"
android:icon="#mipmap/ic_launcher">
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- This keeps the window background of the activity showing
until Flutter renders its first frame. It can be removed if
there is no splash screen (such as the default splash screen
defined in #style/LaunchTheme). -->
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
adding this inside application of your manifest might solve your problem
<service android:name="com.folk.localnotifications.services.LocalNotificationsService"
android:exported="false" />
Remember: com.folk is used for this project only. For different project, go to your manifest, see package name and edit accordingly.
I had the same problem but couldn't find the solution online, however, later I did figure out running flutter clean then flutter run seems to do the trick for me.
You have to essentially clean your build and rebuild it again. Hope that helps.
I had the same issue, I solved it by creating a separate notification channel for each android notification I was issuing, even if they share the same priority.
In my case, I just added the following inside initState()
var initializationSettingsAndroid =
AndroidInitializationSettings('#mipmap/ic_launcher');
var initializationSettingsIOS = IOSInitializationSettings();
var initializationSettings = InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(
initializationSettings,
);

Firebase Cloud Messaging: How to set the notification icon on android?

I am having trouble setting the notification icon on android studio.
I set up the drawable folder like so:
And I've also set the default icon in my AndroidManifest.xml file:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/notification_icon" />
And here I'm setting the icon field to notification_icon: https://developers.google.com/cloud-messaging/http-server-ref#downstream-http-messages-json (p.s. I'm aware that's GCM, but it works. I'm receiving the notification with everything besides the icon)
What am I missing? All I see is a white square inside a grey circle.
This is my backend code: Pushex.push(%{title: user.name, body: "message goes here", badge: 1, sound: "default", icon: "notification_icon"}, to: user.fcm_token, using: :gcm) (https://github.com/tuvistavie/pushex)
Fixed it... this is so stupid. Was inspired by this answer:
https://stackoverflow.com/a/28387744/1555312
I made my notification icon my app icon:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#mipmap/ic_launcher" />
And then the magic line in android/app/build.gradle...
defaultConfig {
targetSdkVersion 20 // this has to be < 21
...
}
Hope I save hours of someone else's life
With SDK 9.8.0 however, you can override the default! In your AndroidManifest.xml you can set the following fields to customise the icon and color:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/notification_icon" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/google_blue" />
and
<manifest>
<application
android:icon="#drawable/icon"
android:label="#string/app_name">
<!-- Add your meta-data here-->
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Check this code. It may help you.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent = new Intent(getApplicationContext(), YourClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), NotificationID.getID(), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(getNotificationIcon())
.setContentTitle(remoteMessage.getData().get("title"))
.setContentText(remoteMessage.getData().get("body"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getData().get("body")))
.setContentIntent(contentIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NotificationID.getID(), notificationBuilder.build());
}
private int getNotificationIcon() {
boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
//If the build version is higher than kitkat we need to create Silhouette icon.
return useWhiteIcon ? R.mipmap.ic_notification : R.mipmap.ic_launcher;
}
public static class NotificationID {
private static final AtomicInteger c = new AtomicInteger(0);
public static int getID() {
return c.incrementAndGet();
}
}
}
If the build version is higher than kitkat we need to create Silhouette icon. For that online tool is available
Refer:https://romannurik.github.io/AndroidAssetStudio/icons-notification.html
I am using the FCM plugin and here is what worked for me (September 2019):
In config.xml (yourapp/config.xml)
Add the following to the tag at the end
xmlns:android="http://schemas.android.com/apk/res/android"
It should look something like this now:
<widget id="com.mydomain.app" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
Or simply, copy the above line, replace the value of widget id, with your own.
In the same config.xml file:
Just before the tag corresponding to , add this:
<config-file parent="/manifest/application/" target="app/src/main/AndroidManifest.xml">
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="#drawable/fcm_push_icon" />
</config-file>
Visit the following link:
Notification Icon Generator
Upload a White version (single color) of your logo on a Transparent background. If you upload a colored version, you will get a dark gray icon, which would look nasty. If you don't have a white version of your logo, get it designed. Leave the rest of the settings as they are. For the Name textbox value, enter: fcm_push_icon. Then click on the Blue colored round shaped button to download the zip file.
Unzip the zip file that you just downloaded it the above step and extract its contents to a folder. You will notice that it contains a res folder. If you open this folder, it will contain other folders with the following names:
drawable-hdpi
drawable-mdpi
drawable-xhdpi
drawable-xxhdpi
drawable-xxxhdpi
Each of those folders will contain a PNG icon by the name "fcm_push_icon.png". The only difference between the icons in those different folders is their size.
Open the following file path in your app (If it doesn't exist, create it as shown below):
yourApp/platforms/android/app/src/main/res
Simply copy all the 5 folders listed in in the point 4 above, to the location shown just above i.e. into the res folder i.e. into yourApp/platforms/android/app/src/main/res
That's it! Now just build your app. Whenever you receive a notification, you will see your app icon in the notifications (at least on Android).
If anyone has figured out how to make colored icons appear in the Android notifications, please share your solution.

Categories

Resources