Flutter推送通知插件jpush_google_flutter的使用

Flutter推送通知插件jpush_google_flutter的使用

安装

在工程 pubspec.yaml 文件中加入依赖:

dependencies:
  jpush_google_flutter: 1.1.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

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

使用

首先导入插件:

import 'package:jpush_google_flutter/jpush_google_flutter.dart';

接下来是一个完整的示例代码:

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:jpush_google_flutter/jpush_google_flutter.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String? debugLable = 'Unknown';
  final JPush jpush = new JPush();

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String? platformVersion;

    try {
      jpush.addEventHandler(
          onReceiveNotification: (Map<String, dynamic> message) async {
        print("flutter onReceiveNotification: $message");
        setState(() {
          debugLable = "flutter onReceiveNotification: $message";
        });
      }, onOpenNotification: (Map<String, dynamic> message) async {
        print("flutter onOpenNotification: $message");
        setState(() {
          debugLable = "flutter onOpenNotification: $message";
        });
      }, onReceiveMessage: (Map<String, dynamic> message) async {
        print("flutter onReceiveMessage: $message");
        setState(() {
          debugLable = "flutter onReceiveMessage: $message";
        });
      }, onReceiveNotificationAuthorization:
              (Map<String, dynamic> message) async {
        print("flutter onReceiveNotificationAuthorization: $message");
        setState(() {
          debugLable = "flutter onReceiveNotificationAuthorization: $message";
        });
      }, onNotifyMessageUnShow: (Map<String, dynamic> message) async {
        print("flutter onNotifyMessageUnShow: $message");
        setState(() {
          debugLable = "flutter onNotifyMessageUnShow: $message";
        });
      }, onInAppMessageShow: (Map<String, dynamic> message) async {
        print("flutter onInAppMessageShow: $message");
        setState(() {
          debugLable = "flutter onInAppMessageShow: $message";
        });
      }, onInAppMessageClick: (Map<String, dynamic> message) async {
        print("flutter onInAppMessageClick: $message");
        setState(() {
          debugLable = "flutter onInAppMessageClick: $message";
        });
      }, onConnected: (Map<String, dynamic> message) async {
        print("flutter onConnected: $message");
        setState(() {
          debugLable = "flutter onConnected: $message";
        });
      });
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    jpush.setAuth(enable: true);
    jpush.setup(
      appKey: "xxxxx", // 你自己应用的 AppKey
      channel: "theChannel",
      production: false,
      debug: true,
    );
    jpush.applyPushAuthority(
        new NotificationSettingsIOS(sound: true, alert: true, badge: true));

    // 获取注册 ID
    jpush.getRegistrationID().then((rid) {
      print("flutter get registration id : $rid");
      setState(() {
        debugLable = "flutter getRegistrationID: $rid";
      });
    });

    // iOS 要是使用应用内消息,请在页面进入离开的时候配置 pageEnterTo 和 pageLeave 函数,参数为页面名。
    jpush.pageEnterTo("HomePage"); // 在离开页面的时候请调用 jpush.pageLeave("HomePage");

    // 如果 widget 被从树中移除,而异步平台消息还在飞行中,则我们想丢弃回复而不是调用 setState 来更新我们的非存在的外观。
    if (!mounted) return;

    setState(() {
      debugLable = platformVersion;
    });
  }

  // 编写视图
  [@override](/user/override)
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Plugin example app'),
        ),
        body: new Center(
            child: new Column(children: [
          Container(
            margin: EdgeInsets.fromLTRB(10, 10, 10, 10),
            color: Colors.brown,
            child: Text(debugLable ?? "Unknown"),
            width: 350,
            height: 100,
          ),
          new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Text(" "),
                new CustomButton(
                    title: "发本地推送",
                    onPressed: () {
                      // 三秒后触发本地推送
                      var fireDate = DateTime.fromMillisecondsSinceEpoch(
                          DateTime.now().millisecondsSinceEpoch + 3000);
                      var localNotification = LocalNotification(
                          id: 234,
                          title: 'fadsfa',
                          buildId: 1,
                          content: 'fdas',
                          fireTime: fireDate,
                          subtitle: 'fasf',
                          badge: 5,
                          extra: {"fa": "0"});
                      jpush
                          .sendLocalNotification(localNotification)
                          .then((res) {
                        setState(() {
                          debugLable = res;
                        });
                      });
                    }),
                new Text(" "),
                new CustomButton(
                    title: "getLaunchAppNotification",
                    onPressed: () {
                      jpush.getLaunchAppNotification().then((map) {
                        print("flutter getLaunchAppNotification:$map");
                        setState(() {
                          debugLable = "getLaunchAppNotification success: $map";
                        });
                      }).catchError((error) {
                        setState(() {
                          debugLable = "getLaunchAppNotification error: $error";
                        });
                      });
                    }),
              ]),
          new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Text(" "),
                new CustomButton(
                    title: "setTags",
                    onPressed: () {
                      jpush.setTags(["lala", "haha"]).then((map) {
                        var tags = map['tags'];
                        setState(() {
                          debugLable = "set tags success: $map $tags";
                        });
                      }).catchError((error) {
                        setState(() {
                          debugLable = "set tags error: $error";
                        });
                      });
                    }),
                new Text(" "),
                new CustomButton(
                    title: "addTags",
                    onPressed: () {
                      jpush.addTags(["lala", "haha"]).then((map) {
                        var tags = map['tags'];
                        setState(() {
                          debugLable = "addTags success: $map $tags";
                        });
                      }).catchError((error) {
                        setState(() {
                          debugLable = "addTags error: $error";
                        });
                      });
                    }),
                new Text(" "),
                new CustomButton(
                    title: "deleteTags",
                    onPressed: () {
                      jpush.deleteTags(["lala", "haha"]).then((map) {
                        var tags = map['tags'];
                        setState(() {
                          debugLable = "deleteTags success: $map $tags";
                        });
                      }).catchError((error) {
                        setState(() {
                          debugLable = "deleteTags error: $error";
                        });
                      });
                    }),
              ]),
          new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Text(" "),
                new CustomButton(
                    title: "getAllTags",
                    onPressed: () {
                      jpush.getAllTags().then((map) {
                        setState(() {
                          debugLable = "getAllTags success: $map";
                        });
                      }).catchError((error) {
                        setState(() {
                          debugLable = "getAllTags error: $error";
                        });
                      });
                    }),
                new Text(" "),
                new CustomButton(
                    title: "cleanTags",
                    onPressed: () {
                      jpush.cleanTags().then((map) {
                        var tags = map['tags'];
                        setState(() {
                          debugLable = "cleanTags success: $map $tags";
                        });
                      }).catchError((error) {
                        setState(() {
                          debugLable = "cleanTags error: $error";
                        });
                      });
                    }),
              ]),
          new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Text(" "),
                new CustomButton(
                    title: "setAlias",
                    onPressed: () {
                      jpush.setAlias("thealias11").then((map) {
                        setState(() {
                          debugLable = "setAlias success: $map";
                        });
                      }).catchError((error) {
                        setState(() {
                          debugLable = "setAlias error: $error";
                        });
                      });
                    }),
                new Text(" "),
                new CustomButton(
                    title: "deleteAlias",
                    onPressed: () {
                      jpush.deleteAlias().then((map) {
                        setState(() {
                          debugLable = "deleteAlias success: $map";
                        });
                      }).catchError((error) {
                        setState(() {
                          debugLable = "deleteAlias error: $error";
                        });
                      });
                    }),
                new Text(" "),
                new CustomButton(
                    title: "getAlias",
                    onPressed: () {
                      jpush.getAlias().then((map) {
                        setState(() {
                          debugLable = "getAlias success: $map";
                        });
                      }).catchError((error) {
                        setState(() {
                          debugLable = "getAlias error: $error";
                        });
                      });
                    }),
              ]),
          new Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new Text(" "),
              new CustomButton(
                  title: "stopPush",
                  onPressed: () {
                    jpush.stopPush();
                  }),
              new Text(" "),
              new CustomButton(
                  title: "resumePush",
                  onPressed: () {
                    jpush.resumePush();
                  }),
            ],
          ),
          new Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new Text(" "),
              new CustomButton(
                  title: "clearAllNotifications",
                  onPressed: () {
                    jpush.clearAllNotifications();
                  }),
              new Text(" "),
              new CustomButton(
                  title: "setBadge",
                  onPressed: () {
                    jpush.setBadge(66).then((map) {
                      setState(() {
                        debugLable = "setBadge success: $map";
                      });
                    }).catchError((error) {
                      setState(() {
                        debugLable = "setBadge error: $error";
                      });
                    });
                  }),
            ],
          ),
          new Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new Text(" "),
              new CustomButton(
                  title: "通知授权是否打开",
                  onPressed: () {
                    jpush.isNotificationEnabled().then((bool value) {
                      setState(() {
                        debugLable = "通知授权是否打开: $value";
                      });
                    }).catchError((onError) {
                      setState(() {
                        debugLable = "通知授权是否打开: ${onError.toString()}";
                      });
                    });
                  }),
              new Text(" "),
              new CustomButton(
                  title: "打开系统设置",
                  onPressed: () {
                    jpush.openSettingsForNotification();
                  }),
            ],
          ),
        ])),
      ),
    );
  }
}

/// 封装控件
class CustomButton extends StatelessWidget {
  final VoidCallback? onPressed;
  final String? title;

  const CustomButton({[@required](/user/required) this.onPressed, [@required](/user/required) this.title});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return new TextButton(
      onPressed: onPressed,
      child: new Text("$title"),
      style: new ButtonStyle(
        foregroundColor: MaterialStateProperty.all(Colors.white),
        overlayColor: MaterialStateProperty.all(Color(0xff888888)),
        backgroundColor: MaterialStateProperty.all(Color(0xff585858)),
        padding: MaterialStateProperty.all(EdgeInsets.fromLTRB(10, 5, 10, 5)),
      ),
    );
  }
}

更多关于Flutter推送通知插件jpush_google_flutter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter推送通知插件jpush_google_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


jpush_google_flutter 是一个用于在 Flutter 应用中集成极光推送(JPush)的插件。它支持 Android 和 iOS 平台,并且可以与 Google Firebase Cloud Messaging (FCM) 集成使用。

以下是使用 jpush_google_flutter 插件的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 jpush_google_flutter 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  jpush_google_flutter: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 配置 Android 项目

android/app/build.gradle 文件中添加以下配置:

android {
    ...
    defaultConfig {
        ...
        manifestPlaceholders = [
            JPUSH_APPKEY: "your_jpush_appkey",  // 替换为你的 JPush AppKey
            JPUSH_CHANNEL: "developer-default", // 默认通道名称
        ]
    }
}

3. 配置 iOS 项目

ios/Runner/Info.plist 文件中添加以下配置:

<key>JPUSH_APPKEY</key>
<string>your_jpush_appkey</string>  <!-- 替换为你的 JPush AppKey -->
<key>JPUSH_CHANNEL</key>
<string>developer-default</string>  <!-- 默认通道名称 -->
<key>JPUSH_ISPRODUCTION</key>
<false/>  <!-- 设置为 true 表示生产环境,false 表示开发环境 -->

4. 初始化 JPush

在你的 Flutter 应用的 main.dart 文件中初始化 JPush:

import 'package:flutter/material.dart';
import 'package:jpush_google_flutter/jpush_google_flutter.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 JPush
  JPush jpush = JPush();
  await jpush.setup(
    appKey: "your_jpush_appkey",  // 替换为你的 JPush AppKey
    channel: "developer-default",
    production: false,  // 设置为 true 表示生产环境,false 表示开发环境
    debug: true,  // 开启调试模式
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'JPush Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('JPush Example'),
        ),
        body: Center(
          child: Text('JPush is ready!'),
        ),
      ),
    );
  }
}

5. 处理推送通知

你可以通过监听 JPush.onReceiveNotification 来处理接收到的推送通知:

JPush jpush = JPush();

void initPushListener() {
  jpush.onReceiveNotification.listen((Map<String, dynamic> message) {
    print("收到通知: $message");
  });
}

6. 获取 Registration ID

你可以通过 jpush.getRegistrationID() 方法来获取设备的 Registration ID:

void getRegistrationID() async {
  String registrationID = await jpush.getRegistrationID();
  print("Registration ID: $registrationID");
}

7. 设置别名和标签

你可以通过 jpush.setAlias()jpush.setTags() 方法来设置别名和标签:

void setAliasAndTags() async {
  await jpush.setAlias("user123");
  await jpush.setTags(["tag1", "tag2"]);
}

8. 停止和恢复推送

你可以通过 jpush.stopPush()jpush.resumePush() 方法来停止和恢复推送:

void stopPush() async {
  await jpush.stopPush();
}

void resumePush() async {
  await jpush.resumePush();
}

9. 处理点击通知事件

你可以通过 JPush.onOpenNotification 来处理用户点击通知的事件:

void initNotificationOpenListener() {
  jpush.onOpenNotification.listen((Map<String, dynamic> message) {
    print("用户点击了通知: $message");
  });
}

10. 处理自定义消息

你可以通过 JPush.onReceiveMessage 来处理接收到的自定义消息:

void initMessageListener() {
  jpush.onReceiveMessage.listen((Map<String, dynamic> message) {
    print("收到自定义消息: $message");
  });
}

11. 处理通知权限

在 iOS 上,你可能需要请求通知权限:

void requestNotificationPermission() async {
  await jpush.requestNotificationPermissions();
}

12. 处理后台消息

如果你需要处理后台消息,可以在 android/app/src/main/AndroidManifest.xml 中添加以下配置:

<service
    android:name="cn.jpush.android.service.PushService"
    android:enabled="true"
    android:exported="false">
    <intent-filter>
        <action android:name="cn.jpush.android.intent.REGISTER" />
        <action android:name="cn.jpush.android.intent.REPORT" />
        <action android:name="cn.jpush.android.intent.PushService" />
    </intent-filter>
</service>

13. 处理 iOS 后台消息

在 iOS 上,你需要在 AppDelegate.swift 中添加以下代码来处理后台消息:

import UIKit
import Flutter
import jpush_google_flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  
  override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    JPushService.registerDeviceToken(deviceToken)
  }
}

14. 处理 Android 后台消息

在 Android 上,你需要在 android/app/src/main/AndroidManifest.xml 中添加以下配置:

<receiver
    android:name="cn.jpush.android.service.PushReceiver"
    android:enabled="true"
    android:exported="false">
    <intent-filter>
        <action android:name="cn.jpush.android.intent.REGISTRATION" />
        <action android:name="cn.jpush.android.intent.MESSAGE_RECEIVED" />
        <action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED" />
        <action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" />
        <action android:name="cn.jpush.android.intent.CONNECTION" />
    </intent-filter>
</receiver>
回到顶部