Я внедряю три кнопки (5, 10 и 15 минут), которые должны планировать будущее уведомление для пользователя. Например. Когда они нажимают 5 минут, через 5 минут появится уведомление с сообщением, несмотря ни на что. Я использую локальный пакет уведомлений для Flutter. Я обнаружил, что могу заставить его хорошо работать с многочисленными эмуляторами, однако, когда я пробую его на реальном устройстве 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();
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 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 {
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 _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'),
),
],
),
),
);
}
}
< /code>
Я попробовал этот код выше, попробовал обновить свой локальный пакет уведомлений (был 14.0.0, затем новейшая версия, но я вернулся к 14.0.0, потому что у меня были проблемы с новой версией) и попробовали новые эмуляторы. Но на реальном устройстве Android он вообще не отображает уведомление.
Подробнее здесь: https://stackoverflow.com/questions/779 ... android-de
Локальные уведомления о Flutter работают только на эмуляторе, но не на реальном устройстве Android? ⇐ Android
Форум для тех, кто программирует под Android
1751156562
Anonymous
Я внедряю три кнопки (5, 10 и 15 минут), которые должны планировать будущее уведомление для пользователя. Например. Когда они нажимают 5 минут, через 5 минут появится уведомление с сообщением, несмотря ни на что. Я использую локальный пакет уведомлений для Flutter. Я обнаружил, что могу заставить его хорошо работать с многочисленными эмуляторами, однако, когда я пробую его на реальном устройстве 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();
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 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 {
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 _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'),
),
],
),
),
);
}
}
< /code>
Я попробовал этот код выше, попробовал обновить свой локальный пакет уведомлений (был 14.0.0, затем новейшая версия, но я вернулся к 14.0.0, потому что у меня были проблемы с новой версией) и попробовали новые эмуляторы. Но на реальном устройстве Android он вообще не отображает уведомление.
Подробнее здесь: [url]https://stackoverflow.com/questions/77930678/local-notificaitons-for-flutter-only-works-on-emulator-but-not-a-real-android-de[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия