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

这篇具有很好参考价值的文章主要介绍了flutter开发实战-实现推送功能Push Notification。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

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

一、效果图

效果图如下
flutter开发实战-实现推送功能Push Notification,flutter,flutter开发实战,移动开发,flutter,android,iOS,推送,notification

二、代码实现

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

2.1、引入jpush_flutter

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

 # 集成极光推送 pub 集成
  jpush_flutter: ^2.4.2
  flutter_app_badger: ^1.5.0

2.2、配置

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

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 来初始化插件,才能保证其他功能正常工作。

实现代码

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中进行初始化。

/// 配置推送JPush

  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,flutter,flutter开发实战,移动开发,flutter,android,iOS,推送,notification

三、小结

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

学习记录,每天不停进步。文章来源地址https://www.toymoban.com/news/detail-602414.html

到了这里,关于flutter开发实战-实现推送功能Push Notification的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • flutter开发实战-hero实现图片预览功能extend_image

    flutter开发实战-hero实现图片预览功能extend_image 在开发中,经常遇到需要图片预览,当feed中点击一个图片,开启预览,多个图片可以左右切换swiper,双击图片及手势进行缩放功能。 这个主要实现使用extend_image插件。在点击图片时候使用hero动画进行展示。 Hero简单使用,可以查

    2024年02月08日
    浏览(32)
  • flutter开发实战-自定义相机camera功能

    flutter开发实战-自定义相机camera功能。 Flutter 本质上只是一个 UI 框架,运行在宿主平台之上,Flutter 本身是无法提供一些系统能力,比如使用蓝牙、相机、GPS等,因此要在 Flutter 中调用这些能力就必须和原生平台进行通信。 实现相机功能,我们使用的是camera插件。 在pubspec.

    2024年02月15日
    浏览(35)
  • 《vue3实战》运用push()方法实现电影评价系统的添加功能

    目录 前言 电影评价系统的添加功能是什么? 电影评价系统的添加功能有什么作用? 一、push()方法是什么?它有什么作用? 含义: 作用: 二、功能实现 这段是添加开始时点击按钮使添加框展示的代码部分: 这段是添加过程中结合elment plus组件实现的添加框的代码部分:

    2024年02月10日
    浏览(29)
  • flutter开发实战-video_player视频播放功能及视频缓存

    flutter开发实战-video_player视频播放功能及视频缓存 最近开发过程中video_player播放视频, 在pubspec.yaml引入video_player 在iOS上,video_player使用的是AVPlayer进行播放。 在Android上,video_player使用的是ExoPlayer。 2.1 在iOS中的设置 在iOS工程中info.plist添加一下设置,以便支持Https,HTTP的视频

    2024年02月14日
    浏览(41)
  • Flutter开发笔记 —— 语音消息功能实现

    最近在开发一款即时通讯(IM)的聊天App,在实现语音消息功能模块后,写下该文章以做记录。 注:本文不提供相关图片资源以及IM聊天中具体实现代码,单论语音功能实现思路 需求分析 比起上来直接贴代码,我们先来逐步分析一下一个正常语音消息的需求是如何的? 长按语音

    2024年02月06日
    浏览(26)
  • 2023最新版uni-push2.0推送开发php调用

    使用 uni-push 2.0,服务端不支持用个推 api 推送,只能用 dcloud 提供的 服务端(云函数)推送。这就意味着网上很多集成个推sdk的形式已经不使用了。 文档详细记录了unipush2.0配置到最后云函数url化调用的全过程。 需要HBuilderX 3.5.1 及其以上版本支持 unipush基本介绍:https://www.

    2024年02月01日
    浏览(78)
  • flutter开发实战-MethodChannel实现flutter与iOS双向通信

    flutter开发实战-MethodChannel实现flutter与iOS双向通信 最近开发中需要iOS与flutter实现通信,这里使用的MethodChannel 如果需要flutter与Android实现双向通信,请看 https://blog.csdn.net/gloryFlow/article/details/132218837 这部分与https://blog.csdn.net/gloryFlow/article/details/132218837中的一致,这里实现一下

    2024年02月13日
    浏览(31)
  • flutter开发实战-inappwebview实现flutter与Javascript方法调用

    flutter开发实战-inappwebview实现flutter与Javascript方法调用 在使用inappwebview时候,需要flutter端与JS进行交互,调用相应的方法,在inappwebview中的JavaScript Handlers。 要添加JavaScript Handlers,可以使用InAppWebViewController.addJavaScriptHandler方法,在该方法中定义handlerName和JavaScript端调用它时要

    2024年02月03日
    浏览(31)
  • flutter开发实战-事件总线EventBus实现

    flutter开发实战-事件总线EventBus实现 在开发中,经常会需要一个广播机制,用以跨Widget事件通知。 事件总线 实现了订阅者模式,订阅者模式包含发布者和订阅者两种角色,可以通过事件总线来触发事件和监听事件。 实现eventBus 在工程的pubspec.yaml引入库 1.使用event_bus库 创建一

    2024年02月15日
    浏览(24)
  • flutter开发实战-MethodChannel实现flutter与原生Android双向通信

    flutter开发实战-MethodChannel实现flutter与原生Android双向通信 最近开发中需要原生Android与flutter实现通信,这里使用的MethodChannel MethodChannel:用于传递方法调用(method invocation)。 通道的客户端和宿主端通过传递给通道构造函数的通道名称进行连接 一个应用中所使用的所有通道名称

    2024年02月13日
    浏览(24)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包