uniapp轻松集成极光推送自定义消息+通知 Android极光 IOS极光 两行代码集成极光SDK

378 阅读2分钟

###【前言】

极光推送(JPush)在为开发者提供基础推送服务的同时,还提供了用户精准标签、用户分群、地理围栏、应用内消息、智能发送策略、智能促活等服务能力,可有效提升消息的送达率、展示率和点击率,通过精细化运营触达助力 APP 提升日活和留存。基于项目使用了uniapp框架做开发,为了更方便的接入极光,统一数据处理,开始着手开发android+ios统一的极光推送插件。

在这里插入图片描述

\

Android 原生插件注册函数


manifestPlaceholders = [

           //JPush 上注册的包名对应的 Appkey.

           JPUSH_APPKEY : "691f92dbc65e43105a61b361",

   ]

   

    // 读取配置在build.gradle里manifestPlaceholders的参数appkey

    public String getAppkey(){

        ApplicationInfo appInfo = null;

        String msg="";

        try {

            appInfo = mUniSDKInstance.getContext().getPackageManager()

                    .getApplicationInfo(mUniSDKInstance.getContext().getPackageName(),

                            PackageManager.GET_META_DATA);

            msg=appInfo.metaData.getString("JPUSH_APPKEY");

        } catch (PackageManager.NameNotFoundException e) {

            e.printStackTrace();

        }

        return msg;

    }

\


    @UniJSMethod(uiThread = true)

    public void registerJPush(UniJSCallback callback){

        this.callback = callback;

\


        CallBackUtil.newInstance().setBackEvent(callback);

\


        String appkey = getAppkey();

        JPushInterface.setDebugMode(true);

        JPushUPSManager.registerToken(mUniSDKInstance.getContext(), appkey, null, "", new UPSRegisterCallBack() {

            @Override

            public void onResult(TokenResult tokenResult) {

                UniLogUtils.e("注册结果:"+tokenResult.getToken());

                showLog("注册:"+(tokenResult.getReturnCode() == 0 ? "成功":"失败")+"("+tokenResult.getToken()+")");

            }

        });

    }

\


\

Android 原生插件设置别名和标签


    // 设置标签

    @UniJSMethod(uiThread = true)

    public void setTags(JSONObject options){

        if(options != null){

            JSONArray tags = options.getJSONArray("tags");

            Set<String> sets = new HashSet<String>();

\


            for (int i = 0 ; i < tags.size(); i++){

                String tag = (String) tags.get(i);

                sets.add(tag);

            }

            JPushInterface.setTags(mUniSDKInstance.getContext(),1025,sets);

            showLog("设置标签成功:["+sets.toString()+"]");

        }

    }

    

    // 设置别名

    @UniJSMethod(uiThread = true)

    public void setAlias(JSONObject options){

        if(options != null){

            String alias = options.getString("alias");

            JPushInterface.setAlias(mUniSDKInstance.getContext(), 1024, alias);

            showLog("设置别名成功:["+alias+"]");

        }

    }

    

    // 查询标签

    @UniJSMethod(uiThread = true)

    public void queryTags(){

        JPushInterface.getAllTags(mUniSDKInstance.getContext(),1027);

    }

\


    // 查询别名

    @UniJSMethod(uiThread = true)

    public void queryAlias(){

        JPushInterface.getAlias(mUniSDKInstance.getContext(),1026);

    }

\

Android 原生插件设置手机号(可选)


    /**

     * 调用此 API 设置手机号码,用于 短信补充功能。该接口会控制调用频率,频率为 10s 之内最多 3 次。

     * 注:短信补充仅支持国内业务,号码格式为 11 位数字,有无 +86 前缀皆可。

     * 针对开发者提供推送补充服务,如果 App 侧一段时间内无法收到推送的消息(可能由于断网、后台禁止运行、消息延迟等原因)的用户进行短信通道信息补充。

     * 对于到达强需求的业务优先使用推送可以一定程度减少短信费用开销,又能保证信息最终的传递到达。

     */

    @UniJSMethod(uiThread = true)

    public void setMobile(JSONObject options){

        if(options != null){

            String mobile = options.getString("mobile");

            JPushInterface.setMobileNumber(mUniSDKInstance.getContext(),1026,mobile);

            showLog("手机号设置成功:"+mobile);

        }

    }

\

IOS 原生插件 注册


UNI_EXPORT_METHOD(@selector(registerJPush:))

#pragma  初始化

- (void) registerJPush:(UniModuleKeepAliveCallback) callback{

    [self logger:@"initJPushService" log:nil];

    self.callback = callback;

    [JPushStore shared].dataCallback = callback;

    [[JPushStore shared] initJPushService:[JPushStore shared].launchOptions];

    [self showLog:@"初始化极光模块"];

}

\

IOS 原生插件别名标签设置查询


\


// 新增tags

- (void)setTags:(NSDictionary *)params {

    NSSet *tags = [NSSet setWithArray:params[@"tags"]];

    [JPUSHService addTags:tags completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {

        NSString *stringInt = [NSString stringWithFormat:@"%ld", (long)iResCode];

        [self showLog:[@"【极光推送】标签设置状态:" stringByAppendingString:stringInt]];

    } seq:1000];

}

\


// 更新tags

- (void)updateTags:(NSDictionary *)params {

    NSSet *tags = [NSSet setWithArray:params[@"tags"]];

    [JPUSHService setTags:tags completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {

        NSString *stringInt = [NSString stringWithFormat:@"%ld", (long)iResCode];

        [self showLog:[@"【极光推送】标签更新状态:" stringByAppendingString:stringInt]];

    } seq:1001];

}

\


// 删除所有tags

- (void)cleanTags:(NSDictionary *)params {

    [JPUSHService cleanTags:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {

        NSString *stringInt = [NSString stringWithFormat:@"%ld", (long)iResCode];

        [self showLog:[@"【极光推送】全部标签清除状态:" stringByAppendingString:stringInt]];

    } seq:1002];

}

\


// 删除指定的tags

- (void)deleteTags:(NSDictionary *)params {

    NSSet *tags = [NSSet setWithArray:params[@"tags"]];

    [JPUSHService deleteTags:tags completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {

        NSString *stringInt = [NSString stringWithFormat:@"%ld", (long)iResCode];

        [self showLog:[@"【极光推送】指定标签删除状态:" stringByAppendingString:stringInt]];

    } seq:1003];

}

\


// 查询所有tags

- (void)queryTags:(NSDictionary *)params {

    [JPUSHService getAllTags:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {

        NSArray *tempTags = (iTags.allObjects.count > 0 ? iTags.allObjects : @[]);

        NSDictionary *result = @{@"data":tempTags};

        [self showLog:result withType:@"tags"];

    } seq:1004];

}

\


// 查询某一个tag

- (void)queryTag:(NSDictionary *)params {

    NSString *tag = params[@"tag"];

    [JPUSHService validTag:tag completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq, BOOL isBind) {

        NSArray *tempTags = (iTags.allObjects.count > 0 ? iTags.allObjects : @[]);

        NSDictionary *result = @{@"data":tempTags};

        [self showLog:result withType:@"tags"];

    } seq:1005];

}

\


// 设置别名

- (void)setAlias:(NSDictionary *)params {

    NSString *alias = params[@"alias"];

    [JPUSHService setAlias:alias completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {

        NSString *stringInt = [NSString stringWithFormat:@"%ld", (long)iResCode];

        [self showLog:[@"【极光推送】别名设置状态:" stringByAppendingString:stringInt]];

    } seq:1006];

}

\


// 删除别名

- (void)deleteAlias:(NSDictionary *)params {

    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {

        NSString *stringInt = [NSString stringWithFormat:@"%ld", (long)iResCode];

        [self showLog:[@"【极光推送】别名删除状态:" stringByAppendingString:stringInt]];

    } seq:1007];

}

\


// 查询别名

- (void)queryAlias:(NSDictionary *)params {

    [JPUSHService getAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {

        NSDictionary *result = @{@"data":iAlias};

        [self showLog:result withType:@"alias"];

    } seq:1008];

}

\

uniapp端调用


<template>

    <view>

        <view v-if="textContent" class="console_view">{{textContent}}</view>

        <view class="button red" @click="doRegisterJPush">注册极光[必须]</view>

        <view class="button gray" @click="doUnRegisterJPush">反注册极光</view>

        

        <view class="button gray" @click="doSetAlias">设置别名</view>

        <view class="button gray" @click="doQueryAlias">查询别名</view>

        <view class="button gray" @click="doSetTags">设置标签</view>

        <view class="button gray" @click="doQueryTags">查询标签</view>

        

        <view class="button gray" @click="stopPush">停止推送服务</view>

        <view class="button gray" @click="resumePush">恢复推送服务</view>

\


        <view class="button gray" @click="setPushTime">设置推送时间</view>

        <view class="button gray" @click="setSilenceTime">设置静默时间</view>

        

        <view class="button gray" @click="setMobile">设置手机号</view>

        

    </view>

</template>

\


<script>

    const JPush = uni.requireNativePlugin("luanqing-jgpush");

    

    export default {

        data() {

            return {

                textContent:'',

            }

        },

        methods: {

            // 注册推送服务(如有业务需求可以设置一个storage值来控制是否执行,如应用场景是关闭推送后,需要用户去手动开启时,直接调用registerJPush会激活之前反注册掉的推送服务

            // 如果无此要求,可以在onReady或App.vue的onShow中调用本方法注册)

            doRegisterJPush(){

                // Android + IOS

                // 在此传入回调,用于接收消息

                JPush.registerJPush((res=>{

                    let mesType = res.type;

                    try{

                        this.textContent = JSON.stringify(res||{});

                    }catch(e){

                        console.error("解析出现异常:",e);

                        this.textContent = '解析出现异常:'+e;

                    }

                    

                    if(mesType === 'log'){

                        console.log("栾青网络科技-极光消息推送插件:",(res.data??{}));

                    }else{

                        let data = res.data;

                        if(mesType === 'notice'){

                            console.error("极光消息-收到通知:",data);

                        }else if(mesType === 'custom'){

                            console.error("极光消息-收到自定义消息:",data);

                        }else if(mesType === 'notice-open'){

                            console.error("极光消息-点击了通知:",data);

                        }else if(mesType === 'notice-button-open'){

                            console.error("极光消息-点击了通知上的按钮:",data);

                        }else if(mesType === 'tags'){

                            console.error("极光消息-查询标签:",data);

                        }else if(mesType === 'alias'){

                            console.error("极光消息-查询别名:",data);

                        }

                    }

                }));

            },

            // 解除注册,无法再收到消息除非重新registerJPush或重新安装app

            doUnRegisterJPush(){

                JPush.unregisterJPush();

            },

            // 查询别名(数据在registerJPush的回调函数中返回)

            doQueryAlias(){

                // Android + IOS

                JPush.queryAlias();

            },

            // 查询本机的所有标签(数据在registerJPush的回调函数中返回)

            doQueryTags(){

                // Android + IOS

                JPush.queryTags();

            },

            // 设置别名: 传入alias,后台可根据此别名来指定发送消息(注:此为覆盖模式,非追加)

            doSetAlias(){

                // Android + IOS

                JPush.setAlias({alias:"xushiyong5"});

            },

            // 设置标签: 传入tags,可传多个,后台可根据此别名来指定发送消息(注:此为覆盖模式,非追加)

            doSetTags(){

                // Android + IOS

                JPush.setTags({tags:["xushiyong1","xushiyong2"]});

            },

            // 停止推送 推送服务完全被停止

            stopPush(){

                JPush.stopPush();

            },

            // 恢复推送

            resumePush(){

                JPush.resumePush();

            },

            // 设置允许推送时间 (二十四小时制)

            setPushTime(){

                // 设置可推送时间为: 周一 ~ 周五  08 - 20

                JPush.setPushTime({days: [1,2,3,4,5], startHour:8, endHour:20});

            },

            // 设置静默时间 (二十四小时制)

            setSilenceTime(){

                // 00:30  ~  06:30 之间为静默时间,此时间段内收到消息不震动不发声 免打扰

                JPush.setSilenceTime({startHour:0,endHour:6,startMinute:30,endMinute:30});

            },

            // 设置手机号

            setMobile(){

                // Android + IOS

                JPush.setMobile({mobile:'15921627041'});

            }

        }

    }

</script>

\


<style>

    .console_view{

        width: 700rpx;

        background-color: #E9E9E9;

        color: #666666;

        font-size: 28rpx;

        padding: 25rpx;

        margin-bottom: 15rpx;

    }

    .red{

        background-color: #E00300;

        color: #ffffff;

    }

    .gray{

        background-color: #BBBBBB;

        color: #333333;

    }

    .button{

        width: calc(80vw);

        margin-left: calc(10vw);

        margin-right: calc(10vw);

        padding-top: 12rpx;

        padding-bottom: 12rpx;

        margin-top: 20rpx;

        text-align: center;

        border-radius: 25rpx;

        font-size: 34rpx;

        font-weight: bold;

    }

    .button:active{

        background-color: aquamarine;

        color: #E00300;

    }

</style>

\


\

后语

至此插件开发完成,在uniapp项目中引用插件即可,插件为Android和IOS提供了统一的操作函数和数据格式,方便开发者调用,同时比极光官方更便捷的集成方式,让开发者节省下90%的开发时间。

\

插件下载地址: 点击前往

\

效果展示图

\

\

\