极光推送使用流程:
1.去极光推送开发者服务网站注册账号
https://www.jiguang.cn/accounts/register/form
2.注册完毕,登陆后创建应用
3.创建完毕获取应用信息
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
添加权限
<!-- Required -->
<permission
android:name="com.example.lucian.jpushdemo.permission.JPUSH_MESSAGE"
android:protectionLevel="signature" />
<!-- Required 一些系统要求的权限,如访问网络等-->
<uses-permission android:name="com.example.lucian.jpushdemo.permission.JPUSH_MESSAGE" />
<uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
在Application中添加广播接收器
<!-- User defined. For test only 用户自定义的广播接收器-->
<receiver
android:name="com.example.lucian.jpushdemo.MyReceiver"
android:exported="false"
android:enabled="true">
<intent-filter>
<action android:name="cn.jpush.android.intent.REGISTRATION" /> <!--Required 用户注册SDK的intent-->
<action android:name="cn.jpush.android.intent.MESSAGE_RECEIVED" /> <!--Required 用户接收SDK消息的intent-->
<action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED" /> <!--Required 用户接收SDK通知栏信息的intent-->
<action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" /> <!--Required 用户打开自定义通知栏的intent-->
<action android:name="cn.jpush.android.intent.CONNECTION" /><!-- 接收网络变化 连接/断开 since 1.6.3 -->
<category android:name="com.example.lucian.jpushdemo" />
</intent-filter>
</receiver>
7.创建信息接收器MyReceiver,该信息接收器为Manifiest中注册定义的MyReceiver
package com.example.lucian.jpushdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
import cn.jpush.android.api.JPushInterface;
/**
* 自定义接收器
*
* 如果不定义这个 Receiver,则:
* 1) 默认用户会打开主界面
* 2) 接收不到自定义消息
*/
public class MyReceiver extends BroadcastReceiver {
private static final String TAG = "JPush";
@Override
public void onReceive(Context context, Intent intent) {
try {
Bundle bundle = intent.getExtras();
Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
String regId = 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] 接收到推送下来的通知");
int notifactionId = 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())) {
boolean connected = 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 (Exception e){
}
}
// 打印所有的 intent extra 数据
private static String printBundle(Bundle bundle) {
StringBuilder sb = new StringBuilder();
for (String key : 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 {
JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
Iterator<String> it = json.keys();
while (it.hasNext()) {
String myKey = it.next().toString();
sb.append("\nkey:" + key + ", value: [" +
myKey + " - " +json.optString(myKey) + "]");
}
} catch (JSONException e) {
Log.e(TAG, "Get message extra JSON error!");
}
} else {
sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
}
}
return sb.toString();
}
//send msg to MainActivity
private void processCustomMessage(Context context, Bundle bundle) {
if (JPushActivity.isForeground) {
String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
Intent msgIntent = new Intent(JPushActivity.MESSAGE_RECEIVED_ACTION);
msgIntent.putExtra(JPushActivity.KEY_MESSAGE, message);
if (!extras.isEmpty()) {
try {
JSONObject extraJson = new JSONObject(extras);
if (extraJson.length() > 0) {
msgIntent.putExtra(JPushActivity.KEY_EXTRAS, extras);
}
} catch (JSONException e) {
}
}
LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
}
}
//send msg to MainActivity
private void processNotification(Context context, Bundle bundle) {
if (JPushActivity.isForeground) {
String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
String notification = bundle.getString(JPushInterface.EXTRA_ALERT);
Intent msgIntent = new Intent(JPushActivity.MESSAGE_RECEIVED_ACTION);
msgIntent.putExtra(JPushActivity.KEY_MESSAGE, notification);
if (!extras.isEmpty()) {
try {
JSONObject extraJson = new JSONObject(extras);
if (extraJson.length() > 0) {
msgIntent.putExtra(JPushActivity.KEY_EXTRAS, extras);
}
} catch (JSONException e) {
}
}
LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
}
}
private void processNotificationTitle(Context context, Bundle bundle) {
if (JPushActivity.isForeground) {
//进入下一个Activity前的处理
Intent i = new Intent(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
package com.example.lucian.jpushdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
/**
* Created by qulus on 2017/6/29 0029.
*/
public class JPushActivity {
private static final String TAG = "JPushActivity" ;
private static Context mContext ;
public static boolean isForeground = true;//接收到信息是否传递给Activity
private String receiveResult ;
public JPushActivity() {}
public JPushActivity(Context context) {
this.mContext = context ;
}
private MessageReceiver mMessageReceiver;
public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
public static final String KEY_TITLE = "title";
public static final String KEY_MESSAGE = "message";
public static final String KEY_EXTRAS = "extras";
/**
*注册信息接收
*/
public void registerMessageReceiver() {
mMessageReceiver = new MessageReceiver() ;
IntentFilter filter = new IntentFilter() ;
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(MESSAGE_RECEIVED_ACTION);
LocalBroadcastManager.getInstance(mContext).registerReceiver(mMessageReceiver,filter);
}
/**
*设置接收到信息是否向下传递给Activity
*/
public void setIsForeground(boolean isForeground) {
this.isForeground = isForeground ;
}
/**
*停止Push信息
*/
public void stopPush() {
JPushInterface.stopPush(mContext);
}
/**
*重启Push
*/
public void resumePush() {
JPushInterface.resumePush(mContext);
}
/**
*初始化推送服务,不初始化,无法接收到信息
*/
public void initJPush() {
JPushInterface.setDebugMode(true);
JPushInterface.init(mContext);
}
/**
*取消注册接收服务
*/
public void unregisterReceiver() {
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mMessageReceiver);
}
/**
*信息接收器,接收到信息后的处理
*/
public class MessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
String message = intent.getStringExtra(KEY_MESSAGE) ;
String extras = intent.getStringExtra(KEY_EXTRAS) ;
StringBuilder showMsg = new StringBuilder() ;
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() ;
}
}
}
/**
*获取接收到的信息
*/
public String getReceiveResult() {
return receiveResult ;
}
/**
*为设备设置标签
*/
public static void setTag(String tag) {
// 检查 tag 的有效性
if (TextUtils.isEmpty(tag)) {
return;
}
// ","隔开的多个 转换成 Set
String[] sArray = tag.split(",");
Set<String> tagSet = new LinkedHashSet<String>();
for (String sTagItme : 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 void setAlias(String alias) {
// 检查 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 boolean isValidTagAndAlias(String s) {
Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_!@#$&*+=.|]+$");
Matcher m = p.matcher(s);
return m.matches();
}
private static final int MSG_SET_ALIAS = 1001;
private static final int MSG_SET_TAGS = 1002;
private final static Handler mHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_SET_ALIAS:
Log.d(TAG, "Set alias in handler.");
JPushInterface.setAliasAndTags(mContext, (String) msg.obj, null, mAliasCallback);
break;
case MSG_SET_TAGS:
Log.d(TAG, "Set tags in handler.");
JPushInterface.setAliasAndTags(mContext, null, (Set<String>) msg.obj, mTagsCallback);
break;
default:
Log.i(TAG, "Unhandled msg - " + msg.what);
}
}
};
/**
*设置别名的回调函数
*/
private final static TagAliasCallback mAliasCallback = new TagAliasCallback() {
@Override
public void gotResult(int code, String alias, Set<String> tags) {
String LogUtilss;
switch (code) {
case 0:
LogUtilss = "Set tag and alias success";
Log.i(TAG, LogUtilss);
break;
case 6002:
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 static TagAliasCallback mTagsCallback = new TagAliasCallback() {
@Override
public void gotResult(int code, String alias, Set<String> tags) {
String LogUtilss;
switch (code) {
case 0:
LogUtilss = "Set tag and alias success";
Log.i(TAG, LogUtilss);
break;
case 6002:
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 boolean isConnected(Context context) {
ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = conn.getActiveNetworkInfo();
return (info != null && info.isConnected());
}
}
9.在需要的地方初始化JPush和注册信息接收器
package com.example.lucian.jpushdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private JPushActivity mJPush ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mJPush = new JPushActivity(this) ;
mJPush.initJPush();//初始化极光推送
mJPush.registerMessageReceiver();//注册信息接收器
mJPush.setTag("admin1,admin2");//为设备设置标签
mJPush.setAlias("automic");//为设备设置别名
}
}
10.通过极光推送开发者服务平台测试,是否能接收到信息,可根据设置的标签,别名,等形式发送,可发送通知和自定义消息
11.推送历史: