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代碼粘貼到登錄成功後執行就可以了,然後執行後端方法推送消息:效果如下~

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

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