我想通过电报机器人从我的手机发送某个应用程序的通知消息,并且我的应用程序应该在后台保持打开状态。我使用通知:^2.0.1来收听来自我的手机的通知
和teledart: ^0.2.1用于通过 bot 使用flutter_background_service: ^0.2.2发送味精。
我的代码是
import 'dart:async';
import 'package:notifications/notifications.dart';
import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:teledart/teledart.dart';
import 'package:teledart/telegram.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
initializeService();
runApp(MyApp());
}
Future<void> initializeService() async {
final service = FlutterBackgroundService();
await service.configure(
androidConfiguration: AndroidConfiguration(
// this will executed when app is in foreground or background in separated isolate
onStart: onStart,
// auto start service
autoStart: true,
isForegroundMode: true,
),
iosConfiguration: IosConfiguration(
// auto start service
autoStart: true,
// this will executed when app is in foreground in separated isolate
onForeground: onStart,
// you have to enable background fetch capability on xcode project
onBackground: onIosBackground,
),
);
}
// to ensure this executed
// run app from xcode, then from xcode menu, select Simulate Background Fetch
void onIosBackground() {
WidgetsFlutterBinding.ensureInitialized();
print('FLUTTER BACKGROUND FETCH');
}
void onStart() {
WidgetsFlutterBinding.ensureInitialized();
print('object');
final service = FlutterBackgroundService();
service.onDataReceived.listen((event) {
if (event!["action"] == "setAsForeground") {
service.setForegroundMode(true);
return;
}
if (event["action"] == "setAsBackground") {
service.setForegroundMode(false);
}
if (event["action"] == "stopService") {
service.stopBackgroundService();
}
});
final token = 'token';
void startListen(id, message) async {
print("START LISTENING");
var telegram = Telegram(token);
var event = Event((await telegram.getMe()).username!);
telegram.sendMessage(id, message).then((value) => print('Message sent'));
}
List<String> _log = [];
void Notification() async {
Notifications().notificationStream?.forEach((element) {
if (element.message != null) {
if (!_log.contains(element.message.toString())) {
if (element.title == "any app") {
if (element.message != "") {
_log.add(element.message.toString());
startListen(ch_id, element.message);
}
}
if (element.title == "any app") {
if (element.message != "") {
_log.add(element.message.toString());
startListen(ch_id, element.message);
}
}
if (element.title == "any app") {
if (element.message != "") {
startListen(ch_id, element.message);
}
}
if (element.title == "any app") {
if (element.message != "") {
_log.add(element.message.toString());
startListen(ch_id, element.message);
}
}
if (element.title == "any app") {
if (element.message != "") {
startListen(ch_id, element.message);
}
}
if (element.title == "any app") {
if (element.message != "") {
startListen(ch_id, element.message);
}
}
if (element.title == "any app") {
if (element.message != "") {
startListen(ch_id, element.message);
}
}
}
}
});
print(_log);
}
// bring to foreground
service.setForegroundMode(true);
Timer.periodic(Duration(seconds: 1), (timer) async {
Notification();
print('time');
if (!(await service.isServiceRunning())) timer.cancel();
service.setNotificationInfo(
title: "My App Service",
content: "Updated at ${DateTime.now()}",
);
service.sendData(
{"current_date": DateTime.now().toIso8601String()},
);
});
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String text = "Stop Service";
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Service App'),
),
body: Column(
children: [
StreamBuilder<Map<String, dynamic>?>(
stream: FlutterBackgroundService().onDataReceived,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
final data = snapshot.data!;
DateTime? date = DateTime.tryParse(data["current_date"]);
return Text(date.toString());
},
),
ElevatedButton(
child: Text("Foreground Mode"),
onPressed: () {
FlutterBackgroundService()
.sendData({"action": "setAsForeground"});
},
),
ElevatedButton(
child: Text("Background Mode"),
onPressed: () {
FlutterBackgroundService()
.sendData({"action": "setAsBackground"});
},
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
FlutterBackgroundService().sendData({
"hello": "world",
});
},
child: Icon(Icons.play_arrow),
),
),
);
}
我正面临一个问题,一段时间后它给了我
我的 Flutter doc -v 在这里
D:\Android Studio Projects\maseka>flutter pub get 在 maseka 中运行“flutter pub get”... 887ms
D:\Android Studio Projects\maseka>flutter doctor -v [√] Flutter (Channel stable, 2.8.1, on Microsoft Windows [Version 10.0.22000.376], locale en-US) • Flutter 版本 2.8.1 在 C:\ Users\Ubaid Bodla\flutter • 上游存储库https://github.com/flutter/flutter.git • 框架修订版 77d935af4d(3 周前),2021-12-16 08:37:33 -0800 • 引擎修订版 890a5fca2e • Dart 2.15.1 版
[√] Android 工具链 - 为 Android 设备开发(Android SDK 版本 32.0.0) • C:\Users\Ubaid Bodla\AppData\Local\Android\sdk 中的 Android SDK • 平台 android-32,构建工具 32.0.0 • Java 二进制文件位于:C:\Program Files\Android\Android Studio\jre\bin\java • Java 版本 OpenJDK 运行时环境(内部版本 11.0.10+0-b96-7249189) • 接受所有 Android 许可证。
[√] Chrome - 为网络开发 • Chrome 位于 C:\Program Files\Google\Chrome\Application\chrome.exe
[√] Android Studio(版本 2020.3) • Android Studio 位于 C:\Program Files\Android\Android Studio • Flutter 插件可以从以下位置安装: https ://plugins.jetbrains.com/plugin/9212-flutter • Dart 插件可以从以下位置安装: https : //plugins.jetbrains.com/plugin/6351-dart • Java 版本 OpenJDK 运行时环境(内部版本 11.0.10+0-b96-7249189)
[√] VS Code(版本 1.63.2) • C:\Users\Ubaid Bodla\AppData\Local\Programs\Microsoft VS Code 的 VS Code • Flutter 扩展版本 3.32.0
[√] 连接设备(3 个可用) • M2007J20CG(移动) • 229ff5e4 • android-arm64 • Android 11 (API 30) • Chrome(网络) • chrome • web-javascript • Google Chrome 96.0.4664.110 • Edge(网络) •边缘 • web-javascript • Microsoft Edge 96.0.1054.62
• 未发现任何问题!