我正在尝试在收到短信后触发操作,但没有成功。我可以在发送短信甚至发送短信时启动我的操作,但不能在收到短信时发起。我正在使用短信0.1.0 https://pub.dartlang.org/packages/sms#-readme-tab-
要清楚
1 - 我可以将短信发送到另一台设备
2 - 另一台设备收到短信
3 - 另一台设备然后发给我一个短信
4 - 我想在收到此回复时触发行动
目前,我找不到如何做到这一点
这是当前代码
...
SmsSender sender = new SmsSender();
String _nirbinumber;
SmsReceiver receiver = new SmsReceiver();
SmsMessage _lastMessage = new SmsMessage(null, "No new messages");
...
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
body: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Container(
height: 250.0,
child: new Stack(
children: <Widget>[
new Center(
child :
new Container(
child : new FloatingActionButton(
child : new Icon (Icons.location_on),
onPressed: ()
async {
SmsMessage message = new SmsMessage(_nirbinumber, '$loc1');
sender.sendSms(message);
message.addStateListener((state) {
if (state == SmsMessageState.Delivered) {
receiver.onSmsReceived.listen((SmsMessage msg) => _lastMessage = msg);
setState(() {
savegeoValue(); // function to extract GPS coordinate of the received sms and save it with "shared preference"
StreamSubscription<SmsMessage> _smsSubscription;
}
);
showMap(); // function to launch googlemap view
}
}
);
}
),
),
),
],
)
)
],
)
)
);
}
答案 0 :(得分:1)
你总是留下一条信息的原因是&#39;是这一行receiver.onSmsReceived.listen((SmsMessage msg) => _lastMessage = msg);
这一行只是创建了一个监听器。它没有等待消息到达,因此您可以立即继续进入setState(前一条消息仍在_lastMessage
中)。事实上,继续创建监听器是没有意义的 - 你只需要一个。
我以不同的方式构建它,以便您始终拥有相同的侦听器,它会告诉您有关所有传入的消息,并根据(例如)电话号码或正文中的某些预期字符查找回复
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _nirbinumber = '12345';
// _lastMessage is probably redundant, as you can use msg (below)
SmsMessage _lastMessage = new SmsMessage('', '');
@override
void initState() {
super.initState();
// listen to the stream of *all* message arriving
new SmsReceiver().onSmsReceived.listen((SmsMessage msg) {
// filter out the replies by number
if (msg.address == _nirbinumber) {
// fantastique - it's one of the ones we want
setState(() {
_lastMessage = msg;
});
saveGeoValue(msg); // this cannot use the value in _lastMessage as it will not have been set yet
showMap(msg);
}
});
}
void _send() {
// fire (and forget)
new SmsSender().sendSms(new SmsMessage(_nirbinumber, 'test message'));
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('SMS demo'),
),
body: new Center(
child: new Text(_lastMessage.body),
),
floatingActionButton: new FloatingActionButton(
onPressed: _send,
tooltip: 'Send SMS',
child: new Icon(Icons.sms),
),
);
}
}