I have recently Implemented the flutter_local_notifications and the notification is working fine. But there's one problem is that the notification doesn't show as pop up by default. The option is disabled by default in the notification settings.
My code like this :
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
ServiceContainer.initialize(Injector());
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
await PreferenceHelper.create();
FirebaseMessaging messaging = FirebaseMessaging.instance;
await messaging.requestPermission(
alert: true,
badge: true,
sound: true,
provisional: false,
);
await FirebaseMessaging.instance.requestPermission();
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(statusBarColor: Colors.transparent));
runApp(const App());
await [Permission.storage, Permission.notification].request();
}
You need to request for notification permissions
Requesting permissions on Android 13 or higher
From Android 13 (API level 33) onwards, apps now have the ability to display a prompt where users can decide if they want to grant an app permission to show notifications. For further reading on this matter read https://developer.android.com/guide/topics/ui/notifiers/notification-permission. To support this applications need target their application to Android 13 or higher and the compile SDK version needs to be at least 33 (Android 13). For example, to target Android 13, update your app's build.gradle file to have a targetSdkVersion of 33. Applications can then call the following code to request the permission where the requestPermission method is associated with the AndroidFlutterLocalNotificationsPlugin class (i.e. the Android implementation of the plugin)
This is how you do it.
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>().requestPermission();
Related
I am using notifee to create notifications in a react native app. I noticed, by default notifications get blocked by android (See under Settings->Apps->My App). Do I have to set the permission somewhere in my app?
When I enable notifications in the Apps-Settings, they work fine, but I'd like them to be enabled when installing the apk.
Yes, You have to explicitly request notifications permission if you targets Android 13.
Paste the following line in AndroidManifest.xml:
<uses-permission android:name="android.permission.POST_NOTIFICATION"/>
And then in your app:
import { PermissionsAndroid } from 'react-native'
const requestNotificationPermission = async () => {
try {
await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATION
)
} catch (err) {
if (_DEV_) console.warn('requestNotificationPermission error: ', err)
}
}
Permission could be named "POST_NOTIFICATION" or "POST_NOTIFICATIONS", depending on your RN version.
In my project, I was using flutter 3.0.3. Once I updated to 3.0.4 and updated dependencies, suddenly when I launched the app on android, the splash screen is showing continuously(never going to the main app). I tried by moving to my previous commit, downgrading flutter but to no avail.
This happened before but I luckily fixed it by upgrading kotlin jdk to 8(was 7 before).
I am using flutter_native_splash library. But it looks it doesn't have any impact on my project.
This question talks about only release mode. But, in my case it is happening both release and debug modes. I would really appreciate your help on this!
My main function:
void mainCommon() {
WidgetsFlutterBinding.ensureInitialized();
SentryFlutter.init(
(options) => options.dsn = Config.sentryDsn,
appRunner: () async {
await Firebase.initializeApp();
await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
final GlobalKey<ScaffoldMessengerState> messengerKey = GlobalKey<ScaffoldMessengerState>();
await BlocOverrides.runZoned(
() async => App(
api: Api(Config.grpcChannel),
database: await Config.db,
appDirectory: await getApplicationDocumentsDirectory(),
notificationManager: await NotificationManager.init(Config.grpcChannel),
messengerKey: messengerKey,
),
blocObserver: AppBlocObserver(errorCallback: BlocErrorHandler(messengerKey).errorCallback),
);
},
);
}
This is not for all cases. But, upgrading firebase_core and firebase_messaging could solve for some cases. In my case, it solved the problem for the first. But, once I upgraded all my other packages, it occurred again.
Android studio sucks. When I used Visual Studio Code, the exception was thrown in main where I initialised firebase. But in android, it ignored exception so I wasted a lot of time finding where the problem was.
To see the error in Android studio, you need to get mainCommon in try/catch bloc:
try {
await Firebase.initializeApp();
await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
runApp(App(
api: Api(Config.grpcChannel),
database: await Config.db,
appDirectory: await getApplicationDocumentsDirectory(),
notificationManager: await NotificationManager.init(Config.grpcChannel),
));
} catch (e) {
logger.e("Got exception in mainCommon: $e");
rethrow;
}
My project heavily relies on push notifications or FCM messages for VoIP & messaging features. The issues is these notifications aren't being received by any device when sending a cloud-messaging test message.
Project on Github to view code directly (excluding GoogleServices files): Github Here
Creating a fresh flutter project + firebase project, I performed the following steps:
Create Flutter project, using com.company.pushnotifications + add firebase & messaging deps (ref)
Created a Firebase project
Create Android Firebase App, download GoogleServices.json and place into android/app folder + add required android/build.gradle + android/app/build.gradle plugins (source)
Create iOS Firebase App, download GoogleService-Info.plist, copy into Runner folder using Xcode specifically.
Configure iOS app identity + provisioning profile + APNS key (installed into Firebase Cloud Messaging) with Push notifications + enable Background (fetch + notification) capabilities & push notifications capabilities
do not swizzle notifications by adding the following to the Info.plist file:
Info.plist file:
FirebaseAppDelegateProxyEnabled -> NO (Boolean)
edit ios/Runner/AppDelegate.swift with the following content:
AppDelegate.swift content:
import UIKit
import Flutter
import Firebase // added this line
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
FirebaseApp.configure() //add this
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
Setup firebase messaging with the following flutter code:
I'm debugging with breakpoints in background & foreground messages, left it for 2 hours incase the messages were delayed but on not one of the debugging sessions did a breakpoint trigger indicating a message was received
main.dart file:
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// 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.
await Firebase.initializeApp(); // breakpoint for debugging placed here
print("Handling a background message: ${message.messageId}");
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
FirebaseApp defaultApp = await Firebase.initializeApp();
// source: https://firebase.flutter.dev/docs/messaging/usage#background-messages
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
// source: https://firebase.flutter.dev/docs/messaging/usage#foreground-messages
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Got a message whilst in the foreground!'); // breakpoint for debugging placed here
print('Message data: ${message.data}');
if (message.notification != null) {
print('Message also contained a notification: ${message.notification}');
}
});
runApp(MyApp());
}
When sending a test push notification using Cloud Messaging Test notifications, I expect the notification to show on Android (emulated or physical atleast), but it does not show on either iOS or Android (emulated or physical).
To my knowledge I've followed the documentation as required - did I miss something or is something broken?
React Native project with push notifications, I use this.
I follow this tutorial.
I only need local notifications. But if I run this project I get an error default firebaseapp is not initialized in this process.
I follow this answer and get a google service.json from firebase to make it start (notification don't show up unfortunately). But is this also possible without firebase?
requestPermissions: Platform.OS === 'ios', This line you have to add
import { Platform} from 'react-native';
PushNotification.configure({
onRegister: function (token) {
console.log("TOKEN:", token);
},
onNotification: function (notification) {
console.log("NOTIFICATION:", notification);
},
permissions: {
alert: true,
badge: true,
sound: true,
},
popInitialNotification: true,
requestPermissions: Platform.OS === 'ios',// This line you have to add //import Platform from react native
});
This package does work without firebase, after installing and setting up clear gradle cache.
On Windows:
gradlew cleanBuildCache
On Mac or UNIX:
./gradlew cleanBuildCache
Yes, it is possible to push local notification without firebase. I implemented it in one of my projects. You can take reference from this comment.
And also you don't have to call register methods from example which is available in react-native-push-notifications repo.
PS: As author did not marked any of the above answers as resolved. I hope this will work.
I have a NodeJS Server and when my React Native app receive a Push Notification from the Server, the app stop working.
In the Emulator the app just close and in the Cellphone with a Release APK isntalled the app close and show an alert saying that the application stop working.
Here I can show some configuration I added in my Android Application
android/build.gradle
classpath 'com.android.tools.build:gradle:3.1.3'
classpath 'com.google.gms:google-services:4.0.1'
build.gradle
implementation project(':react-native-firebase')
implementation 'com.google.android.gms:play-services-base:15.0.1'
implementation 'com.google.firebase:firebase-core:16.0.1'
implementation 'com.google.firebase:firebase-messaging:17.1.0'
Notifications Listeners
export const configureMessaging = async () => {
try {
const enabled = await FirebaseMessaging.hasPermission();
log('Push Notifications enabled?', enabled);
return enabled;
} catch (err) {
return false;
}
}; // This is returning true
export const configureOnNotificationDisplayed = () => FirebaseNotifications.onNotificationDisplayed((notification) => {
// Process your notification as required
// ANDROID: Remote notifications do not contain the channel ID.
// You will have to specify this manually if you'd like to re-display the notification.
console.log(notification);
});
export const configureOnNotification = () => FirebaseNotifications.onNotification((notification) => {
// Process your notification as required
console.log(notification);
});
export const configureOnNotificationOpened = () => FirebaseNotifications.onNotificationOpened((notificationOpen) => {
// Get the action triggered by the notification being opened
// Get information about the notification that was opened
console.log(notification);
});
I attached a debugger in the AVM and no error was throw
Connected to the target VM, address: 'localhost:8624', transport:
'socket'
Disconnected from the target VM, address: 'localhost:8624',
transport: 'socket'
Note
I do not know what happened in iOS because the app is not configured
to use iOS
The problem was that I had another dependency that was using the Push Notifications. I removed it and everything works perfect