Reputation: 2247
I have a Flutter app that uses Firebase messaging to delivery notifications. This is the base code, it does nothing special, besides saving the token on my DB.
FirebaseMessaging _firebaseMessaging = new FirebaseMessaging();
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) {
},
onResume: (Map<String, dynamic> message) {
},
onLaunch: (Map<String, dynamic> message) {
},
);
_firebaseMessaging.getToken().then((token) {
saveToken(token);
});
Do I have to implement some kind of background service to keep saving the new token on my DB everytime it gets refreshed? I remember using onTokenRefresh()
on Android(JAVA) to do this, but I found nothing about it in Flutter (DART).
I read somewhere that the token gets refreshed every 3600 seconds. I wonder if this is true.
Upvotes: 9
Views: 15326
Reputation: 1
FirebaseMessaging.instance.onTokenRefresh.listen((newToken) {
// Save newToken
});
Upvotes: 0
Reputation: 3600
Here is an example of subscribing to the firebaseMessaging.onTokenRefresh
stream and updating the token if the token has changed:
FirebaseMessaging().onTokenRefresh.listen((token) async {
final prefs = await SharedPreferences.getInstance();
final String firebaseTokenPrefKey = 'firebaseToken';
final String currentToken = prefs.getString(firebaseTokenPrefKey);
if (currentToken != token) {
print('token refresh: ' + token);
// add code here to do something with the updated token
await prefs.setString(firebaseTokenPrefKey, token);
}
});
Upvotes: 3
Reputation: 917
No, FCM token doesn't refresh every 3600 seconds. It only refreshes when :
FirebaseMessaging().deleteInstanceID()
You can listen to token refresh stream using:
FirebaseMessaging().onTokenRefresh.listen((newToken) {
// Save newToken
});
Hope it helps
Upvotes: 23
Reputation: 21
After the user logs in my app logs her in again automatically every 3500 seconds.
I used a Timer like this:
void _timerPressed() {
const timeout = const Duration(seconds: 3500);
new Timer.periodic(timeout, (Timer t) => _handleSignIn());
}
I set the timer in the 'login' button press method after the login has occurred:
void _loginPressed() {
print('The user wants to login with $_email and $_password');
_handleSignIn()
.then((FirebaseUser user) => print(user))
.catchError((e) => print(e));
_timerPressed();
}
(Don't be fooled by the name of the method, '_timerPressed'. I used a button press for testing the technique and haven't gotten around to renaming the method after I tied it in to the login button.)
Upvotes: -5
Reputation: 40423
You can use firebaseMessaging.onTokenRefresh
to get a stream which receives an event each time a new token is received.
Upvotes: 3