bxpush_mi 0.0.4
bxpush_mi: ^0.0.4 copied to clipboard
bxpush_mi sdk for flutter.
example/lib/main.dart
import 'dart:async';
import 'package:bxpush_mi/mipush.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _mipushPlugin = Mipush();
final _appIdController = TextEditingController(text: '2882303761520352304');
final _appKeyController = TextEditingController(text: '5302035224304');
final _aliasController = TextEditingController();
final _accountController = TextEditingController();
final _topicController = TextEditingController();
final _startHourController = TextEditingController(text: '0');
final _startMinuteController = TextEditingController(text: '0');
final _endHourController = TextEditingController(text: '23');
final _endMinuteController = TextEditingController(text: '59');
String _regId = 'Unknown';
final List<String> _logs = <String>[];
StreamSubscription<Map<String, dynamic>>? _eventSubscription;
bool _autoRegisterTriggered = false;
bool _registering = false;
String _lastToastKey = '';
DateTime _lastToastAt = DateTime.fromMillisecondsSinceEpoch(0);
@override
void initState() {
super.initState();
_mipushPlugin.registerPush(
appId: _appIdController.text.trim(),
appKey: _appKeyController.text.trim(),
);
_eventSubscription = _mipushPlugin.events().listen(
(event) {
_appendLog('[event] $event');
_showEventToast(event);
},
onError: (Object error) {
_appendLog('event error: $error');
},
);
WidgetsBinding.instance.addPostFrameCallback((_) {
_triggerAutoRegister();
});
}
Future<void> _showEventToast(Map<String, dynamic> event) async {
final eventType = (event['event'] ?? 'unknown').toString();
final content = (event['content'] ?? '').toString();
final description = (event['description'] ?? '').toString();
final title = (event['title'] ?? '').toString();
final command = (event['command'] ?? '').toString();
final resultCode = (event['resultCode'] ?? '').toString();
final text = _firstNonEmpty(<String>[content, description, title]);
String? message;
switch (eventType) {
case 'registerResult':
final regId = (event['regId'] ?? '').toString();
message = resultCode == '0'
? 'register success ${regId.isEmpty ? '' : 'regId=$regId'}'.trim()
: 'register failed code=$resultCode';
break;
case 'commandResult':
// commandResult is often noisy; only toast failures.
if (resultCode != '0') {
message = 'command $command failed code=$resultCode';
}
break;
case 'notificationArrived':
message =
'notification arrived: ${text.isEmpty ? 'new message' : text}';
break;
case 'notificationClicked':
message = 'notification clicked: ${text.isEmpty ? 'opened' : text}';
break;
case 'passThrough':
message = 'passThrough: ${text.isEmpty ? 'new message' : text}';
break;
default:
if (text.isNotEmpty) {
message = '$eventType: $text';
}
break;
}
if (message == null || message.trim().isEmpty) {
return;
}
if (_isDuplicateToast('$eventType|$message')) {
return;
}
await Fluttertoast.showToast(
msg: message,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
);
}
String _firstNonEmpty(List<String> values) {
for (final value in values) {
final trimmed = value.trim();
if (trimmed.isNotEmpty) {
return trimmed;
}
}
return '';
}
bool _isDuplicateToast(String key) {
final now = DateTime.now();
final duplicated = key == _lastToastKey &&
now.difference(_lastToastAt).inMilliseconds < 1500;
_lastToastKey = key;
_lastToastAt = now;
return duplicated;
}
Future<void> _triggerAutoRegister() async {
if (_autoRegisterTriggered) {
return;
}
_autoRegisterTriggered = true;
_appendLog('auto register on app startup');
// Give first frame and startup tasks time to settle before network registration.
await Future<void>.delayed(const Duration(milliseconds: 600));
if (!mounted) {
return;
}
await _register();
}
@override
void dispose() {
_eventSubscription?.cancel();
_appIdController.dispose();
_appKeyController.dispose();
_aliasController.dispose();
_accountController.dispose();
_topicController.dispose();
_startHourController.dispose();
_startMinuteController.dispose();
_endHourController.dispose();
_endMinuteController.dispose();
super.dispose();
}
void _appendLog(String text) {
if (!mounted) {
return;
}
setState(() {
_logs.insert(0, text);
if (_logs.length > 200) {
_logs.removeLast();
}
});
}
Future<void> _register() async {
if (_registering) {
_appendLog('registerPush skipped: request in progress');
return;
}
_registering = true;
try {
await _mipushPlugin.registerPush(
appId: _appIdController.text.trim(),
appKey: _appKeyController.text.trim(),
);
final regId = await _mipushPlugin.getRegId() ?? 'null';
if (!mounted) {
return;
}
setState(() {
_regId = regId;
});
_appendLog('registerPush success, regId=$_regId');
} on PlatformException catch (e) {
if (!mounted) {
return;
}
setState(() {
_regId = 'register failed';
});
_appendLog('registerPush failed: ${e.code} ${e.message}');
} finally {
_registering = false;
}
}
Future<void> _refreshRegId() async {
try {
final regId = await _mipushPlugin.getRegId() ?? 'null';
if (!mounted) {
return;
}
setState(() {
_regId = regId;
});
_appendLog('getRegId success: $_regId');
} on PlatformException catch (e) {
_appendLog('getRegId failed: ${e.code} ${e.message}');
}
}
Future<void> _unregister() async {
await _safeInvoke('unregisterPush', _mipushPlugin.unregisterPush);
}
Future<void> _setAlias() async {
final alias = _aliasController.text.trim();
if (alias.isEmpty) {
_appendLog('alias is empty');
return;
}
await _safeInvoke('setAlias($alias)', () => _mipushPlugin.setAlias(alias));
}
Future<void> _unsetAlias() async {
final alias = _aliasController.text.trim();
if (alias.isEmpty) {
_appendLog('alias is empty');
return;
}
await _safeInvoke(
'unsetAlias($alias)',
() => _mipushPlugin.unsetAlias(alias),
);
}
Future<void> _setAccount() async {
final account = _accountController.text.trim();
if (account.isEmpty) {
_appendLog('account is empty');
return;
}
await _safeInvoke(
'setUserAccount($account)',
() => _mipushPlugin.setUserAccount(account),
);
}
Future<void> _unsetAccount() async {
final account = _accountController.text.trim();
if (account.isEmpty) {
_appendLog('account is empty');
return;
}
await _safeInvoke(
'unsetUserAccount($account)',
() => _mipushPlugin.unsetUserAccount(account),
);
}
Future<void> _subscribe() async {
final topic = _topicController.text.trim();
if (topic.isEmpty) {
_appendLog('topic is empty');
return;
}
await _safeInvoke(
'subscribe($topic)',
() => _mipushPlugin.subscribe(topic),
);
}
Future<void> _unsubscribe() async {
final topic = _topicController.text.trim();
if (topic.isEmpty) {
_appendLog('topic is empty');
return;
}
await _safeInvoke(
'unsubscribe($topic)',
() => _mipushPlugin.unsubscribe(topic),
);
}
Future<void> _setAcceptTime() async {
final startHour = int.tryParse(_startHourController.text) ?? 0;
final startMinute = int.tryParse(_startMinuteController.text) ?? 0;
final endHour = int.tryParse(_endHourController.text) ?? 23;
final endMinute = int.tryParse(_endMinuteController.text) ?? 59;
await _safeInvoke(
'setAcceptTime($startHour:$startMinute-$endHour:$endMinute)',
() => _mipushPlugin.setAcceptTime(
startHour: startHour,
startMinute: startMinute,
endHour: endHour,
endMinute: endMinute,
),
);
}
Future<void> _pausePush() async {
await _safeInvoke('pausePush', _mipushPlugin.pausePush);
}
Future<void> _resumePush() async {
await _safeInvoke('resumePush', _mipushPlugin.resumePush);
}
Future<void> _safeInvoke(String action, Future<void> Function() call) async {
try {
await call();
_appendLog('$action success');
} on PlatformException catch (e) {
_appendLog('$action failed: ${e.code} ${e.message}');
}
}
Widget _lineTextField(TextEditingController controller, String label) {
return TextField(
controller: controller,
decoration: InputDecoration(labelText: label, isDense: true),
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('MiPush Plugin Example')),
body: SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
_lineTextField(_appIdController, 'App ID'),
_lineTextField(_appKeyController, 'App Key'),
Wrap(
spacing: 8,
runSpacing: 8,
children: <Widget>[
ElevatedButton(
onPressed: _register,
child: const Text('Register Push'),
),
OutlinedButton(
onPressed: _unregister,
child: const Text('Unregister'),
),
OutlinedButton(
onPressed: _refreshRegId,
child: const Text('Get RegId'),
),
],
),
Text('RegId: $_regId'),
const Divider(height: 16),
_lineTextField(_aliasController, 'Alias'),
Wrap(
spacing: 8,
runSpacing: 8,
children: <Widget>[
OutlinedButton(
onPressed: _setAlias,
child: const Text('Set Alias'),
),
OutlinedButton(
onPressed: _unsetAlias,
child: const Text('Unset Alias'),
),
],
),
_lineTextField(_accountController, 'Account'),
Wrap(
spacing: 8,
runSpacing: 8,
children: <Widget>[
OutlinedButton(
onPressed: _setAccount,
child: const Text('Set Account'),
),
OutlinedButton(
onPressed: _unsetAccount,
child: const Text('Unset Account'),
),
],
),
_lineTextField(_topicController, 'Topic'),
Wrap(
spacing: 8,
runSpacing: 8,
children: <Widget>[
OutlinedButton(
onPressed: _subscribe,
child: const Text('Subscribe Topic'),
),
OutlinedButton(
onPressed: _unsubscribe,
child: const Text('Unsubscribe Topic'),
),
],
),
Row(
children: <Widget>[
Expanded(
child: _lineTextField(
_startHourController,
'Start Hour',
),
),
const SizedBox(width: 8),
Expanded(
child: _lineTextField(
_startMinuteController,
'Start Minute',
),
),
const SizedBox(width: 8),
Expanded(
child: _lineTextField(_endHourController, 'End Hour'),
),
const SizedBox(width: 8),
Expanded(
child: _lineTextField(
_endMinuteController,
'End Minute',
),
),
],
),
Wrap(
spacing: 8,
runSpacing: 8,
children: <Widget>[
OutlinedButton(
onPressed: _setAcceptTime,
child: const Text('Set Accept Time'),
),
OutlinedButton(
onPressed: _pausePush,
child: const Text('Pause Push'),
),
OutlinedButton(
onPressed: _resumePush,
child: const Text('Resume Push'),
),
],
),
const SizedBox(height: 8),
const Text('Logs / Events:'),
const SizedBox(height: 8),
SizedBox(
height: 220,
child: DecoratedBox(
decoration: BoxDecoration(
border: Border.all(color: Colors.black26),
),
child: ListView.builder(
itemCount: _logs.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
child: Text(
_logs[index],
style: Theme.of(context).textTheme.bodySmall,
),
);
},
),
),
),
],
),
),
),
),
),
);
}
}