React Native
Token retrieval
Learn to get push tokens.
What is a push token?
A push token is a string that uniquely identifies your device. Your server sends notifications to this string and the Apple or Google service routes it to the real device. Without a token you cannot send remote notifications.
The expo-notifications package returns an Expo token through getExpoPushTokenAsync. The token has the form ExponentPushToken[xxxxxxxxxxxxxxx]. You register the token with your server; when the server wants to send a notification it uses this token.
Android channel
On Android 8 and later, notifications must be tied to a channel. The channel sets the notification's sound, importance and behavior. iOS has no channel concept; so channel settings apply only to Android.
To create a channel you call Notifications.setNotificationChannelAsync. Example: Notifications.setNotificationChannelAsync('default', {{ name: 'Default', importance: Notifications.AndroidImportance.HIGH }}). This call is made once when the app starts; you then give the same channel name to notifications.
Exercise Get the token and log it
Complete the registerForPushNotifications function. First get the permission status with Notifications.getPermissionsAsync(); if not granted, call Notifications.requestPermissionsAsync(). Then get the token with const token = await Notifications.getExpoPushTokenAsync({{ projectId: 'abc123' }}) and log it with console.log(token.data).
Show example solution
async function registerForPushNotifications() {
const current = await Notifications.getPermissionsAsync();
let final = current;
if (!final.granted) {
final = await Notifications.requestPermissionsAsync();
}
if (!final.granted) return null;
const token = await Notifications.getExpoPushTokenAsync({ projectId: 'abc123' });
console.log(token.data);
return token.data;
}
Test yourself
-
Write the token function
const token = await Notifications.____({ projectId: 'your-project-id' });
Show answer
const token = await Notifications.getExpoPushTokenAsync({ projectId: 'your-project-id' });
-
What is a push token used for?
- Only to schedule local notifications
- To send a notification from the server to the device
- To store the user password
- To change the app icon
Show answer
To send a notification from the server to the device — The server sends a notification to the token; the service routes it to the device.
-
Match each part to its role
- getExpoPushTokenAsync
- Returns Expo token
- getPermissionsAsync
- Gives permission status
- requestPermissionsAsync
- Requests permission
- token.data
- Holds the token string
Next lesson: Local notifications