所以我试图向用户发送通知,并编写了这段代码,基本上它更像是一个提醒应用程序,用户将创建一个提醒,我的应用程序将在确切的时间给他们一个通知。 每个功能都工作正常,但通知在真实设备上不显示,在模拟器上它显示通知。
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:awesome_notifications/awesome_notifications.dart';
import 'dart:convert';
import 'package:table_calendar/table_calendar.dart';
import 'dart:io'; // Import for platform checking
class GcalcScreen extends StatefulWidget {
@override
_GcalcScreenState createState() => _GcalcScreenState();
}
class _GcalcScreenState extends State<GcalcScreen> {
bool isDarkMode = false;
List<Map<String, dynamic>> reminders = [];
int nextReminderId = 1; // Increment for each reminder
DateTime selectedDate = DateTime.now();
TimeOfDay selectedTime = TimeOfDay.now();
@override
void initState() {
super.initState();
_loadThemePreference();
_loadReminders();
_initializeNotifications();
_requestNotificationPermissions(); // Request notification permissions
}
// Load the theme preference from SharedPreferences
void _loadThemePreference() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
isDarkMode = prefs.getBool('isDarkMode') ?? false;
});
}
// Initialize Awesome Notifications
void _initializeNotifications() {
AwesomeNotifications().initialize(
'resource://drawable/res_app_icon',
[
NotificationChannel(
channelKey: 'gcalc_channel',
channelName: 'Graphics Calculator Notifications',
channelDescription: 'Notification channel for graphics calculator',
defaultColor: Color(0xFF9D50DD),
ledColor: Colors.white,
importance: NotificationImportance.High,
),
],
);
}
// Request notification permissions
void _requestNotificationPermissions() async {
if (Platform.isAndroid) {
final status = await AwesomeNotifications().isNotificationAllowed();
if (!status) {
AwesomeNotifications().requestPermissionToSendNotifications();
}
}
}
// Load reminders from SharedPreferences
void _loadReminders() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String? remindersString = prefs.getString('reminders');
if (remindersString != null) {
List<dynamic> jsonList = json.decode(remindersString);
reminders = jsonList.map((item) => Map<String, dynamic>.from(item)).toList();
nextReminderId = reminders.isNotEmpty ? reminders.last['id'] + 1 : 1; // Update next reminder ID
}
setState(() {});
}
// Save reminders to SharedPreferences
void _saveReminders() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('reminders', json.encode(reminders));
}
// Method to send a reminder notification
void _sendReminder(String message, DateTime dateTime, bool isActive, int id) {
if (isActive) {
AwesomeNotifications().createNotification(
content: NotificationContent(
channelKey: 'gcalc_channel',
id: id,
title: 'Reminder!',
body: message,
),
schedule: NotificationCalendar(
year: dateTime.year,
month: dateTime.month,
day: dateTime.day,
hour: dateTime.hour,
minute: dateTime.minute,
second: 0,
millisecond: 0,
preciseAlarm: true,
),
);
}
}
// Show dialog for setting a reminder
void _setReminder() {
String reminderMessage = '';
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Set Reminder"),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: TextField(
onChanged: (value) {
reminderMessage = value;
},
decoration: InputDecoration(
hintText: "Enter reminder message",
border: OutlineInputBorder(),
),
),
),
),
SizedBox(height: 10),
Text("Select Time:"),
ElevatedButton(
onPressed: () async {
TimeOfDay? pickedTime = await showTimePicker(
context: context,
initialTime: selectedTime,
);
if (pickedTime != null) {
selectedTime = pickedTime;
}
},
child: Text("Pick Time"),
),
],
),
),
actions: [
TextButton(
onPressed: () {
if (reminderMessage.isNotEmpty) {
DateTime reminderDateTime = DateTime(
selectedDate.year,
selectedDate.month,
selectedDate.day,
selectedTime.hour,
selectedTime.minute,
);
_sendReminder(reminderMessage, reminderDateTime, true, nextReminderId);
reminders.add({
'id': nextReminderId,
'message': reminderMessage,
'dateTime': reminderDateTime.toIso8601String(),
'isActive': true,
});
nextReminderId++;
_saveReminders();
// Call setState to refresh the UI
setState(() {});
Navigator.of(context).pop();
}
},
child: Text("Set"),
),
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("Cancel"),
),
],
);
},
);
}
// Method to cancel a reminder
void _cancelReminder(int id) {
AwesomeNotifications().cancel(id);
reminders.removeWhere((reminder) => reminder['id'] == id);
_saveReminders();
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Reminders"),
backgroundColor: Colors.transparent,
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
isDarkMode
? 'Asset/images/bg_dark.png' // Dark mode background
: 'Asset/images/bg_light.png', // Light mode background
),
fit: BoxFit.cover,
),
),
child: Column(
children: [
// Calendar Widget
TableCalendar(
focusedDay: selectedDate,
firstDay: DateTime.utc(2020, 1, 1),
lastDay: DateTime.utc(2030, 12, 31),
selectedDayPredicate: (day) => isSameDay(selectedDate, day),
onDaySelected: (selectedDay, focusedDay) {
setState(() {
selectedDate = selectedDay;
});
},
),
SizedBox(height: 10),
// Reminders Card
Expanded(
child: Card(
elevation: 8, // Increased elevation for the card
child: reminders.isNotEmpty
? ListView.separated(
itemCount: reminders.length,
separatorBuilder: (context, index) => Divider(),
itemBuilder: (context, index) {
final reminder = reminders[index];
DateTime reminderDateTime = DateTime.parse(reminder['dateTime']);
String formattedTime = "Time: ${reminderDateTime.hour}:${reminderDateTime.minute.toString().padLeft(2, '0')}";
String formattedDate = "Date: ${reminderDateTime.day}/${reminderDateTime.month}/${reminderDateTime.year}";
return Dismissible(
key: Key(reminder['id'].toString()),
background: Container(
color: Colors.red,
alignment: Alignment.centerLeft,
padding: EdgeInsets.symmetric(horizontal: 20),
child: Icon(
Icons.delete,
color: Colors.white,
size: 30,
),
),
onDismissed: (direction) {
_cancelReminder(reminder['id']);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Reminder deleted")),
);
},
child: ListTile(
title: Text(reminder['message']),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(formattedTime),
Text(formattedDate),
],
),
trailing: Switch(
value: reminder['isActive'],
onChanged: (value) {
setState(() {
reminder['isActive'] = value;
if (value) {
_sendReminder(
reminder['message'],
reminderDateTime,
true,
reminder['id'],
);
} else {
AwesomeNotifications().cancel(reminder['id']);
}
_saveReminders();
});
},
),
),
);
},
)
: Center(
child: Text(
"No reminders set.",
style: TextStyle(
color: isDarkMode ? Colors.white : Colors.black,
fontSize: 24,
),
),
),
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _setReminder, // Show dialog to set reminder
child: Icon(Icons.add),
),
);
}
}
所以,我认为这是我的代码中的问题,所以我尝试了很棒的通知包的示例代码并得到了相同的结果,通知显示在模拟器上,但在真实设备上没有任何显示
将设备连接到您的系统并记录它以查看其记录的内容
flutter logs
在Android 13,即API 33及更高版本中,您是否在AndroidManifest.xml中单独授予了权限?
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>