flutter 的本地通知仅适用于模拟器,但不适用于真正的 Android 设备?

问题描述 投票:0回答:1

我正在实现三个按钮(5、10 和 15 分钟),这些按钮应该为用户安排未来的通知。例如。当他们点击 5 分钟时,无论如何,5 分钟后都会弹出一条通知,其中包含一条消息。我正在使用本地通知包来进行颤动。我发现我可以让它在许多模拟器上很好地工作,但是,当我在真正的 Android 设备上尝试它时,它根本不起作用。通知不会弹出。

这是我使用的代码,如果有任何问题请告诉我,或者我需要如何修复它才能在真正的 Android 设备上工作:

 import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_timezone/flutter_timezone.dart';
import 'package:rxdart/rxdart.dart';
import 'package:timezone/data/latest_all.dart';
import 'package:timezone/timezone.dart';

class NotificationApi {
static final _notifications = FlutterLocalNotificationsPlugin();
static final onNotifications = BehaviorSubject<String?>();

static bool notificationPermission = true;

static Future _notificationDetails() async {
    return const NotificationDetails(
        android: AndroidNotificationDetails(
            'channelID',
            'channelName',
            channelDescription: 'channelDescription',
            importance: Importance.high, // Set the importance to high
            priority: Priority.high, // Set the priority to high
            playSound: true,
        ),
    );
}

static Future init({bool initScheduled = false}) async {
    const AndroidInitializationSettings android =
        AndroidInitializationSettings('@mipmap/ic_launcher');
    const InitializationSettings settings =
        InitializationSettings(android: android);

    final details = await _notifications.getNotificationAppLaunchDetails();
    if (details != null && details.didNotificationLaunchApp) {
        onNotifications.add(details.notificationResponse?.payload);
    }

    await _notifications.initialize(settings,
        onDidReceiveNotificationResponse: ((payload) async {
            onNotifications.add(payload.payload);
        }));

    if (initScheduled) {
        initializeTimeZones();
        final timeZoneName = await FlutterTimezone.getLocalTimezone();
        setLocalLocation(getLocation(timeZoneName));
    }
}

static Future<bool?> checkNotificationPermissions() async {
    if (Platform.isAndroid) {
        await _notifications
            .resolvePlatformSpecificImplementation<
                AndroidFlutterLocalNotificationsPlugin>()
            ?.requestPermission();
        return await _notifications
            .resolvePlatformSpecificImplementation<
                AndroidFlutterLocalNotificationsPlugin>()
            ?.areNotificationsEnabled();
    }
    return null;
}

static void showScheduledNotification({
    required int id,
    String? title,
    String? body,
    String? payload,
    required DateTime scheduledDate,
}) async =>
    _notifications.zonedSchedule(id, title, body,
        TZDateTime.from(scheduledDate, local), await _notificationDetails(),
        androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
        uiLocalNotificationDateInterpretation:
            UILocalNotificationDateInterpretation.absoluteTime,
        payload: payload);

static void cancel(int id) => _notifications.cancel(id);
static void cancelAll() => _notifications.cancelAll();
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
    return MaterialApp(
        home: HomePage(),
    );
}
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
bool _notificationPermission = true;

@override
void initState() {
    super.initState();

    WidgetsBinding.instance!.addPostFrameCallback((_) async {
        await NotificationApi.init(initScheduled: true);
        _listenNotifications();
        NotificationApi.checkNotificationPermissions().then((value) {
            setState(() {
                _notificationPermission = value ?? true;
            });
        });
    });
    }

@override
void dispose() {
    NotificationApi.onNotifications.close();
    super.dispose();
}  

Future<void> _requestNotificationPermission() async {
    final bool? result = await NotificationApi.checkNotificationPermissions();
    if (result != null && !result) {
        setState(() {
            _notificationPermission = false;
        });
        // Handle the case where the user has not granted notification permissions
    }
    }

void _scheduleNotification(int minutes) {
    final scheduledDate = DateTime.now().add(Duration(minutes: minutes));
    NotificationApi.showScheduledNotification(
        id: minutes,
        scheduledDate: scheduledDate,
        title: 'Time is up',
        body: 'This is the notificaiton message that needs to be displayed.',
    );

    ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text('Notification scheduled for $minutes minutes.'),
        ),
    );
    }

void _listenNotifications() =>
    NotificationApi.onNotifications.stream.listen((payload) {
        // Handle notification payload, if needed
        print('Notification payload: $payload');
    });

@override
Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: const Text('Local Notification Page'),
        ),
        body: Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                    ElevatedButton(
                        onPressed: () async {
                            await _requestNotificationPermission();
                            _scheduleNotification(5);
                        },
                        child: const Text('Schedule notification message in 5 Minutes'),
                    ),
                    SizedBox(height: 16),
                    ElevatedButton(
                        onPressed: () async {
                            await _requestNotificationPermission();
                            _scheduleNotification(10);
                        },
                        child: const Text('Schedule notification message in 10 Minutes'),
                    ),
                    SizedBox(height: 16),
                    ElevatedButton(
                        onPressed: () async {
                            await _requestNotificationPermission();
                            _scheduleNotification(15);
                        },
                        child: const Text('Schedule notification message in 15 Minutes'),
                    ),
                ],
            ),
        ),
    );
}
}

我尝试了上面的代码,尝试更新我的本地通知包(当时是14.0.0,然后是最新版本,但我回到了14.0.0,因为我在最新版本中遇到了问题),并尝试了新的模拟器。但在真正的 Android 设备上,它根本不显示通知。

android flutter dart mobile notifications
1个回答
0
投票

试试这些

1-检查 AndroidManifest.xml 中的权限请求

2-当您安装应用程序时,请在应用程序设置中授予所有权限

3-尝试发送通知并检查终端

希望有帮助

一切顺利

© www.soinside.com 2019 - 2024. All rights reserved.