Flutter集成极光推送实现消息推送

这又是一个新的知识点,安卓已经亲测成功(ios目前客户端完成了推送,客户端接收到了推送,但是通知栏不显示,得继续研究下),下面上教程:

首先到极光官网注册个账户:极光官网

然后按照以下流程创建应用 :

然后在弹出来的对话框中输入应用名称,上传个图标,应用创建ok~

应用创建后会得到AppKey和Master Secret这两个key就是接下来要用到的了~可以先在网站上测试推送,在开发者服务里先设置以下推送设置(先贴安卓端),安卓端的好弄,配置上包名就可以了(ios端待小编弄好了一起贴)

 目标平台暂时只能选Android,因为其他的都没配置,填写好表单就可以推送了,不出意外可以在手机通知栏看到推送消息

俺先贴一个服务端的代码,java后台:

首先pom引入极光依赖:springboot里已经集成了slf4j日志,不用引依赖也可以

<dependency>
    <groupId>cn.jpush.api</groupId>
    <artifactId>jpush-client</artifactId>
    <version>3.4.4</version>
</dependency>
public class JGPushClient {
    private static Logger log = LoggerFactory.getLogger(JGPushClient.class);
    private static String APPKEY  = “你的appkey”;
    private static String MASTERSECRET = "你的mastersecret";
    private JGPushClient () {
        throw new AssertionError("无法创建对象");
    }

    //推送指定用户
    public static int sendToAliasUser (List<String> alias, String nofificationTitle, String msgTitle, String msgContent, String extrasparam) {
        JPushClient jPushClient = new JPushClient(MASTER_SECRECT, APP_KEY);
        int result = 0;
        try {
            PushPayload pushPayload = JPushClientUtil.buildPushObject_all_alias_alertWithTitle(alias, nofificationTitle, msgTitle, msgContent, extrasparam);
            PushResult pushResult = jPushClient.sendPush(pushPayload);
            if (pushResult.getResponseCode() == 200) {
                result = 1;
            }
            log.info("[极光推送结果]" + pushResult);
        } catch (APIConnectionException e) {
            log.info("[极光推送连接异常]", e);
//            e.printStackTrace();
        } catch (APIRequestException e) {
            log.info("[极光推送请求异常]", e);
            log.info("[极光推送请求状态]", e.getStatus());
            log.info("[极光推送请求错误码]", e.getErrorCode());
            log.info("[极光推送请求错误信息]", e.getErrorMessage());
//            e.printStackTrace();
        }
        return 0;
    }

    //推送指定用户(定时)
    public static int sendToAliasUserByTime (List<String> alias, String nofificationTitle, String msgTitle, String msgContent, String extrasparam, String time) {
        JPushClient jPushClient = new JPushClient(MASTER_SECRECT, APP_KEY);
        int result = 0;
        try {
            PushPayload pushPayload = JPushClientUtil.buildPushObject_all_alias_alertWithTitle(alias, nofificationTitle, msgTitle, msgTitle, extrasparam);
            ScheduleResult scheduleResult = jPushClient.createSingleSchedule("", time, pushPayload);
            if (scheduleResult.getResponseCode() == 200) {
                result = 1;
            }
            log.info("[极光推送结果]" + scheduleResult);
        } catch (APIConnectionException e) {
            log.info("[极光推送连接异常]", e);
//            e.printStackTrace();
        } catch (APIRequestException e) {
            log.info("[极光推送请求异常]", e);
            log.info("[极光推送请求状态]", e.getStatus());
            log.info("[极光推送请求错误码]", e.getErrorCode());
            log.info("[极光推送请求错误信息]", e.getErrorMessage());
//            e.printStackTrace();
        }
        return result;
    }

    //推送安卓用户
    public static int sendToAllAndroidUser (String nofificationTitle, String msgTitle, String msgContent, String extrasparam) {
        int result = 0;
        try {
            PushPayload pushPayload = JPushClientUtil.buildPushObject_android_all_alertWithTitle(nofificationTitle, msgTitle, msgContent, extrasparam);
            PushResult pushResult = jPushClient.sendPush(pushPayload);
            if (pushResult.getResponseCode() == 200) {
                result = 1;
            }
            log.info("[极光推送结果]" + pushResult);
        } catch (APIConnectionException e) {
            log.info("[极光推送连接异常]", e);
//            e.printStackTrace();
        } catch (APIRequestException e) {
            log.info("[极光推送请求异常]", e);
            log.info("[极光推送请求状态]", e.getStatus());
            log.info("[极光推送请求错误码]", e.getErrorCode());
            log.info("[极光推送请求错误信息]", e.getErrorMessage());
//            e.printStackTrace();
        }
        return result;
    }

    //推送ios用户
    public static int sendToAllIosUser (String nofificationTitle, String msgTitle, String msgContent, String extrasparam) {
        int result = 0;
        try {
            PushPayload pushPayload = JPushClientUtil.buildPushObject_ios_all_alertWithTitle(nofificationTitle, msgTitle, msgContent, extrasparam);
            PushResult pushResult = jPushClient.sendPush(pushPayload);
            if (pushResult.getResponseCode() == 200) {
                result = 0;
            }
            log.info("[极光推送结果]" + pushResult);
        } catch (APIConnectionException e) {
            log.info("[极光推送连接异常]", e);
//            e.printStackTrace();
        } catch (APIRequestException e) {
            log.info("[极光推送请求异常]", e);
            log.info("[极光推送请求状态]", e.getStatus());
            log.info("[极光推送请求错误码]", e.getErrorCode());
            log.info("[极光推送请求错误信息]", e.getErrorMessage());
//            e.printStackTrace();
        }
        return result;
    }

    //推送所有用户
    public static int sendToAll (String nofificationTitle, String msgTitle, String msgContent, String extrasparam) {
        int result = 0;
        try {
            PushPayload pushPayload = JPushClientUtil.buildPushObject_android_and_ios(nofificationTitle, msgTitle, msgContent, extrasparam);
            PushResult pushResult = jPushClient.sendPush(pushPayload);
            if (pushResult.getResponseCode() == 200) {
                result = 0;
            }
            log.info("[极光推送结果]" + pushResult);
        } catch (APIConnectionException e) {
            log.info("[极光推送连接异常]", e);
//            e.printStackTrace();
        } catch (APIRequestException e) {
            log.info("[极光推送请求异常]", e);
            log.info("[极光推送请求状态]", e.getStatus());
            log.info("[极光推送请求错误码]", e.getErrorCode());
            log.info("[极光推送请求错误信息]", e.getErrorMessage());
//            e.printStackTrace();
        }
        return result;
    }

    //推送所有用户(定时)
    public static int sendToAllByTime (String nofificationTitle, String msgTitle, String msgContent, String extrasparam, String time) {
        JPushClient jPushClient = new JPushClient(MASTER_SECRECT, APP_KEY);
        int result = 0;
        try {
            PushPayload pushPayload = JPushClientUtil.buildPushObject_android_and_ios(nofificationTitle, msgTitle, msgTitle, extrasparam);
            ScheduleResult scheduleResult = jPushClient.createSingleSchedule("", time, pushPayload);
            if (scheduleResult.getResponseCode() == 200) {
                result = 1;
            }
            log.info("[极光推送结果]" + scheduleResult);
        } catch (APIConnectionException e) {
            log.info("[极光推送连接异常]", e);
//            e.printStackTrace();
        } catch (APIRequestException e) {
            log.info("[极光推送请求异常]", e);
            log.info("[极光推送请求状态]", e.getStatus());
            log.info("[极光推送请求错误码]", e.getErrorCode());
            log.info("[极光推送请求错误信息]", e.getErrorMessage());
//            e.printStackTrace();
        }
        return result;
    }

    //推送安卓用户实现方法
    private static PushPayload buildPushObject_allAndroid(String notification_title, String msg_title, String msg_content, String extrasparam) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.all())
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(msg_content)
                                .setTitle(notification_title)
                                .addExtra("url",extrasparam)
                                .build())
                        .build()
                )
                .setMessage(Message.newBuilder()
                        .setMsgContent(msg_content)
                        .setTitle(msg_title)
                        .addExtra("url",extrasparam)
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .setSendno(1)
                        .setTimeToLive(86400)
                        .build())
                .build();
    }

    //推送ios用户实现方法
    private static PushPayload buildPushObject_allIos(String nofificationTitle, String msgTitle, String msgContent, String extrasparam) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.all())
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(msgContent)
                                .incrBadge(1)
                                .setSound("sound.caf")
                                .addExtra("url",extrasparam)
                                // .setContentAvailable(true)
                                .build())
                        .build()
                )
                .setMessage(Message.newBuilder()
                        .setMsgContent(msgContent)
                        .setTitle(msgTitle)
                        .addExtra("url",extrasparam)
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)
                        .setSendno(1)
                        .setTimeToLive(86400)
                        .build())
                .build();
    }

    //推送所有用户实现方法
    private static PushPayload buildPushObject_allAndroidAndIos(String notification_title, String msg_title, String msg_content, String extrasparam) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.all())
                .setNotification(Notification.newBuilder()
                        .setAlert(msg_content)
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(msg_content)
                                .setTitle(notification_title)
                                .addExtra("url",extrasparam)
                                .build()
                        )
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(msg_content)
                                .incrBadge(1)
                                .setSound("sound.caf")
                                .addExtra("url",extrasparam)
                                // .setContentAvailable(true)
                                .build()
                        )
                        .build()
                )
                .setMessage(Message.newBuilder()
                        .setMsgContent(msg_content)
                        .setTitle(msg_title)
                        .addExtra("url",extrasparam)
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .setSendno(1)
                        .setTimeToLive(86400)
                        .build()
                )
                .build();
    }

    //推送所有别名实现方法
    private static PushPayload buildPushObject_allAlias(List<String> alias,String nofificationTitle, String msgTitle, String msgContent, String extrasparam) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                //指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
                .setAudience(Audience.alias(alias))
//                .setAudience(Audience.registrationId(registrationId))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(msgContent)
                                .setTitle(nofificationTitle)
                                .addExtra("url",extrasparam)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(msgContent)
                                .incrBadge(1)
                                .setSound("sound.caf")
                                .addExtra("url",extrasparam)
                                //此项说明此推送是一个background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
                                //取消此注释,消息推送时ios将无法在锁屏情况接收
                                 //.setContentAvailable(true)
                                .build())
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(msgContent)
                        .setTitle(msgTitle)
                        .addExtra("url",extrasparam)
                        .build())
                .setOptions(Options.newBuilder()
                        //此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
                        .setApnsProduction(true)
                        //此字段是给开发者自己给推送编号,方便推送者分辨推送记录
                        .setSendno(1)
                        .setTimeToLive(86400)
                        .build())
                .build();
    }

    //可以在本地直接测试
    public static void main (String[] args) {
        JGPushClient.sendToAllAndroidUser("通知", "", "审核已通过", "");
        //测试返回信息自行查看吧
    }
}

极光推送官方文档:文档

下面来实现以下flutter前端:

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

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    //我这里每次打开APP验证了一下用户是否登录,如果登录了,初始化JPush,并将用户ID设为alias,用于以后推送个别用户,获取用户信息代码没贴,各位需求不同,需要的话可以评论上或私聊我
    this._getUserInfo();
  }

  Future<void> initPlatformState() async {}
  
  String debugLabel = 'Unknown';
  final JPush jPush = new JPush();   //初始化插件
  String platformVersion;
  _getUserInfo () async {
    if (mounted) {
      jPush.addEventHandler(
        //接收通知
        onReceiveNotification: (Map<String, dynamic> message) async {
          print("接收到推送: $message");
          setState(() {
            debugLabel = "接收到推送: $message";
          });
        },
        //打开通知
        onOpenNotification: (Map<String, dynamic> message) async {
          print("打开推送: $message");
          setState(() {
            debugLabel = "打开推送: $message";
          });
        },
        onReceiveMessage: (Map<String, dynamic> message) async {
          print("flutter onReceiveMessage: $message");
          setState(() {
            debugLabel = "flutter onReceiveMessage: $message";
          });
        },
        onReceiveNotificationAuthorization: (Map<String, dynamic> message) async {
          print("flutter onReceiveNotificationAuthorization: $message");
          setState(() {
            debugLabel =
                  "flutter onReceiveNotificationAuthorization: $message";
          });
        }
      );

      jPush.setup(
        appKey: "你的appkey",
        channel: "theChannel",
        production: false,
        debug: true
      );

      jPush.setAlias(this.userInfo[0]["id"]).then((value) {
        print(value);
      });

      jPush.applyPushAuthority(new NotificationSettingsIOS(
        sound: true, alert: true, badge: true));

      jPush.getRegistrationID().then((rid) {
        print("flutter get registration id : $rid");
        setState(() {
          debugLabel = "flutter getRegistrationID: $rid";
        });
      });

      setState(() {
        debugLabel = platformVersion;
      });
    } else if (!mounted) {
      return ;
    }
  }

  @override
  Widget build(BuildContext context) {
    此处省略
  }
}

登录后设置 alias:每次登录后直接把alias设置上,把上面的初始化JPush代码粘贴到登录成功后执行就可以了,然后执行后端方法推送消息:效果如下~

大功告成~未完待续······

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章