2
respostas

[Dúvida] Notificação quando agendada, não funciona

Olá boa noite. Espero que estejam bem.

Estou desenvolvendo um app para aprendizado, utilizando os conhecimentos que adquiri com alguns cursos da alura + coisas adicionadas pela documentação e me deparei com um problema.
Neste app, adicionei um agendademento de notificação. A idéia seria que no horário em que a pessoa salvou o lembrete, a notificação fosse exibida.
Porém, quando o horario chega, a notificação não é exibida.
Eu sei que a notificação está funcionando, pois para teste, coloquei um botão para que, quando acionado, disparasse a notificação através do método ".show()" do plugin de notificação. E nesta ação, a notificação é exibida.

Já adicionei as permissões no Android.Manifest, já alterei os canais, ja fiz de tudo, e a bendita notificação não é exibida.
Estou utilizando o pacote "flutter_local_notifications" e minhas dependencias no pubspec.yaml estão dessa forma:

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.8
  sqflite: ^2.4.2
  flutter_local_notifications: ^20.1.0
  timezone: ^0.10.1
  flutter_timezone: ^5.0.1
  permission_handler: ^12.0.1
  android_intent_plus: ^6.0.0
  shared_preferences: ^2.5.4

O código para agendamento da notificação é o seguinte:

  //Function to schedule a notification
  Future<void> scheduleNotification(String? title, String? body, {int id = 1, required int hour, required int minute}) async {
    //Get the date and time from device
    final dateAndTimeDevice = timeZone.TZDateTime.now(timeZone.local);
    //Set the time when notification will be schedule
    var notificationSchedule = timeZone.TZDateTime(
      timeZone.local,
      dateAndTimeDevice.year,
      dateAndTimeDevice.month,
      dateAndTimeDevice.day,
      hour,
      minute,
    );

    //Schedule the notification into the plugin
    await notificationPlugin.zonedSchedule(
      id: id,
      title: title,
      body: body,
      scheduledDate: notificationSchedule,
      notificationDetails: notificationDetails(isScheduled: true),
      androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle,
      matchDateTimeComponents: DateTimeComponents.time,
    );

    print(
      'Notification Scheduled for Notification $title at Date '
      '${dateAndTimeDevice.day}/${dateAndTimeDevice.month}/${dateAndTimeDevice.year} time $hour:$minute',
    );
  }

Alguém já passou por alguma situação parecida, que possa me ajudar?

2 respostas

Dei mais uma olhada na documentação da "flutter_local_notifications" e vi na seção de agendamentos que precisa adicionar os receivers no manifest.
Insira aqui a descrição dessa imagem para ajudar na acessibilidade
Porém ao tentar adicionar os receivers, dentro da tag application, é gerado um erro e o app não roda mais

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.res.LinkApplicationAndroidResourcesTask$TaskAction
   > Android resource linking failed
     ERROR: C:\LocalProjects\RAM\pos_senai\tcc\notes_reminders\build\app\intermediates\packaged_manifests\debug\processDebugManifestForPackage\AndroidManifest.xml:79: AAPT: error: unexpected element <receiver> found in <manifest><application><activity>.

     ERROR: C:\LocalProjects\RAM\pos_senai\tcc\notes_reminders\build\app\intermediates\packaged_manifests\debug\processDebugManifestForPackage\AndroidManifest.xml:82: AAPT: error: unexpected element <receiver> found in <manifest><application><activity>.


* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
> Get more help at https://help.gradle.org.

BUILD FAILED in 5s
Error: Gradle task assembleDebug failed with exit code 1

Alguém sabe como corrigir isso?

Aqui está o meu arquivo Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- PERMISSIONS-->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
    <!-- NOTE: the example app requests USE_EXACT_ALARM to make it easier to run the app.
         Developers will need to check if their own app needs to use SCHEDULE_EXACT_ALARM instead -->
    <uses-permission android:name="android.permission.USE_EXACT_ALARM" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <!-- NOTE: Special use was selected as it's the closest match for this example app.
         apps should specify the appropriate permission for their use cases. -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
    <!-- NOTE: This permission isn't needed by the local notification plugin. It is only being
         requested because the example app will download remote content to demonstrate some scenarios-->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />

    <application
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher"
        android:label="notes_reminders">
        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:exported="true"
            android:hardwareAccelerated="true"
            android:launchMode="singleTop"
            android:taskAffinity=""
            android:theme="@style/LaunchTheme"
            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. -->
            <receiver
                android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver"
                android:exported="false" />
            <receiver
                android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver"
                android:exported="false">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                    <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
                    <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                    <action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
                </intent-filter>
            </receiver>

            <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>
    <!-- Required to query activities that can process text, see:
         https://developer.android.com/training/package-visibility and
         https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.

         In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
    <queries>
        <intent>
            <action android:name="android.intent.action.PROCESS_TEXT" />
            <data android:mimeType="text/plain" />
        </intent>
    </queries>
</manifest>