Локальные уведомления о Flutter работают только на эмуляторе, но не на реальном устройстве Android?Android

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Локальные уведомления о Flutter работают только на эмуляторе, но не на реальном устройстве Android?

Сообщение 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 он вообще не отображает уведомление.

Подробнее здесь: https://stackoverflow.com/questions/779 ... android-de
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»