jpush_receive.dart 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import 'dart:convert';
  2. import 'package:jpush_flutter/jpush_flutter.dart';
  3. import 'package:plugin_basic/constants/app_constant.dart';
  4. import 'package:plugin_basic/service/user_service.dart';
  5. import 'package:shared/utils/log_utils.dart';
  6. /// 处理极光推送的逻辑
  7. class JPushReceive {
  8. JPushReceive._internal();
  9. //保存单例
  10. static final JPushReceive _singleton = JPushReceive._internal();
  11. //工厂构造函数
  12. factory JPushReceive() => _singleton;
  13. /// 初始化极光推送,并设置监听回调
  14. void init() {
  15. JPush jpush = JPush();
  16. jpush.addEventHandler(
  17. // 接收通知回调方法。
  18. onReceiveNotification: (Map<String, dynamic> message) async {
  19. Log.d("flutter-jpush: onReceiveNotification: $message");
  20. },
  21. // 点击通知回调方法。
  22. onOpenNotification: (Map<String, dynamic> message) async {
  23. Log.d("flutter-jpush: onOpenNotification: $message");
  24. //拿到后端设置的内容Json对象
  25. dynamic extrasJson = message['extras'];
  26. dynamic extrasChildJson = extrasJson['cn.jpush.android.EXTRA'];
  27. Map<String, dynamic> jsonMap = jsonDecode(extrasChildJson.toString());
  28. //根据后端返回的type类型跳转到不同的路由页面
  29. },
  30. // 接收自定义消息回调方法。
  31. onReceiveMessage: (Map<String, dynamic> message) async {
  32. Log.d("flutter-jpush: onReceiveMessage: $message");
  33. },
  34. // 通知授权的回调
  35. onReceiveNotificationAuthorization: (Map<String, dynamic> message) async {
  36. Log.d("flutter-jpush: onReceiveNotificationAuthorization: $message");
  37. if (message.containsKey('isEnabled')) {
  38. //不管有没有开启通知权限,通知开关,先拿到 RegistrationId 赋值了再说
  39. final registrationId = await getRegistrationId();
  40. Log.d('flutter-jpush: 获取到registrationId:$registrationId');
  41. //设置给 RxString 对象,并保存到 UserService 中。
  42. UserService.to.registrationId.value = registrationId;
  43. } else {
  44. Log.d("flutter-jpush: onReceiveNotificationAuthorization 没有isEnable字段");
  45. }
  46. },
  47. // // 通知不显示的回调
  48. // onNotifyMessageUnShow: (Map<String, dynamic> message) async {
  49. // Log.d("flutter-refruiter: onNotifyMessageUnShow: $message");
  50. // },
  51. // // 极光推送连接的回调
  52. // onConnected: (Map<String, dynamic> message) async {
  53. // Log.d("flutter-refruiter: onConnected: $message");
  54. // },
  55. );
  56. jpush.setup(
  57. appKey: "23dedb30175208f894d3756f",
  58. channel: "developer-default",
  59. production: AppConstant.inProduction,
  60. debug: !AppConstant.inProduction, // 设置是否打印 debug 日志
  61. );
  62. //申请iOS授权
  63. jpush.applyPushAuthority(const NotificationSettingsIOS(sound: true, alert: true, badge: true));
  64. }
  65. /// 获取极光推送的id
  66. Future<String> getRegistrationId() async {
  67. JPush jpush = JPush();
  68. return jpush.getRegistrationID();
  69. }
  70. }
  71. var jpush = JPushReceive();