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閱讀 228,333評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,491評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,263評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,946評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,708評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,186評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,255評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,409評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,939評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,774評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,976評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,518評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,209評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,641評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,872評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,650評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,958評論 2 373

推薦閱讀更多精彩內容