·

Engenharia de Controle e Automação ·

Linguagens de Programação

Envie sua pergunta para a IA e receba a resposta na hora

Fazer Pergunta

Recomendado para você

Texto de pré-visualização

Valentim Realinho 1 Computação Móvel Mobile Computation 202324 Firebase Cloud Messaging The aim of this work is to explore the Flutter plugin to use the Firebase Cloud Messaging FCM API available at httpspubdevpackagesfirebasemessaging With this plugin you can receive and process push notifications as well as data messages on Android and iOS devices Read about Firebase FCM messages to learn more about the differences between notification messages and data messages This plugin contains a set of classes whose documentation can be found at httpspubdevdocumentationfirebasemessaginglatest Below is a summary of the steps necessary to build an application capable of receiving push messages without eliminating the need to read the documentation so that you can develop an application that allows you to receive messages Create a new Android application in Firebase In the Firebase console add an Android application to a project If you dont have any created project create one first and add the Android application following the wizard Valentim Realinho 2 Create a new Android Flutter project 1 Create a new Flutter project with the name mimessaging 2 Execute the steps available in Add Firebase to a Flutter AppPDF 3 In your Flutter project directory run the following commands to install Firebase Cloud Messaging plugin flutter pub add firebasemessaging flutterfire configure 4 Execute the App to ensure that everything stills runs Receive Notifications Messages are sent to the Flutter application via the onMessage callback onMessage runs when the application is open and running in the foreground The onMessage callback is called when the application is running in the foreground When the notification is received in the foreground the application is open we can manipulate it with one of Flutters builtin widgets Create a class to store messages that are received messagedart import packagefluttermaterialdart immutable class Message final String title final String body Valentim Realinho 3 const Messagethistitle thisbody Create a class to represent a message in a Widget messagelistentrydart import packagefluttermaterialdart class MessageListEntry extends Container MessageListEntry String who String message bool me Key key super key key padding const EdgeInsetsall8 child Row mainAxisAlignment me MainAxisAlignmentend MainAxisAlignmentstart children Expanded child Column crossAxisAlignment CrossAxisAlignmentstart children Container padding const EdgeInsetsonlybottom 8 child Text who style const TextStyle fontWeight FontWeightbold Text message style TextStyle color Colorsgrey500 Finally replace the maindart file code with the following maindart import packagefluttermaterialdart import packagefirebasecorefirebasecoredart import packagefirebasemessagingfirebasemessagingdart import firebaseoptionsdart import messagedart import messagelistentrydart Futurevoid main async WidgetsFlutterBindingensureInitialized await FirebaseinitializeApp options DefaultFirebaseOptionscurrentPlatform Valentim Realinho 4 runAppMyApp class MyApp extends StatelessWidget final String appTitle ESTG Instant Messaging override Widget buildBuildContext context MaterialApp title appTitle home MainPageappTitle class MainPage extends StatelessWidget final String appTitle const MainPagethisappTitle superkey override Widget buildBuildContext context Scaffold appBar AppBartitle TextappTitle body MessagingWidget class MessagingWidget extends StatefulWidget const MessagingWidgetsuperkey override MessagingWidgetState createState MessagingWidgetState class MessagingWidgetState extends StateMessagingWidget final FirebaseMessaging messaging FirebaseMessaginginstance final ListMessage messages final TextEditingController textEditingController TextEditingController final ScrollController listScrollController ScrollController String token Futurevoid setup async NotificationSettings settings await messagingrequestPermission alert true announcement false badge true carPlay false criticalAlert false provisional false sound true FirebaseMessagingonMessagelistenRemoteMessage message if messagenotification null setState messagesadd Messagemessagenotificationtitle messagenotificationbody Subscribe a topic called all messagingsubscribeToTopicall Valentim Realinho 5 messaginggetTokenthentoken token token override void initState superinitState setup override Widget buildBuildContext context final ListMessageListEntry list messagesmapmessage String who token messagetitle I said Someone said return MessageListEntrywho messagebody messagetitle token toList return SafeArea child Column children Widget Flexible child ListView padding const EdgeInsetsall120 controller listScrollController children list Try running your application The final appearance should be as shown in the following figure Valentim Realinho 6 Send Notifications See the Firebase Cloud Messaging documentation for full details on sending messages to your app A notification or data message can be sent from a terminal using curl To do this install curl if you havent already installed it and create the sendbat file with the following content You must replace the servertoken with one generated in the Firebase console SET DATAnotification body Hello worldtitle ESTG Messagingpriority high data clickactionFLUTTERNOTIFICATIONCLICK id 1status doneto topicsall curl httpsfcmgoogleapiscomfcmsend H Content Typeapplicationjson X POST d DATA H Authorizationkeyservertoken To generate the servertoken in the Firebase Console go to the Project Settings that was created select the Cloud Messaging tab and do Add Server Key You can also send messages from a Flutter application using the http package void sendNotificationtitle body async await httppost Uriparsehttpsfcmgoogleapiscomfcmsend headers String String ContentType applicationjson Authorization keyservertoken body jsonEncode String dynamic notification String dynamicbody body title title priority high data String dynamic clickaction FLUTTERNOTIFICATIONCLICK id 1 status done to topicsall Valentim Realinho 7 Exercise The application as it stands only allows you to receive messages Make the necessary changes to be able to send messages as illustrated in the following figure