Попытка вызвать метод интерфейса java.lang.String java.lang.CharSequence.toString() для ссылки на нулевой объект
Я хочу отправлять сообщения с уведомлением об определенном приложении со своего мобильного телефона с помощью бота Telegram, и мое приложение должно оставаться открытым в фоновом режиме. Я использую уведомления: ^ 2.0.1 , чтобы слушать уведомления с мобильного
и teledart: ^ 0.2.1 для отправки сообщения ботом с использованием 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 -v здесь
D: \ Android Studio Projects \ maseka>flutter pub get Запуск "flutter pub get" в масеке ... 887 мс
D: \ Android Studio Projects \ maseka>flutter doctor -v[√] Flutter (стабильный канал, 2.8.1, в Microsoft Windows [версия 10.0.22000.376], локаль en-US)• Flutter версии 2.8.1 в C: \ Users \ Ubaid Bodla \ flutter• Репозиторий Upstream 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) • Android SDK в C: \ Users \ Ubaid Bodla \ AppData \ Local \ Android \ sdk• Платформа android-32, инструменты сборки 32.0.0• Бинарный файл Java находится по адресу: C: \ Program Files \ Android \ Android Studio \ jre \ bin \ java• Версия Java OpenJDK Runtime Environment (сборка 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 Runtime Environment (сборка 11.0.10 +0-b96-7249189)
[√] Код VS (версия 1.63.2)• Код VS в C: \ Users \ Ubaid Bodla \ AppData \ Local \ Programs \ Microsoft VS Code• Расширение Flutter версии 3.32.0
[√] Подключенное устройство (доступно 3)• M2007J20CG (мобильный) • 229ff5e4 • android-arm64 • Android 11 (API 30)• Chrome (веб) • Chrome • веб-javascript • Google Chrome 96.0.4664.110• Edge (веб) • edge • веб-javascript • Microsoft Edge 96.0.1054.62
• Проблем не обнаружено!