您好,我正在尝试创建一个颤振应用程序,即使应用程序关闭也能显示通知。
我设法找到了一些与flutter_background_service相关的插件,但是当我尝试复制示例中显示的代码时,它显示了一些与 AndroidServiceInstance 和 setAsBackgroundService() 相关的错误,说明它们未定义。如何解决这个问题?有没有更好的方法来实现我想要的?谢谢之前。
这是我当前的代码:
Future<void> initializeService() async {
final service = FlutterBackgroundService();
const AndroidNotificationChannel channel = AndroidNotificationChannel(
notificationChannelId, // ID
'MY FOREGROUND SERVICE', // Title
description:
'This channel is used for important notifications.', // Description
importance: Importance.low, // importance must be at low or higher level
);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
if (Platform.isIOS) {
await flutterLocalNotificationsPlugin.initialize(
const InitializationSettings(
iOS: IOSInitializationSettings(),
),
);
}
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
await service.configure(
androidConfiguration: AndroidConfiguration(
onStart: onStart,
autoStart: true,
isForegroundMode: true,
notificationChannelId: 'my_foreground',
initialNotificationTitle: 'AWESOME SERVICE',
initialNotificationContent: 'Initializing',
foregroundServiceNotificationId: 888,
),
iosConfiguration: IosConfiguration(
autoStart: true,
onForeground: onStart,
onBackground: onIosBackground,
),
);
service.startService();
}
onStart(ServiceInstance service) async {
DartPluginRegistrant.ensureInitialized();
if (service is AndroidServiceInstance) {
service.on('setAsForeground').listen((event) {
service.setAsForegroundService();
});
service.on('setAsBackground').listen((event) {
service.setAsBackgroundService();
});
}
service.on('stopService').listen((event) {
service.stopSelf();
});
}
Run Code Online (Sandbox Code Playgroud)
pma*_*ias 10
我在重新创建示例应用程序后才意识到。
您需要导入另一个依赖项:
import 'package:flutter_background_service_android/flutter_background_service_android.dart';
Run Code Online (Sandbox Code Playgroud)
我遇到了同样的错误AndroidServiceInstance,并且setAsBackgroundService()在添加附加包之前未定义。
| 归档时间: |
|
| 查看次数: |
1579 次 |
| 最近记录: |