当前位置: 移动技术网 > IT编程>移动开发>Android > HWPushDemo【华为推送集成,基于2.6.1.301版本】

HWPushDemo【华为推送集成,基于2.6.1.301版本】

2019年04月25日  | 移动技术网IT编程  | 我要评论

道奇chargersrt8,活血镇痛胶囊,网络硬件知识

版权声明:本文为haiyuking原创文章,转载请注明出处!

前言

这个demo只是记录华为推送的集成,不能运行。

另外,因为可能用到存储权限,所以还需要搭配运行时权限申请功能。

使用步骤

一、项目组织结构图

注意事项:

1、  导入类文件后需要change包名以及重新import r文件路径

2、  values目录下的文件(strings.xml、dimens.xml、colors.xml等),如果项目中存在,则复制里面的内容,不要整个覆盖

二、导入步骤

2.1、接入准备

参考官网《》

注册成为开发者——》创建应用——》获取push服务参数 

最终是要能获得appid值

2.2、下载sdk(hms agent套件  、hms sdk两个)

(1)下载hms agent套件

(2)下载hms sdk

 因为现在大部分是使用android studio开发环境,所以直接使用gradle+maven集成方式。

2.3、先集成hms sdk(集成hms agent套件在后面会讲到)

(1)配置maven仓

项目的build.gradle文件中添加以下代码

// top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        

        // note: do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        //<!-- ======================华为推送sdk====================== -->
        maven {url 'http://developer.huawei.com/repo/'}
    }
}

task clean(type: delete) {
    delete rootproject.builddir
}

(2)在子工程(module)的build.gradle文件中添加依赖

为了便于统一管理,我在demo中新创建了一个thirdlib的module,集成华为推送sdk都放到thirdlib这个module中。

apply plugin: 'com.android.library'

android {
    compilesdkversion 28



    defaultconfig {
        minsdkversion 16
        targetsdkversion 28
        versioncode 1
        versionname "1.0"

        testinstrumentationrunner "android.support.test.runner.androidjunitrunner"

    }

    buildtypes {
        release {
            minifyenabled false
            proguardfiles getdefaultproguardfile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation filetree(dir: 'libs', include: ['*.jar'])

    implementation 'com.android.support:appcompat-v7:28.0.0'
    testimplementation 'junit:junit:4.12'
    androidtestimplementation 'com.android.support.test:runner:1.0.2'
    androidtestimplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    //华为推送sdk
    api 'com.huawei.android.hms:push:2.6.1.301'
}

(3)同步修改的文件

(4)还需要在app的build.gradle文件中依赖thirdlib这个module

apply plugin: 'com.android.application'

android {
    compilesdkversion 28
    defaultconfig {
        applicationid "com.why.project.hwpushdemo"
        minsdkversion 16
        targetsdkversion 28
        versioncode 1
        versionname "1.0"
        testinstrumentationrunner "android.support.test.runner.androidjunitrunner"
    }
    buildtypes {
        release {
            minifyenabled false
            proguardfiles getdefaultproguardfile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation filetree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testimplementation 'junit:junit:4.12'
    androidtestimplementation 'com.android.support.test:runner:1.0.2'
    androidtestimplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    //thirdlib
    implementation project(':thirdlib')
}

 2.4、集成hms agent套件

(1)解压包

(2)执行gethmsagent_xx.bat生成copysrc的文件夹,里面是根据您选择需要集成hms服务,抽取后的hmsagent代码(java 文件夹)和manifest文件(androidmanifest.xml)

 

gethmsagent_cn.bat为中文脚本
gethmsagent_oversea.bat为英文脚本

此时,多了一个copysrc目录

(3)拷贝copysrc/java里面的代码到您现有的工程。请保持hmsagent代码的包的路径和结构不变

 

2.5、配置app这个module的androidmanifest.xml

参考copysrc目录下的appmanifestconfig.xml文件中的相关代码和官网的资料!

注意,是app这个module,而不是thirdlib这个module!

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.why.project.hwpushdemo">

    <!-- ======================华为推送sdk====================== -->
    <!--hms-sdk引导升级hms功能,访问ota服务器需要网络权限 | hms-sdk upgrade hms feature, access to ota server requires network privileges-->
    <uses-permission android:name="android.permission.internet" />
    <!--hms-sdk引导升级hms功能,保存下载的升级包需要sd卡写权限 | hms-sdk upgrade hms feature, save downloaded upgrade pack requires sd card write permission-->
    <uses-permission android:name="android.permission.write_external_storage" />
    <!--检测网络状态 | detecting network status-->
    <uses-permission android:name="android.permission.access_network_state"/>
    <!--检测wifi状态 | detecting wifi status-->
    <uses-permission android:name="android.permission.access_wifi_state"/>
    <!--获取用户手机的imei,用来唯一的标识设备。 | gets the imei of the user's phone, used to uniquely identify the device.-->
    <uses-permission android:name="android.permission.read_phone_state"/>
    <!--如果是安卓8.0,应用编译配置的targetsdkversion>=26,请务必添加以下权限 -->
    <uses-permission android:name="android.permission.request_install_packages" />
    <!-- 接收push token的广播以及push消息需要定义该权限 ${package_name} 要替换上您应用的包名 -->
    <permission
        android:name="${applicationid}.permission.process_push_msg"
        android:protectionlevel="signatureorsystem"/>
    <!--接收push token的广播以及push消息需要定义该权限 ${package_name} 要替换上您应用的包名 -->
    <uses-permission android:name="${applicationid}.permission.process_push_msg" />

    <application
        android:allowbackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundicon="@mipmap/ic_launcher_round"
        android:supportsrtl="true"
        android:theme="@style/apptheme">
        <activity android:name=".mainactivity">
            <intent-filter>
                <action android:name="android.intent.action.main"/>

                <category android:name="android.intent.category.launcher"/>
            </intent-filter>
        </activity>

        <!-- ======================华为推送sdk====================== -->
        <!-- 接入hmssdk 需要注册的appid参数。value的值中“100222233444”用实际申请的appid替换,来源于开发者联盟网站应用的权益详情。
                    格式 android:value="appid=xxxxxx"
                    access hmssdk need to register appid parameters. value "100223344" is replaced with the actual application appid, derived from the developer affiliate website application.
                    format android:value= "appid=xxxxxx"-->
        <meta-data
            android:name="com.huawei.hms.client.appid"
            android:value="appid=1000222233444"/>

        <!-- 接入hmssdk 需要注册的activity | access hmssdk activity to be registered 定义了hms-sdk中一些跳转所需要的透明页面-->
        <activity
            android:name="com.huawei.hms.activity.bridgeactivity"
            android:configchanges="orientation|locale|screensize|layoutdirection|fontscale"
            android:excludefromrecents="true"
            android:exported="false"
            android:hardwareaccelerated="true"
            android:theme="@android:style/theme.translucent" >
            <meta-data
                android:name="hwc-theme"
                android:value="androidhwext:style/theme.emui.translucent" />
        </activity>

        <!-- 接入hmssdk 需要注册的activity | access hmssdk activity to be registered 是应用自升级接口所需要使用的页面-->
        <activity
            android:name="com.huawei.updatesdk.service.otaupdate.appupdateactivity"
            android:configchanges="orientation|screensize"
            android:exported="false"
            android:theme="@style/upsdkdldialog" >
            <meta-data
                android:name="hwc-theme"
                android:value="androidhwext:style/theme.emui.translucent.notitlebar" />
        </activity>

        <!-- 接入hmssdk 需要注册的activity | access hmssdk activity to be registered 是应用自升级接口所需要使用的页面-->
        <activity
            android:name="com.huawei.updatesdk.support.pm.packageinstalleractivity"
            android:configchanges="orientation|keyboardhidden|screensize"
            android:exported="false"
            android:theme="@style/upsdkdldialog" >
            <meta-data
                android:name="hwc-theme"
                android:value="androidhwext:style/theme.emui.translucent" />
        </activity>

        <!-- 接入hmssdk 需要注册的provider,authorities 一定不能与其他应用一样,所以这边 com.why.project.hwpushdemo 要替换上您应用的包名
            access hmssdk need to register provider,authorities must not be the same as other applications, so this side ${package_name} to replace the package name you applied
            用于应用自升级-->
        <provider
            android:name="com.huawei.updatesdk.fileprovider.updatesdkfileprovider"
            android:authorities="com.why.project.hwpushdemo.updatesdk.fileprovider"
            android:exported="false"
            android:granturipermissions="true">
        </provider>

        <!-- 接入hmssdk 需要注册的应用下载服务 | access hmssdk need to register app download service
        用于应用自升级-->
        <service android:name="com.huawei.updatesdk.service.deamon.download.downloadservice"
                 android:exported="false"/>

        <!-- 使用 hmsagent 代码接入hmssdk 需要注册的activity | use hmsagent code to access hmssdk activity that requires registration-->
        <!--解决华为移动服务升级问题的透明界面(必须声明)-->
        <activity
            android:name="com.huawei.android.hms.agent.common.hmsagentactivity"
            android:configchanges="orientation|locale|screensize|layoutdirection|fontscale"
            android:excludefromrecents="true"
            android:exported="false"
            android:hardwareaccelerated="true"
            android:theme="@android:style/theme.translucent" >
            <meta-data
                android:name="hwc-theme"
                android:value="androidhwext:style/theme.emui.translucent" />
        </activity>

        <!-- 接入hmssdk 需要注册的provider,authorities 一定不能与其他应用一样,所以这边 com.why.project.hwpushdemo 要替换上您应用的包名
           access hmssdk need to register provider,authorities must not be the same as other applications, so this side ${package_name} to replace the package name you applied
           用于hms-sdk引导升级hms,提供给系统安装器读取升级文件-->
        <provider
            android:name="com.huawei.hms.update.provider.updateprovider"
            android:authorities="com.why.project.hwpushdemo.hms.update.provider"
            android:exported="false"
            android:granturipermissions="true"/>

        <!-- 接入hmssdk push模块需要注册,第三方相关 :接收push消息(注册、push消息、push连接状态)广播,
                此receiver类需要开发者自己创建并继承com.huawei.hms.support.api.push.pushreceiver类,
                参考示例代码中的类:com.huawei.hmsagent.huaweipushrevicer
            access to the hmssdk push module requires registration:
                receive push message (registration, push message, push connection state) broadcast.
                this receiver class requires the developer to create and inherit the com.huawei.hms.support.api.push.pushreceiver class.
                reference to class in sample code: com.huawei.hmsagent.huaweipushrevicer-->
        <!--用来接收push消息的receiver-->
        <!-- 接入hmssdk push模块需要注册,第三方相关 :接收push消息(注册、push消息、push连接状态)广播,
                此receiver类需要开发者自己创建并继承com.huawei.hms.support.api.push.pushreceiver类,
                参考示例代码中的类:com.huawei.hmsagent.huaweipushrevicer
            access to the hmssdk push module requires registration:
                receive push message (registration, push message, push connection state) broadcast.
                this receiver class requires the developer to create and inherit the com.huawei.hms.support.api.push.pushreceiver class.
                reference to class in sample code: com.huawei.hmsagent.huaweipushrevicer-->
        <receiver android:name="com.why.project.hwpushdemo.huaweipush.huaweipushrevicer" >
            <intent-filter>
                <!-- 必须,用于接收token | must, for receiving token -->
                <action android:name="com.huawei.android.push.intent.registration" />
                <!-- 必须,用于接收消息 | must, used to receive messages-->
                <action android:name="com.huawei.android.push.intent.receive" />
                <!-- 可选,用于点击通知栏或通知栏上的按钮后触发onevent回调 | optional, click the button on the notification bar or the notification bar to trigger the onevent callback -->
                <action android:name="com.huawei.android.push.intent.click" />
                <!-- 可选,查看push通道是否连接,不查看则不需要 | optional, query whether the push channel is connected or not -->
                <action android:name="com.huawei.intent.action.push_state" />
            </intent-filter>
        </receiver>

        <!-- 接入hmssdk push模块需要注册 :接收通道发来的通知栏消息 | the access hmssdk push module needs to be registered: the notification bar message sent from the receiving channel -->
        <!--接收通道发来的通知栏消息-->
        <receiver android:name="com.huawei.hms.support.api.push.pusheventreceiver" >
            <intent-filter>
                <action android:name="com.huawei.intent.action.push" />
            </intent-filter>
        </receiver>
        <!-- 华为推送自定义动作打开的界面【需要透明】,需要注意scheme必须设置唯一的,和手机上其他的app使用的scheme不一样 -->
        <!--hwdemoscheme://{包名}/notify_detail?title={标题}&content={内容}-->
        <activity
            android:name="com.why.project.hwpushdemo.huaweipush.hwpushactivity"
            android:theme="@android:style/theme.translucent">
            <intent-filter>
                <action android:name="android.intent.action.view"/>
                <category android:name="android.intent.category.default"/>
                <data
                    android:host="${applicationid}"
                    android:path="/notify_detail"
                    android:scheme="hwdemoscheme"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

1、appid需要换成自己的;

2、将黄色标记的代码中的包名(com.why.project.hwpushdemo)全部替换成自己的包名(如果是从copysrc的appmanifestconfig.xml文件复制的代码,直接是自己的包名);

3、huaweipushrevicer【华为推送的回调,比如获取token】的完整路径需要更换成真实的;

4、hwpushactivity【点击通知后打开的界面】的完整路径需要更换成真实的;

5、hwpushactivity下的host、path、scheme要换成自己项目的,另外这三个字段的值在推送的时候用的到;

2.6、将huaweipushrevicer、hwpushactivity添加到项目中

其中,huaweipushrevicer不用管,hwpushactivity需要根据实际情况修改下,activity_hwpush.xml文件不用管,就是个空布局。

package com.why.project.hwpushdemo.huaweipush;

import android.app.activity;
import android.content.context;
import android.content.intent;
import android.os.bundle;
import android.util.log;

import com.why.project.hwpushdemo.r;

import org.json.jsonobject;


/**
 * created by haiyuking
 * used 华为推送自定义动作打开的界面【华为推送sdk】
 * https://www.jianshu.com/p/3b0df1c976a5
 * https://blog.csdn.net/gaoshang0304/article/details/80463246
 * https://blog.csdn.net/nsacer/article/details/80346965
 * https://blog.csdn.net/u013904672/article/details/71079278
 */
public class hwpushactivity extends activity {
    private static final string tag = hwpushactivity.class.getsimplename();

    private context mcontext;

    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_hwpush);

        mcontext = this;

        //获取自定义动作的值
        intent intent = getintent();
        string intenturi = intent.touri(intent.uri_intent_scheme);
        log.e(tag,"action是:" + intenturi);
        //intent://com.why.project.hwpushdemo/notify_detail?title=测试标题&content=测试内容&extratitle=界面标题&url=http://www.baidu.com#intent;scheme=hwdemoscheme;launchflags=0x13000000;component=com.why.project.hwpushdemo/.huaweipush.hwpushactivity;end

        //关闭当前界面,跳转到指定的界面
        try {
            string title = getintent().getdata().getqueryparameter("title");
            string content = getintent().getdata().getqueryparameter("content");
            string extratitle = getintent().getdata().getqueryparameter("extratitle");
            string url = getintent().getdata().getqueryparameter("url");

            jsonobject extrajson = new jsonobject();
            extrajson.put("extratitle",extratitle);
            extrajson.put("url",url);

            bundle bundle = new bundle();
            bundle.putstring(jpushinterface.extra_notification_title,title);//通知的标题
            bundle.putstring(jpushinterface.extra_alert,content);//通知内容
            bundle.putstring(jpushinterface.extra_extra,extrajson.tostring());//通知附加字段
            bundle.putint(jpushinterface.extra_notification_id,0);//通知id值【没什么用】

            intent i = new intent(mcontext, jpushactivity.class);
            i.putextras(bundle);
            i.setflags(intent.flag_activity_new_task);//必须使用这个,这个保证了多个通知,点击返回返回到的是上一个通知界面
            mcontext.startactivity(i);
            finish();

        } catch (exception e){
            e.printstacktrace();
        }

    }
}

 这里稍微讲解下,这个activity的主要作用是下面两点:

1、获取自定义动作的值;

2、关闭当前界面,跳转到指定的界面(传值过去);

上面代码中跳转界面那里(橙色标记的代码),是需要根据实际情况修改的。

2.7、将jpushactivity添加到项目中(仅供参考)

 

package com.why.project.hwpushdemo;

import android.content.context;
import android.content.intent;
import android.content.res.resources;
import android.os.bundle;
import android.support.v7.app.appcompatactivity;
import android.support.v7.widget.toolbar;
import android.view.keyevent;
import android.view.view;
import android.widget.textview;

import org.json.jsonexception;
import org.json.jsonobject;

/**
 * used 极光推送点开通知后打开的界面
 * 和webviewpreviewactivity共用一个布局文件
 * 需要先检查是否已经登录,如果没有登录,直接登录即可,不需要返回到登录界面了
 * 极光推送sdk
 */
public class jpushactivity extends appcompatactivity {
    private static final string tag = jpushactivity.class.getsimplename();

    /**从登录界面打开的标记(传递参数用)*/
    public static final string extra_onlogin = "onlogin";

    /*jpush传递过来的参数*/
    private bundle jpushbundle;
    /**通知标题*/
    private string jpushtitle;
    /**通知内容*/
    private string jpushcontent;
    /**通知附加字段*/
    private string jpushextrajson;
    /**通知id值*/
    private int jpushid;

    //展现在导航栏上的标题
    private string bundle_title;
    //网页url地址
    private string bundle_url;

    /**标记是否从登录界面打开的状态值*/
    private boolean bundle_onlogin = false;

    private context mcontext;

    private toolbar mtoolbar;

    private mywebview mywebview;

    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_webviewpreview);

        mcontext = this;

        //初始化控件
        initviews();
        //初始化数据
        initdata();
        inittoolbar();//初始化toolbar
    }

    @override
    public void ondestroy()
    {
        //销毁webview控件
        mywebview.removeallviews();
        mywebview.destroy();
        super.ondestroy();
    }

    /**
     * 初始化view
     */
    private void initviews() {
        mywebview = (mywebview)findviewbyid(r.id.id_webview);
        mywebview.setcanbackpreviouspage(true,jpushactivity.this);//可以返回上一页
    }

    /**
     * 初始化数据【接收点击通知栏传过来的数据:通知、自定义消息两种(这里只需要处理通知的即可)】
     */
    private void initdata() {
        intent intent = getintent();
        if (null != intent) {
            jpushbundle = getintent().getextras();
            jpushtitle = jpushbundle.getstring(jpushinterface.extra_notification_title);//保存服务器推送下来的通知的标题
            jpushcontent = jpushbundle.getstring(jpushinterface.extra_alert);//保存服务器推送下来的通知内容
            jpushextrajson = jpushbundle.getstring(jpushinterface.extra_extra);//保存服务器推送下来的附加字段。这是个 json 字符串
            jpushid = jpushbundle.getint(jpushinterface.extra_notification_id);//sdk 1.3.5 以上版本支持,通知栏的notification id,可以用于清除notification

            bundle_onlogin = jpushbundle.getboolean(extra_onlogin);
        }

        if(!jpushextrajson.equals("")){
            try {
                jsonobject extrajsonobj = new jsonobject(jpushextrajson);
                if(extrajsonobj.has("from")){
                    extrajsonobj = new jsonobject(extrajsonobj.getstring("from"));
                }
                if(!extrajsonobj.getstring("extratitle").equals("")){
                    //获取标题
                    bundle_title = extrajsonobj.getstring("extratitle");
                }
                if(!extrajsonobj.getstring("url").equals("")){
                    //获取网页地址
                    bundle_url = extrajsonobj.getstring("url");
                }
            } catch (resources.notfoundexception e) {
                // todo auto-generated catch block
                e.printstacktrace();
            } catch (jsonexception e) {
                // todo auto-generated catch block
                e.printstacktrace();
            }
        }

        if(! bundle_onlogin){//如果是从登录界面打开的话,那么不用验证了
            initcheckloginstate();//验证是否需要重新登录
        }else{
            loadweburl();//打开网页
        }

    }

    private void inittoolbar() {
        mtoolbar = findviewbyid(r.id.toolbar_base);
        mtoolbar.settitle("");//这样设置的话,自带的标题就不会显示
        //设置自定义的标题(居中)
        textview toolbartitle = mtoolbar.findviewbyid(r.id.toolbartitle);
        toolbartitle.settext(bundle_title);
        setsupportactionbar(mtoolbar);//由于toolbar只是一个普通控件,我们将toolbar设置为actionbar
        //设置导航图标要在setsupportactionbar方法之后
        mtoolbar.setnavigationicon(r.drawable.nav_back);//设置为空的话,就会不显示左侧的图标
        //对navigationicon添加点击
        mtoolbar.setnavigationonclicklistener(new view.onclicklistener() {
            @override
            public void onclick(view v) {
                //返回到首页界面(重新登录的情况下)或者直接关闭自己(不需要重新登录的情况下)
                backhomeorfinish();
            }
        });
    }

    /**
     * 点击返回键
     * event.getrepeatcount() == 0:点后退键的时候,为了防止点得过快,触发两次后退事件,故做此设置。
     */
    @override
    public boolean onkeydown(int keycode, keyevent event) {
        // todo auto-generated method stub
        if (keycode == keyevent.keycode_back && event.getrepeatcount() == 0) {
            //返回到首页界面(如果是从登录界面打开的)或者关闭自己(从通知打开的)
            backhomeorfinish();
        }
        return super.onkeydown(keycode, event);
    }


    //返回功能
    private void backhomeorfinish() {
        if (bundle_onlogin) {
            activityjump.normaljumpandfinish(jpushactivity.this, homeactivity.class);
        } else {
            activityjump.back(this);
        }
    }


    /**
     * 网络请求检查登录状态,主要判断是否在线
     */
    private void initcheckloginstate() {
        if(result.indexof("alert(") != -1){
            //登陆身份失效,请重新登陆
            activityjump.bundlejumpandfinish(jpushactivity.this, loginactivity.class,jpushbundle);
        }
        else{
            loadweburl();//加载网页
        }
    }

    /**
     * 加载url地址
     */
    private void loadweburl() {
        synccookie(jpushactivity.this, serverapi.server_url);

        if (!bundle_url.equals("")) {
            mywebview.loadweburl(serverapi.server_url + bundle_url);
        } else {
            mywebview.loadurl("about:blank");//加载一个空白页
        }
    }

    /**
     * sync cookie
     */
    public static void synccookie(context context, string url){
        //参考本博客的《okhttputils【 android 一个改善的okhttp封装库】使用(二)》
    }
}

 3、初始化agent

 在application的oncreate方法中初始化hmsagent。如果没有自己的application类,请创建并在manifest文件中配置application节点的name属性。

package com.why.project.hwpushdemo;

import android.app.application;

import com.huawei.android.hms.agent.hmsagent;

/**
 * created by haiyuking
 * used
 */
public class myapplication extends application {
    @override
    public void oncreate() {
        super.oncreate();

        //华为推送sdk
        inithuaweipush();
    }

    //华为推送sdk
    private void inithuaweipush(){
        hmsagent.init(this);
    }

    @override
    public void onterminate() {
        super.onterminate();
        //华为推送sdk
        hmsagent.destroy();
    }
}

4、调用connect接口

建议在应用启动时调用connect。在哪个activity中调用,哪个activity的alertdialog不弹出,返回软键点击后无响应。

package com.why.project.hwpushdemo;

import android.content.context;
import android.content.intent;
import android.os.bundle;
import android.support.v7.app.appcompatactivity;

import com.huawei.android.hms.agent.hmsagent;
import com.huawei.android.hms.agent.common.handler.connecthandler;
import com.huawei.android.hms.agent.push.handler.gettokenhandler;
import com.why.project.hwpushdemo.huaweipush.huaweipushrevicer;

import static com.why.project.hwpushdemo.huaweipush.huaweipushrevicer.action_token;
import static com.why.project.hwpushdemo.huaweipush.huaweipushrevicer.action_updateui;

/**
 * created by haiyuking
 * used
 */
public class welcomeactivity extends appcompatactivity implements huaweipushrevicer.ipushcallback{

    private static final string tag = welcomeactivity.class.getsimplename();

    private context mcontext;

    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_welcome);

        mcontext = this;

        /*====华为推送sdk相关=======*/
        huaweipushrevicer.registerpushcallback(this);

        /*========================华为推送sdk相关=======================*/
        hmsagent.connect(this, new connecthandler() {
            @override
            public void onconnect(int rst) {
                logutil.d(tag,"hms connect end:" + rst);
                //push的token会过期和失效,应用集成push后,推荐在每次启动应用时调用gettoken方法申请token,该方法可以重复调用,在有效期内获得的token值不会变化。
                //建议在应用的首个activity的oncreate方法中,调用申请token接口。【为什么呢?因为如果在homeactivity中调用的,alertdialog不弹出,返回软键点击后无响应】
                logutil.d(tag,"get token: begin");
                hmsagent.push.gettoken(new gettokenhandler() {
                    @override
                    public void onresult(int rtncode) {
                        logutil.d(tag,"get token: end code=" + rtncode);
                    }
                });
            }
        });
        //检查应用升级,暂时用不到
        /*hmsagent.checkupdate(this, new checkupdatehandler() {
            @override
            public void onresult(int rst) {
                logutil.d(tag,"check app update end:" + rst);
            }
        });*/
    }

    @override
    protected void ondestroy() {
        super.ondestroy();

        /*====华为推送sdk相关=======*/
        huaweipushrevicer.unregisterpushcallback(this);
    }

    @override
    public void onreceive(intent intent) {
        //===============华为推送sdk相关===============
        //其实放在这里有个风险,那就是可能执行不到这里,因为时间短,还没有等到返回数据就执行ondestory方法了
        if (intent != null) {
            string action = intent.getaction();
            bundle b = intent.getextras();
            if (b != null && action_token.equals(action)) {
                string hwtoken = b.getstring(action_token);
                logutil.e(tag,"hwtoken="+hwtoken);
                //保存数据,homeactivity中用得到
                preferencesutils.putstring(mcontext,globals.hwpush_token_key,hwtoken);
            } else if (b != null && action_updateui.equals(action)) {
                string log = b.getstring("log");
                logutil.e(tag,log);
            }
        }
    }

}

globals.java文件

package com.why.project.hwpushdemo;

/**
 * created by haiyuking
 * used
 */
public class globals {

    /*=======================================华为推送sdk相关=============================================*/
    //华为推送的token值
    public static final string hwpush_token_key = "hwpushtoken";
}

5、申请push token

package com.why.project.hwpushdemo;

import android.content.context;
import android.os.bundle;
import android.support.v7.app.appcompatactivity;

public class mainactivity extends appcompatactivity {

    private static final string tag = welcomeactivity.class.getsimplename();

    private context mcontext;

    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main);

        mcontext = this;

        /*====华为推送sdk相关=======*/
        gettoken();
    }

    /*========================华为推送sdk相关======start====================*/
    private void gettoken(){
        string hwtoken = preferencesutils.getstring(mcontext,globals.hwpush_token_key,"");
        logutil.e(tag,"hwtoken="+hwtoken);
        requestdeviceid(hwtoken);//判断是请求接口还是弹出对话框
    }

   //请求接口存储设备id或者token的方法
    private void requestdeviceid(string regid) {
        //首要条件是设备id值或者token值不为空,否则下面的判断没有意义了
        //如果没有设置过别名,或者则需要设置别名
        //如果服务器上的deviceid值是空值,表明当前用户还没有绑定任何设备,则直接请求接口,不需要弹出对话框;
        //如果服务器上的deviceid值不为空,并且客户端获取的设备id值和服务器上的deviceid值相同,则不需要弹出对话框,直接请求接口(这个是卸载重新安装的情况)
        //如果服务器上的deviceid值不为空,并且客户端获取的设备id值和服务器上的deviceid值不同,则需要弹出对话框(这个是换设备的情况)

        //如果已经设置过别名(存储过了设备id值)了,但是当前的别名(设备id值)和服务器上的不一致,则需要重新设置别名(存储设备id值)(这个是其他设备上登录的情况)
    }
}

三、发送消息

参考官网《发送消息

混淆配置

# add project specific proguard rules here.
# you can control the set of applied configuration files using the
# proguardfiles setting in build.gradle.
#
# for more details, see
#   http://developer.android.com/guide/developing/tools/proguard.html

# if your project uses webview with js, uncomment the following
# and specify the fully qualified class name to the javascript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
#   public *;
#}

# uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes sourcefile,linenumbertable

# if you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute sourcefile
#=====================华为推送sdk=====================
#注意:不要混淆hms sdk自带的资源文件。部分应用和游戏会混淆工程中的所有资源文件,请注意不要混淆hms sdk的相关资源文件。
-ignorewarning
-keepattributes *annotation*
-keepattributes exceptions
-keepattributes innerclasses
-keepattributes signature
-keepattributes sourcefile,linenumbertable
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}

-keep class com.huawei.android.hms.agent.**{*;}
-keep class com.huawei.gamebox.plugin.gameservice.**{*;}

参考资料

android集成华为推送踩坑问题总结

android集成华为推送实践

集成华为推送,华为手机app在活动点开推送重启app并且未进入到推送落地页

android集成华为推送的问题总结

项目demo下载地址

链接:https://pan.baidu.com/s/13fw_2o4fgzdv9q5-s-mxiw 提取码:qhk4 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网