Сохранение веб-сокета открытым, когда приложение Flutter переходит в фоновый режимAndroid

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

Сообщение Anonymous »

Я использую пакет: flutter_foreground_task. Я следую их инструкциям https://pub.dev/packages/flutter_foreground_task
Служба никогда не запускается. Вот код:

Код: Выделить всё

// The callback function should always be a top-level function.
@pragma('vm:entry-point')
void startCallback() {
// The setTaskHandler function must be called to handle the task in the background.
FlutterForegroundTask.setTaskHandler(FirstTaskHandler());
}

WebSocketChannel? _channel;

class FirstTaskHandler extends TaskHandler {
Timer? _timer;

@override
void onStart(DateTime timestamp, SendPort? sendPort) async {
// Start sending ping messages periodically
_timer = Timer.periodic(Duration(seconds: 15), (Timer t) async {
try {
_channel!.sink.add(jsonEncode({'type': 'ping'})); // Send a ping message
print('pinging');
} catch (e) {
//there is a problem so we abort
}
});
}

@override
void onRepeatEvent(DateTime timestamp, SendPort? sendPort) async {}

@override
void onDestroy(DateTime timestamp, SendPort? sendPort) async {
_timer?.cancel();
}
}
в пользовательской функции _init, которую я вызываю:

Код: Выделить всё

WidgetsBinding.instance.addPostFrameCallback((_) async {
await _requestPermissionForAndroid();
await _startForegroundTask();
});

Future _startForegroundTask() async {
FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
channelId: 'channel_id',
channelName: 'Foreground Service',
channelDescription:
'This notification appears when the foreground service is running.',
channelImportance: NotificationChannelImportance.LOW,
priority: NotificationPriority.LOW,
iconData: NotificationIconData(
resType: ResourceType.mipmap,
resPrefix: ResourcePrefix.ic,
name: 'launcher',
),
),
iosNotificationOptions: const IOSNotificationOptions(
showNotification: true,
playSound: false,
),
foregroundTaskOptions: const ForegroundTaskOptions(
interval: 5000,
autoRunOnBoot: true,
allowWifiLock: true,
),
);

await FlutterForegroundTask.startService(
notificationTitle: 'Foreground service is running',
notificationText: 'Tap to return to the app',
callback: startCallback,
);
}
У меня есть разрешение, добавленное в манифест Android.
Наконец, мой основной виджет завернут: return WithForegroundTask( child: Scaffold(

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

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

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

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

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

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

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