flutter开发实战-实现推送功能Push Notification

flutter开发实战-实现推送功能Push Notification

推送服务现在可以说是所有 App 的标配了,最近在Flutter工程项目上实现推送功能。flutter上实现推送功能需要依赖原生的功能,需要插件实现,这里使用的是极光推送的服务。

一、效果图

效果图如下

二、代码实现

在使用极光推送功能时,需要使用的是极光提供的flutter推送插件jpush_flutter

2.1、引入jpush_flutter

在工程的pubspec.yaml文件中引入库

dart 复制代码
 # 集成极光推送 pub 集成
  jpush_flutter: ^2.4.2
  flutter_app_badger: ^1.5.0

2.2、配置

配置

Android:

在 /android/app/build.gradle 中添加下列代码:

dart 复制代码
android: {
  ....
  defaultConfig {
    applicationId "替换成自己应用 ID"
    ...
    ndk {
	//选择要添加的对应 cpu 类型的 .so 库。
	abiFilters 'armeabi', 'armeabi-v7a', 'x86', 'x86_64', 'mips', 'mips64', 'arm64-v8a',        
    }

    manifestPlaceholders = [
        JPUSH_PKGNAME : applicationId,
        JPUSH_APPKEY : "appkey", // NOTE: JPush 上注册的包名对应的 Appkey.
        JPUSH_CHANNEL : "developer-default", //暂时填写默认值即可.
    ]
  }  

iOS:

在 xcode8 之后需要点开推送选项: TARGETS -> Capabilities -> Push Notification 设为 on 状态

iOS需要使用开发者账号配置推送证书。这里就不描述了。

2.3、实现JPushManager

针对极光的推送服务,我们需要封装一下,实现JPushManager。

初始化setup

需要先调用 JPush.setup 来初始化插件,才能保证其他功能正常工作。

实现代码

dart 复制代码
import 'package:flutter_app_dfaceintl/config/logger_manager.dart';
import 'package:jpush_flutter/jpush_flutter.dart';

typedef OnJPushEventHandler = void Function(Map<String, dynamic> event);

// 处理极光推送
class JPushManager {
  // 私有构造函数
  JPushManager._internal() {
    // 添加callback
    addJPushEventHandler();
  }

  // 保存单例
  static JPushManager _singleton = JPushManager._internal();

  // 工厂构造函数
  factory JPushManager() => _singleton;

  final JPush jpush = new JPush();

  void addJPushEventHandler() {
    // 添加callback
    jpush.addEventHandler(
        onReceiveNotification: (Map<String, dynamic> message) async {
      LoggerManager().debug("flutter onReceiveNotification: $message");
    }, onOpenNotification: (Map<String, dynamic> message) async {
      LoggerManager().debug("flutter onOpenNotification: $message");
    }, onReceiveMessage: (Map<String, dynamic> message) async {
      LoggerManager().debug("flutter onReceiveMessage: $message");
    }, onReceiveNotificationAuthorization:
            (Map<String, dynamic> message) async {
      LoggerManager().debug("flutter onReceiveNotificationAuthorization: $message");
    });
  }

  void jPushRegister({
    required String appKey,
    required String channel,
    required bool production,
    required bool debug,
    bool sound = true,
    bool alert = true,
    bool badge = true,
    Function(String? registrationID)? onRegisterCallback,
  }) {
    jpush.setup(
      appKey: appKey, //你自己应用的 AppKey
      channel: channel,
      production: production,
      debug: debug,
    );
    jpush.applyPushAuthority(
        new NotificationSettingsIOS(sound: sound, alert: alert, badge: badge));

    // Platform messages may fail, so we use a try/catch PlatformException.
    jpush.getRegistrationID().then((rid) {
      LoggerManager().debug("flutter get registration id : $rid");
      if (onRegisterCallback != null) {
        onRegisterCallback(rid);
      }
    });
  }

  // 发送本地推送
  void sendLocalNotification(
      {required int id,
      required String title,
      required String content,
      required DateTime fireTime,
      int? buildId,
      Map<String, String>? extra,
      int badge = 0,
      String? soundName,
      String? subtitle,
      Function(String? res)? onCallback}) {
    // 三秒后出发本地推送
    var fireDate = DateTime.fromMillisecondsSinceEpoch(
        DateTime.now().millisecondsSinceEpoch + 3000);
    var localNotification = LocalNotification(
        id: id,
        // 通知 id, 可用于取消通知
        title: title,
        buildId: buildId,
        // 通知样式:1 为基础样式,2 为自定义样式
        content: content,
        fireTime: fireTime,
        subtitle: subtitle,
        badge: badge,
        extra: extra);
    jpush.sendLocalNotification(localNotification).then((res) {
      if (onCallback != null) {
        onCallback(res);
      }
    });
  }

  // 获取App启动的通知
  void getLaunchAppNotification({
    Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
  }) {
    jpush.getLaunchAppNotification().then((map) {
      LoggerManager().debug("flutter getLaunchAppNotification:$map");
      if (onCallback != null) {
        onCallback(map, null);
      }
    }).catchError((error) {
      if (onCallback != null) {
        onCallback(null, error);
      }
    });
  }

  // 设置setTags
  void setTags({
    required List<String> tags,
    Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
  }) {
    jpush.setTags(tags).then((map) {
      var tags = map['tags'];
      if (onCallback != null) {
        onCallback(map, null);
      }
    }).catchError((error) {
      if (onCallback != null) {
        onCallback(null, error);
      }
    });
  }

  // 添加addTags
  void addTags({
    required List<String> tags,
    Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
  }) {
    jpush.addTags(tags).then((map) {
      var tags = map['tags'];
      if (onCallback != null) {
        onCallback(map, null);
      }
    }).catchError((error) {
      if (onCallback != null) {
        onCallback(null, error);
      }
    });
  }

  // 删除deleteTags
  void deleteTags({
    required List<String> tags,
    Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
  }) {
    jpush.deleteTags(tags).then((map) {
      var tags = map['tags'];
      if (onCallback != null) {
        onCallback(map, null);
      }
    }).catchError((error) {
      if (onCallback != null) {
        onCallback(null, error);
      }
    });
  }

  // 获取所有Tags getAllTags
  void getAllTags({
    Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
  }) {
    jpush.getAllTags().then((map) {
      var tags = map['tags'];
      if (onCallback != null) {
        onCallback(map, null);
      }
    }).catchError((error) {
      if (onCallback != null) {
        onCallback(null, error);
      }
    });
  }

  // 清理tags cleanTags
  void cleanTags({
    Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
  }) {
    jpush.cleanTags().then((map) {
      var tags = map['tags'];
      if (onCallback != null) {
        onCallback(map, null);
      }
    }).catchError((error) {
      if (onCallback != null) {
        onCallback(null, error);
      }
    });
  }

  // 设置别名
  void setAlias({
    required String alias,
    Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
  }) {
    jpush.setAlias(alias).then((map) {
      var tags = map['tags'];
      if (onCallback != null) {
        onCallback(map, null);
      }
    }).catchError((error) {
      if (onCallback != null) {
        onCallback(null, error);
      }
    });
  }

  // 删除别名 deleteAlias
  void deleteAlias({
    Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
  }) {
    jpush.deleteAlias().then((map) {
      var tags = map['tags'];
      if (onCallback != null) {
        onCallback(map, null);
      }
    }).catchError((error) {
      if (onCallback != null) {
        onCallback(null, error);
      }
    });
  }

  // stopPush
  void stopPush() {
    jpush.stopPush();
  }

  // resumePush
  void resumePush() {
    jpush.resumePush();
  }

  // clearAllNotifications
  void clearAllNotifications() {
    jpush.clearAllNotifications();
  }

  // 设置setBadge
  void setBadge({
    required int badge,
    Function(Map<dynamic, dynamic>? map, dynamic? error)? onCallback,
  }) {
    jpush.setBadge(badge).then((map) {
      if (onCallback != null) {
        onCallback(map, null);
      }
    }).catchError((error) {
      if (onCallback != null) {
        onCallback(null, error);
      }
    });
  }

  // 通知授权是否打开
  void getNotificationEnabled({
    Function(bool value, dynamic? error)? onCallback,
  }) {
    jpush.isNotificationEnabled().then((bool value) {
      if (onCallback != null) {
        onCallback(value, null);
      }
    }).catchError((onError) {
      if (onCallback != null) {
        onCallback(false, onError);
      }
    });
  }

  // 打开系统设置
  void openSettingsForNotification() {
    jpush.openSettingsForNotification();
  }
}

2.3、使用Jpush极光推送

首先在MyApp.dart中进行初始化。

dart 复制代码
/// 配置推送JPush
@override
  void initState() {
    // TODO: implement initState
    super.initState();

    configJPush();
    jPushResetBadge();
  }

  void configJPush() {
    // TODO 替换极光推送的appKey,channel
    JPushManager().jPushRegister(
      appKey: "appKey",
      channel: "app-ios",
      production: false,
      debug: true,
      sound: true,
      alert: true,
      badge: true,
      onRegisterCallback: (String? registrationID) {
        LoggerManager().debug("configJPush registrationID:${registrationID}");
      },
    );
  }

/// 重置Badge
  Future<void> jPushResetBadge() async {
    JPushManager().setBadge(
      badge: 0,
      onCallback: (Map<dynamic, dynamic>? map, dynamic? error) {
        LoggerManager().debug("JPush resetBadge map:${map}, error:${error}");
      },
    );

    //直接使用remove方法
    bool isSupported = await FlutterAppBadger.isAppBadgeSupported();
    if (isSupported) {
      FlutterAppBadger.removeBadge();
    }
  }

具体效果

三、小结

flutter开发实战-实现推送功能Push Notification。推送服务现在可以说是所有 App 的标配了,最近在Flutter工程项目上实现推送功能。使用极光推送的服务jpush_flutter。

学习记录,每天不停进步。

相关推荐
千里马学框架1 天前
一起学 Android 14:ShellTransition 屏幕旋转过程深度剖析
android·智能手机·性能优化·framework·性能·屏幕旋转·rotation
美狐美颜SDK开放平台1 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk
AFinalStone1 天前
Android7 SystemUI源码解析(七)Keyguard锁屏模块深度解析
android·systemui
致远ccc2 天前
Google Play 上架前如何测试 App?多国家 Android 环境测试
android·app测试·googleplay·多国家应用测试
ttyyttemo2 天前
Kotlin 协程中的 Job 结构化并发与取消
android
sun0077002 天前
tbox 4g/5g切换,导致wan ip 改变,导致车机旧网络不可用。需要重启车机才行
android
其实防守也摸鱼2 天前
内网穿透与反向代理:原理、工具与实战指南
android·大数据·运维·安全·网络安全·自动化·渗透
茶底世界之下2 天前
为什么预览、录制、离线导出不能共享同一个背压策略?
ios·swift
AFinalStone2 天前
Android7 SystemUI 源码解析(四)NavigationBar 导航栏与 SystemBars
android·systemui
JMchen2 天前
属性动画原理与高级动画实现
android·kotlin·canvas