My flutter app is listening to SMS in foreground as well as background using the telephony package. While registering to receive the messages, I have used two methods (one for foreground and one for background, as required by the telephony package like this:
telephony.listenIncomingSms(onNewMessage: onMessage, onBackgroundMessage: onBackgroundMessage);
But inside both the methods have a call to a common method that saves the most recent SMS received to shared preferences, like this:
onMessage(SmsMessage message) async {
...
saveLastMsg(message);
}
onBackgroundMessage(SmsMessage message) async {
...
saveLastMsg(message);
}
saveLastMsg(SmsMessage message) async{
SharedPreferences sp = await SharedPreferences.getInstance();
sp.setString("lastsmsbody", message.body??'');
}
In App UI, I fetch the lastsmsbody like this:
SharedPreferences sp = await SharedPreferences.getInstance();
String body = sp.getString("lastsmsbody")??'';
I display this value in the UI. This is working fine when the App is running in the foreground. The data on the screen is updated as and when messages come in.
The problem is when the app is pushed in the background. From the logs, I see that it still receives the message and it still saves it in the preferences. But when I bring the app back to the foreground, it is not able to fetch that most recent message that was saved when the app was in bg. sp.getString("lastsmsbody") gets the old message that was saved when the app was in foreground.
I thought that may be preferences are different when app is in fg and bg. But if I kill the app and restart, sp.getString("lastsmsbody") returns the most recent message correct that was saved when the app was in bg.
Can someone tell me what is going on here?