美文网首页Android
Android开发中从账号注册到最终推送一步一步实现极光推送

Android开发中从账号注册到最终推送一步一步实现极光推送

作者: Lucian_qls | 来源:发表于2017-06-29 17:41 被阅读1651次

    极光推送使用流程:

    1.去极光推送开发者服务网站注册账号

    https://www.jiguang.cn/accounts/register/form

    2.注册完毕,登陆后创建应用

    创建完毕获取应用信息

    4.创建工程,本次创建以Android Studio为例子

    应用名称为极光开发者平台的应用名称

    5.创建完毕生成的空的工程,集成极光SDK,本例运用自动集成

    1.jcenter自动集成步骤:

    使用jcenter自动集成的开发者,不需要在项目中添加jar和so,jcenter会自动完成依赖;

    在AndroidManifest.xml中不需要添加任何JPush SDK相关的配置,jcenter会自动导入。

    1.确认android studio的Project根目录的主gradle中配置了jcenter支持。(新建Preject默认配置支持)

    buildscript{

    repositories{

    jcenter()

    }

    dependencies{

    classpath'com.android.tools.build:gradle:2.2.2'

    // NOTE: Do not place your application dependencies here; they belong

    // in the individual module build.gradle files

    }

    }

    allprojects{

    repositories{

    jcenter()

    }

    }

    Module build.gradle配置:

    AndroidManifest替换变量,在defaultConfig中添加

    ndk{

    //选择要添加的对应cpu类型的.so库

    abiFilters'armeabi','armeabi-v7a','armeabi-v8a'

    //'x86', 'x86_64', 'mips', 'mips64'

    }

    manifestPlaceholders= [

    JPUSH_PKGNAME:applicationId,

    JPUSH_APPKEY:'a4d4161ac7d2908449605577',//JPush上注册的包名对应的appkey(https://www.jiguang.cn/push)

    JPUSH_CHANNEL:'developer-default'//默认值

    ]

    添加依赖

    compile'cn.jiguang.sdk:jpush:3.0.5'//JPush版本

    compile'cn.jiguang.sdk:jcore:1.1.2'//JCore版本

    工程根目录文件gradle.properties中添加如下内容

    android.useDeprecatedNdk=true

    6.配置AndroidManifest.xml

    添加权限

    android:name="com.example.lucian.jpushdemo.permission.JPUSH_MESSAGE"

    android:protectionLevel="signature"/>

    在Application中添加广播接收器

    android:name="com.example.lucian.jpushdemo.MyReceiver"

    android:exported="false"

    android:enabled="true">

    7.创建信息接收器MyReceiver,该信息接收器为Manifiest中注册定义的MyReceiver

    packagecom.example.lucian.jpushdemo;

    importandroid.content.BroadcastReceiver;

    importandroid.content.Context;

    importandroid.content.Intent;

    importandroid.os.Bundle;

    importandroid.support.v4.content.LocalBroadcastManager;

    importandroid.text.TextUtils;

    importandroid.util.Log;

    importorg.json.JSONException;

    importorg.json.JSONObject;

    importjava.util.Iterator;

    importcn.jpush.android.api.JPushInterface;

    /**

    *自定义接收器

    *

    *如果不定义这个Receiver,则:

    * 1)默认用户会打开主界面

    * 2)接收不到自定义消息

    */

    public classMyReceiverextendsBroadcastReceiver{

    private static finalStringTAG="JPush";

    @Override

    public voidonReceive(Contextcontext,Intentintent){

    try{

    Bundlebundle = intent.getExtras();

    Log.d(TAG,"[MyReceiver] onReceive - "+ intent.getAction()+", extras: "+printBundle(bundle));

    if(JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())){

    StringregId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);

    Log.d(TAG,"[MyReceiver]接收Registration Id : "+ regId);

    //send the Registration Id to your server...

    }else if(JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())){

    Log.d(TAG,"[MyReceiver]接收到推送下来的自定义消息: "+ bundle.getString(JPushInterface.EXTRA_MESSAGE));

    processCustomMessage(context,bundle);

    }else if(JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())){

    Log.d(TAG,"[MyReceiver]接收到推送下来的通知");

    intnotifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);

    Log.d(TAG,"[MyReceiver]接收到推送下来的通知的ID: "+ notifactionId);

    processNotification(context,bundle);

    }else if(JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())){

    Log.d(TAG,"[MyReceiver]用户点击打开了通知");

    processNotificationTitle(context,bundle);

    }else if(JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())){

    Log.d(TAG,"[MyReceiver]用户收到到RICH PUSH CALLBACK: "+ bundle.getString(JPushInterface.EXTRA_EXTRA));

    //在这里根据JPushInterface.EXTRA_EXTRA的内容处理代码,比如打开新的Activity, 打开一个网页等..

    }else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())){

    booleanconnected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);

    Log.w(TAG,"[MyReceiver]"+ intent.getAction()+" connected state change to "+connected);

    }else{

    Log.d(TAG,"[MyReceiver] Unhandled intent - "+ intent.getAction());

    }

    }catch(Exceptione){

    }

    }

    //打印所有的intent extra数据

    private staticStringprintBundle(Bundlebundle){

    StringBuildersb =newStringBuilder();

    for(Stringkey : bundle.keySet()){

    if(key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)){

    sb.append("\nkey:"+ key +", value:"+ bundle.getInt(key));

    }else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){

    sb.append("\nkey:"+ key +", value:"+ bundle.getBoolean(key));

    }else if(key.equals(JPushInterface.EXTRA_EXTRA)){

    if(TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))){

    Log.i(TAG,"This message has no Extra data");

    continue;

    }

    try{

    JSONObjectjson =newJSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));

    Iterator it =  json.keys();

    while(it.hasNext()){

    StringmyKey = it.next().toString();

    sb.append("\nkey:"+ key +", value: ["+

    myKey +" - "+json.optString(myKey)+"]");

    }

    }catch(JSONExceptione){

    Log.e(TAG,"Get message extra JSON error!");

    }

    }else{

    sb.append("\nkey:"+ key +", value:"+ bundle.getString(key));

    }

    }

    returnsb.toString();

    }

    //send msg to MainActivity

    private voidprocessCustomMessage(Contextcontext,Bundlebundle){

    if(JPushActivity.isForeground){

    Stringmessage = bundle.getString(JPushInterface.EXTRA_MESSAGE);

    Stringextras = bundle.getString(JPushInterface.EXTRA_EXTRA);

    IntentmsgIntent =newIntent(JPushActivity.MESSAGE_RECEIVED_ACTION);

    msgIntent.putExtra(JPushActivity.KEY_MESSAGE,message);

    if(!extras.isEmpty()){

    try{

    JSONObjectextraJson =newJSONObject(extras);

    if(extraJson.length()>0){

    msgIntent.putExtra(JPushActivity.KEY_EXTRAS,extras);

    }

    }catch(JSONExceptione){

    }

    }

    LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);

    }

    }

    //send msg to MainActivity

    private voidprocessNotification(Contextcontext,Bundlebundle){

    if(JPushActivity.isForeground){

    Stringextras = bundle.getString(JPushInterface.EXTRA_EXTRA);

    Stringnotification = bundle.getString(JPushInterface.EXTRA_ALERT);

    IntentmsgIntent =newIntent(JPushActivity.MESSAGE_RECEIVED_ACTION);

    msgIntent.putExtra(JPushActivity.KEY_MESSAGE,notification);

    if(!extras.isEmpty()){

    try{

    JSONObjectextraJson =newJSONObject(extras);

    if(extraJson.length()>0){

    msgIntent.putExtra(JPushActivity.KEY_EXTRAS,extras);

    }

    }catch(JSONExceptione){

    }

    }

    LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);

    }

    }

    private voidprocessNotificationTitle(Contextcontext,Bundlebundle){

    if(JPushActivity.isForeground){

    //进入下一个Activity前的处理

    Intenti =newIntent(context,TestActivity.class);

    i.putExtras(bundle);

    //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);

    context.startActivity(i);

    //下一个Activity的处理

    /*Intent intent = getIntent();

    if (null != intent) {

    Bundle bundle = getIntent().getExtras();

    String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);

    String content = bundle.getString(JPushInterface.EXTRA_ALERT);

    }*/

    }

    }

    }

    8.创建JPushActivity

    packagecom.example.lucian.jpushdemo;

    importandroid.content.BroadcastReceiver;

    importandroid.content.Context;

    importandroid.content.Intent;

    importandroid.content.IntentFilter;

    importandroid.net.ConnectivityManager;

    importandroid.net.NetworkInfo;

    importandroid.os.Handler;

    importandroid.support.v4.content.LocalBroadcastManager;

    importandroid.text.TextUtils;

    importandroid.util.Log;

    importandroid.widget.Toast;

    importjava.util.LinkedHashSet;

    importjava.util.Set;

    importjava.util.regex.Matcher;

    importjava.util.regex.Pattern;

    importcn.jpush.android.api.JPushInterface;

    importcn.jpush.android.api.TagAliasCallback;

    /**

    * Created by qulus on 2017/6/29 0029.

    */

    public classJPushActivity{

    private static finalStringTAG="JPushActivity";

    private staticContextmContext;

    public static booleanisForeground=true;//接收到信息是否传递给Activity

    privateStringreceiveResult;

    publicJPushActivity(){}

    publicJPushActivity(Contextcontext){

    this.mContext= context;

    }

    privateMessageReceivermMessageReceiver;

    public static finalStringMESSAGE_RECEIVED_ACTION="com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";

    public static finalStringKEY_TITLE="title";

    public static finalStringKEY_MESSAGE="message";

    public static finalStringKEY_EXTRAS="extras";

    /**

    *注册信息接收

    */

    public voidregisterMessageReceiver(){

    mMessageReceiver=newMessageReceiver();

    IntentFilterfilter =newIntentFilter();

    filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);

    filter.addAction(MESSAGE_RECEIVED_ACTION);

    LocalBroadcastManager.getInstance(mContext).registerReceiver(mMessageReceiver,filter);

    }

    /**

    *设置接收到信息是否向下传递给Activity

    */

    public voidsetIsForeground(booleanisForeground){

    this.isForeground= isForeground;

    }

    /**

    *停止Push信息

    */

    public voidstopPush(){

    JPushInterface.stopPush(mContext);

    }

    /**

    *重启Push

    */

    public voidresumePush(){

    JPushInterface.resumePush(mContext);

    }

    /**

    *初始化推送服务,不初始化,无法接收到信息

    */

    public voidinitJPush(){

    JPushInterface.setDebugMode(true);

    JPushInterface.init(mContext);

    }

    /**

    *取消注册接收服务

    */

    public voidunregisterReceiver(){

    LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mMessageReceiver);

    }

    /**

    *信息接收器,接收到信息后的处理

    */

    public classMessageReceiverextendsBroadcastReceiver{

    @Override

    public voidonReceive(Contextcontext,Intentintent){

    if(MESSAGE_RECEIVED_ACTION.equals(intent.getAction())){

    Stringmessage = intent.getStringExtra(KEY_MESSAGE);

    Stringextras = intent.getStringExtra(KEY_EXTRAS);

    StringBuildershowMsg =newStringBuilder();

    showMsg.append(KEY_MESSAGE+" : "+ message +"\n");

    if(!(null== extras)){

    showMsg.append(KEY_EXTRAS+" : "+ extras +"\n");

    }

    Toast.makeText(mContext,showMsg.toString(),Toast.LENGTH_SHORT).show();

    receiveResult= showMsg.toString();

    }

    }

    }

    /**

    *获取接收到的信息

    */

    publicStringgetReceiveResult(){

    returnreceiveResult;

    }

    /**

    *为设备设置标签

    */

    public  static voidsetTag(Stringtag){

    //检查tag的有效性

    if(TextUtils.isEmpty(tag)){

    return;

    }

    // ","隔开的多个 转换成Set

    String[] sArray = tag.split(",");

    Set tagSet =newLinkedHashSet();

    for(StringsTagItme : sArray){

    if(!isValidTagAndAlias(sTagItme)){

    Log.e(TAG,"error_tag_gs_empty");

    return;

    }

    tagSet.add(sTagItme);

    }

    //调用JPush API设置Tag

    mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS,tagSet));

    }

    /**

    *为设备设置别名

    */

    public voidsetAlias(Stringalias){

    //检查alias的有效性

    if(TextUtils.isEmpty(alias)){

    return;

    }

    if(!isValidTagAndAlias(alias)){

    Log.e(TAG,"error_alias_empty");

    return;

    }

    //调用JPush API设置Alias

    mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS,alias));

    }

    //校验Tag Alias只能是数字,英文字母和中文

    public static booleanisValidTagAndAlias(Strings){

    Patternp =Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_!@#$&*+=.|]+$");

    Matcherm = p.matcher(s);

    returnm.matches();

    }

    private static final intMSG_SET_ALIAS=1001;

    private static final intMSG_SET_TAGS=1002;

    private final staticHandlermHandler=newHandler(){

    @Override

    public voidhandleMessage(android.os.Messagemsg){

    super.handleMessage(msg);

    switch(msg.what){

    caseMSG_SET_ALIAS:

    Log.d(TAG,"Set alias in handler.");

    JPushInterface.setAliasAndTags(mContext,(String)msg.obj, null,mAliasCallback);

    break;

    caseMSG_SET_TAGS:

    Log.d(TAG,"Set tags in handler.");

    JPushInterface.setAliasAndTags(mContext, null,(Set)msg.obj,mTagsCallback);

    break;

    default:

    Log.i(TAG,"Unhandled msg - "+ msg.what);

    }

    }

    };

    /**

    *设置别名的回调函数

    */

    private final staticTagAliasCallbackmAliasCallback=newTagAliasCallback(){

    @Override

    public voidgotResult(intcode,Stringalias,Set tags){

    StringLogUtilss;

    switch(code){

    case0:

    LogUtilss ="Set tag and alias success";

    Log.i(TAG,LogUtilss);

    break;

    case6002:

    LogUtilss ="Failed to set alias and tags due to timeout. Try again after 60s.";

    Log.i(TAG,LogUtilss);

    if(isConnected(mContext)){

    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS,alias),1000*60);

    }else{

    Log.i(TAG,"No network");

    }

    break;

    default:

    LogUtilss ="Failed with errorCode = "+ code;

    Log.e(TAG,LogUtilss);

    }

    }

    };

    /**

    *设置标签回调函数

    */

    private final staticTagAliasCallbackmTagsCallback=newTagAliasCallback(){

    @Override

    public voidgotResult(intcode,Stringalias,Set tags){

    StringLogUtilss;

    switch(code){

    case0:

    LogUtilss ="Set tag and alias success";

    Log.i(TAG,LogUtilss);

    break;

    case6002:

    LogUtilss ="Failed to set alias and tags due to timeout. Try again after 60s.";

    Log.i(TAG,LogUtilss);

    if(isConnected(mContext)){

    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS,tags),1000*60);

    }else{

    Log.i(TAG,"No network");

    }

    break;

    default:

    LogUtilss ="Failed with errorCode = "+ code;

    Log.e(TAG,LogUtilss);

    }

    }

    };

    /**

    *检测设备是否联网

    */

    public static booleanisConnected(Contextcontext){

    ConnectivityManagerconn =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfoinfo = conn.getActiveNetworkInfo();

    return(info !=null&& info.isConnected());

    }

    }

    9.在需要的地方初始化JPush和注册信息接收器

    packagecom.example.lucian.jpushdemo;

    importandroid.support.v7.app.AppCompatActivity;

    importandroid.os.Bundle;

    public classMainActivityextendsAppCompatActivity{

    privateJPushActivitymJPush;

    @Override

    protected voidonCreate(BundlesavedInstanceState){

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    mJPush=newJPushActivity(this);

    mJPush.initJPush();//初始化极光推送

    mJPush.registerMessageReceiver();//注册信息接收器

    mJPush.setTag("admin1,admin2");//为设备设置标签

    mJPush.setAlias("automic");//为设备设置别名

    }

    }

    10.通过极光推送开发者服务平台测试,是否能接收到信息,可根据设置的标签,别名,等形式发送,可发送通知和自定义消息

    11.推送历史:

    相关文章

      网友评论

      • 隐倾城:你把官网的抄一遍过来有意思么..
      • 青年_8335:哥们我一步一步的去继承 为什么不行啊 我很愚昧

      本文标题:Android开发中从账号注册到最终推送一步一步实现极光推送

      本文链接:https://www.haomeiwen.com/subject/ftcvcxtx.html