極光推送使用流程:
1.去極光推送開發(fā)者服務(wù)網(wǎng)站注冊(cè)賬號(hào)
https://www.jiguang.cn/accounts/register/form
2.注冊(cè)完畢,登陸后創(chuàng)建應(yīng)用
創(chuàng)建完畢獲取應(yīng)用信息
4.創(chuàng)建工程,本次創(chuàng)建以Android Studio為例子
應(yīng)用名稱為極光開發(fā)者平臺(tái)的應(yīng)用名稱
5.創(chuàng)建完畢生成的空的工程,集成極光SDK,本例運(yùn)用自動(dòng)集成
1.jcenter自動(dòng)集成步驟:
使用jcenter自動(dòng)集成的開發(fā)者,不需要在項(xiàng)目中添加jar和so,jcenter會(huì)自動(dòng)完成依賴;
在AndroidManifest.xml中不需要添加任何JPush SDK相關(guān)的配置,jcenter會(huì)自動(dòng)導(dǎo)入。
1.確認(rèn)android studio的Project根目錄的主gradle中配置了jcenter支持。(新建Preject默認(rèn)配置支持)
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{
//選擇要添加的對(duì)應(yīng)cpu類型的.so庫
abiFilters'armeabi','armeabi-v7a','armeabi-v8a'
//'x86',?'x86_64',?'mips',?'mips64'
}
manifestPlaceholders=?[
JPUSH_PKGNAME:applicationId,
JPUSH_APPKEY:'a4d4161ac7d2908449605577',//JPush上注冊(cè)的包名對(duì)應(yīng)的appkey(https://www.jiguang.cn/push)
JPUSH_CHANNEL:'developer-default'//默認(rèn)值
]
添加依賴
compile'cn.jiguang.sdk:jpush:3.0.5'//JPush版本
compile'cn.jiguang.sdk:jcore:1.1.2'//JCore版本
工程根目錄文件gradle.properties中添加如下內(nèi)容
android.useDeprecatedNdk=true
6.配置AndroidManifest.xml
添加權(quán)限
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.創(chuàng)建信息接收器MyReceiver,該信息接收器為Manifiest中注冊(cè)定義的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;
/**
*自定義接收器
*
*如果不定義這個(gè)Receiver,則:
*?1)默認(rèn)用戶會(huì)打開主界面
*?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]用戶點(diǎn)擊打開了通知");
processNotificationTitle(context,bundle);
}else?if(JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())){
Log.d(TAG,"[MyReceiver]用戶收到到RICH?PUSH?CALLBACK:?"+?bundle.getString(JPushInterface.EXTRA_EXTRA));
//在這里根據(jù)JPushInterface.EXTRA_EXTRA的內(nèi)容處理代碼,比如打開新的Activity,?打開一個(gè)網(wǎng)頁等..
}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數(shù)據(jù)
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){
//進(jìn)入下一個(gè)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);
//下一個(gè)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.創(chuàng)建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";
/**
*注冊(cè)信息接收
*/
public?voidregisterMessageReceiver(){
mMessageReceiver=newMessageReceiver();
IntentFilterfilter?=newIntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(MESSAGE_RECEIVED_ACTION);
LocalBroadcastManager.getInstance(mContext).registerReceiver(mMessageReceiver,filter);
}
/**
*設(shè)置接收到信息是否向下傳遞給Activity
*/
public?voidsetIsForeground(booleanisForeground){
this.isForeground=?isForeground;
}
/**
*停止Push信息
*/
public?voidstopPush(){
JPushInterface.stopPush(mContext);
}
/**
*重啟Push
*/
public?voidresumePush(){
JPushInterface.resumePush(mContext);
}
/**
*初始化推送服務(wù),不初始化,無法接收到信息
*/
public?voidinitJPush(){
JPushInterface.setDebugMode(true);
JPushInterface.init(mContext);
}
/**
*取消注冊(cè)接收服務(wù)
*/
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;
}
/**
*為設(shè)備設(shè)置標(biāo)簽
*/
public? static?voidsetTag(Stringtag){
//檢查tag的有效性
if(TextUtils.isEmpty(tag)){
return;
}
//?","隔開的多個(gè)?轉(zhuǎn)換成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);
}
//調(diào)用JPush?API設(shè)置Tag
mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS,tagSet));
}
/**
*為設(shè)備設(shè)置別名
*/
public?voidsetAlias(Stringalias){
//檢查alias的有效性
if(TextUtils.isEmpty(alias)){
return;
}
if(!isValidTagAndAlias(alias)){
Log.e(TAG,"error_alias_empty");
return;
}
//調(diào)用JPush?API設(shè)置Alias
mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS,alias));
}
//校驗(yàn)Tag?Alias只能是數(shù)字,英文字母和中文
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);
}
}
};
/**
*設(shè)置別名的回調(diào)函數(shù)
*/
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);
}
}
};
/**
*設(shè)置標(biāo)簽回調(diào)函數(shù)
*/
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);
}
}
};
/**
*檢測(cè)設(shè)備是否聯(lián)網(wǎng)
*/
public?static?booleanisConnected(Contextcontext){
ConnectivityManagerconn?=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfoinfo?=?conn.getActiveNetworkInfo();
return(info?!=null&&?info.isConnected());
}
}
9.在需要的地方初始化JPush和注冊(cè)信息接收器
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();//注冊(cè)信息接收器
mJPush.setTag("admin1,admin2");//為設(shè)備設(shè)置標(biāo)簽
mJPush.setAlias("automic");//為設(shè)備設(shè)置別名
}
}
10.通過極光推送開發(fā)者服務(wù)平臺(tái)測(cè)試,是否能接收到信息,可根據(jù)設(shè)置的標(biāo)簽,別名,等形式發(fā)送,可發(fā)送通知和自定義消息
11.推送歷史: