hms_push_kit
A Flutter package for Huawei Mobile Services (HMS) Push Kit that handles:
- ✅ Device token retrieval (with timeout & retry)
- ✅ Foreground / background / tap notification handling
- ✅ OAuth2 authentication with Huawei's server (
grant_type=client_credentials) - ✅ Server-side notification sending via the HMS REST API
Features
| Feature | Class |
|---|---|
| Get HMS device token | HmsNotificationServiceImpl |
| Listen for notification taps | HmsNotificationServiceImpl.onNotificationClick |
| Handle background messages | HmsNotificationServiceImpl.backgroundMessageCallback |
| Obtain OAuth2 access token | HmsAuthClient |
| Send push notification | HmsPushClient |
Screenshots
Installation
dependencies:
hms_push_kit: ^0.0.1
Android only — HMS Push Kit is available only on Huawei devices with HMS Core.
Prerequisites
- Create a project in AppGallery Connect.
- Enable Push Kit in the project.
- Download
agconnect-services.jsonand place it inandroid/app/. - Follow the huawei_push setup guide for
AndroidManifest.xml.
Client-side Usage
Initialize (in main.dart)
import 'package:hms_push_kit/hms_push_kit.dart';
final hmsService = HmsNotificationServiceImpl();
// Top-level or static function for handling background messages
@pragma('vm:entry-point')
void myBackgroundHandler(RemoteMessage message) {
print('Received background message: ${message.data}');
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await hmsService.initialize(
onTokenReceived: (String token) async {
// Save token to your backend
await MyApi.saveHmsToken(token);
},
// Optional: Pass custom background handler (or omit to use default)
onBackgroundMessage: myBackgroundHandler,
);
runApp(MyApp());
}
Listen for notification taps
hmsService.onNotificationClick.listen((String? json) {
if (json == null) return;
final data = jsonDecode(json);
// data['id'], data['title'], data['view']
navigateToView(data['view']);
});
Get the current token
final String token = hmsService.token;
Background message handler
When a push notification is received while the app is in the background or terminated, Flutter executes Dart code in a separate Background Isolate.
The huawei_push plugin requires a static or top-level function to handle these background messages.
HmsNotificationServiceImpl.backgroundMessageCallback is pre-configured and automatically registered when you call await hmsService.initialize(). You do not need to call or register it manually.
// Handled automatically inside hmsService.initialize():
await Push.registerBackgroundMessageHandler(
HmsNotificationServiceImpl.backgroundMessageCallback,
);
Note: Background isolates run in a separate memory space and cannot directly emit events to the main UI's
BehaviorSubject. If you need to perform background persistence, use local storage (e.g.SharedPreferencesorHive) inside your background tasks.
Server-side Usage
⚠️ Security Warning: Never embed your
clientSecretin a production Flutter app. UseHmsPushClientonly from a secure Dart backend server or for local testing.
Get an OAuth2 access token
final authClient = HmsAuthClient(
clientId: '110577713', // Your HMS App ID
clientSecret: 'your_secret', // From AppGallery Connect
);
final tokenResponse = await authClient.getAccessToken();
print(tokenResponse.accessToken); // Bearer token
Send a push notification
final pushClient = HmsPushClient(
appId: '110577713',
clientSecret: 'your_secret',
);
final result = await pushClient.sendNotification(
HmsNotification(
title: 'Hello!',
body: 'You have a new message.',
tokens: ['<device_hms_token>'],
data: {
'id': '42',
'title': 'Hello!',
'view': 'chat',
},
),
);
if (result.isSuccess) {
print('Sent! RequestId: ${result.requestId}');
} else {
print('Failed: [${result.code}] ${result.msg}');
}
The client automatically:
- Caches the OAuth2 token and reuses it until expiry.
- Detects expired-token errors (
80300063,80300050) and retries once with a fresh token.
API Reference
HmsNotificationServiceImpl
| Member | Type | Description |
|---|---|---|
initialize({onTokenReceived}) |
Future<void> |
Boot HMS Push Kit |
token |
String |
Current device token |
onNotificationClick |
BehaviorSubject<String?> |
JSON notification payload stream |
backgroundMessageCallback |
static void |
Register with Push.registerBackgroundMessageHandler |
dispose() |
void |
Close the stream |
HmsAuthClient
| Member | Type | Description |
|---|---|---|
getAccessToken() |
Future<HmsTokenResponse> |
Returns cached or fresh OAuth2 token |
refreshToken() |
Future<HmsTokenResponse> |
Force-refresh token |
clearCache() |
void |
Clear cached token |
HmsPushClient
| Member | Type | Description |
|---|---|---|
sendNotification(notification) |
Future<HmsPushResult> |
Send via HMS REST API |
sendNotificationWithToken(notification, token) |
Future<HmsPushResult> |
Use pre-obtained token |
HmsNotification
| Field | Type | Description |
|---|---|---|
title |
String |
Notification title |
body |
String |
Notification body |
tokens |
List<String> |
Target device tokens |
data |
Map<String, String>? |
Custom key-value data |
clickActionType |
int |
Click action (default 3 = open app) |
HMS REST API Endpoints
| Endpoint | URL |
|---|---|
| OAuth2 token | POST https://oauth-login.cloud.huawei.com/oauth2/v3/token |
| Send notification | POST https://push-api.cloud.huawei.com/v1/{appId}/messages:send |
License
MIT — see LICENSE.
Libraries
- fz_hms_push_kit
- fz_hms_push_kit — A Flutter package for Huawei Push Notifications.
- hms_push_kit
- HMS Push Kit — A Flutter package for Huawei Push Notifications.