極光推送使用流程:
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.推送歷史: