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

极光推送使用流程:

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.推送历史:


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容