
Android开发中,极光推送,从账号注册到推送,一步一步实现过程
极光推送使用流程:
1.去极光推送开发者服务网站注册账号
2.注册完毕,登陆后创建应用
- 创建完毕获取应用信息
4.创建工程,本次创建以Android Studio为例子
应用名称为极光开发者平台的应用名称
5.创建完毕生成的空的工程,集成极光SDK,本例运用自动集成
1.jcenter自动集成步骤:
使用jcenter自动集成的开发者,不需要在项目中添加jar和so,jcenter会自动完成依赖;
在l中不需要添加任何JPush SDK相关的配置,jcenter会自动导入。
1.确认android studio的Project根目录的主gradle中配置了jcenter支持。(新建Preject默认配置支持)
buildscript {
repositories {
jcenter ()
}
dependencies {
classpath 'ls.build:gradle:2.2.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module adle files
}
}
allprojects {
repositories {
jcenter ()
}
}
adle配置:
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()
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.配置l
添加权限
<!-- Required -->
<permission
android :name= ample.lucian.jpushdemo.permission.JPUSH_MESSAGE"
android :protectionLevel= "signature" />
<!-- Required 一些系统要求的权限,如访问网络等 -->
<uses-permission android :name= ample.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= ample.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= ample.lucian.jpushdemo" />
</intent-filter>
</receiver>
7.创建信息接收器MyReceiver,该信息接收器为Manifiest中注册定义的MyReceiver
package ample.lucian.jpushdemo ;
import t.BroadcastReceiver ;
import t.Context ;
import t.Intent ;
import android.os.Bundle ;
import android.t.LocalBroadcastManager ;
import 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 = Extras () ;
Log. d (
TAG , "[MyReceiver] onReceive - " + Action () + ", extras: " + printBundle (bundle )) ;
if ( JPushInterface.
ACTION_REGISTRATION_ID.equals (Action ())) {
String regId = String ( JPushInterface.
EXTRA_REGISTRATION_ID ) ;
Log. d (
TAG , "[MyReceiver] 接收 Registration Id : " + regId ) ;
//send the Registration Id to your
} else if ( JPushInterface.
ACTION_MESSAGE_RECEIVED.equals (Action ())) {
Log. d (
TAG , "[MyReceiver] 接收到推送下来的自定义消息 : " + String ( JPushInterface.
EXTRA_MESSAGE )) ;
processCustomMessage (context , bundle ) ;
} else if ( JPushInterface.
ACTION_NOTIFICATION_RECEIVED.equals (Action ())) {
Log. d (
TAG , "[MyReceiver] 接收到推送下来的通知 " ) ;
int notifactionId = Int ( JPushInterface.
EXTRA_NOTIFICATION_ID ) ;
Log. d (
TAG , "[MyReceiver] 接收到推送下来的通知的 ID: " + notifactionId ) ;
processNotification (context , bundle ) ;
} else if ( JPushInterface.
ACTION_NOTIFICATION_OPENED.equals (Action ())) {
Log. d (
TAG , "[MyReceiver] 用户点击打开了通知 " ) ;
processNotificationTitle (context , bundle ) ;
} else if ( JPushInterface.
ACTION_RICHPUSH_CALLBACK.equals (Action ())) {
Log. d (
TAG , "[MyReceiver] 用户收到到 RICH PUSH CALLBACK: " + String ( JPushInterface.
EXTRA_EXTRA )) ;
// 在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码,比如打开新的 Activity , 打开一个网页等 ..
} else if ( JPushInterface.
ACTION_CONNECTION_CHANGE.equals (Action ())) {
boolean connected = BooleanExtra ( JPushInterface.
EXTRA_CONNECTION_CHANGE , false ) ;
Log. w (
TAG , "[MyReceiver]" + Action () + " connected state change to "+connected ) ;
} else {
Log. d (
TAG , "[MyReceiver] Unhandled intent - " + Action ()) ;
}
} 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 ( " n key:" + key + ", value:" + Int (key )) ;
} else if (key.equals ( JPushInterface.
EXTRA_CONNECTION_CHANGE )) {
sb.append ( " n key:" + key + ", value:" + Boolean (key )) ;
} else if (key.equals ( JPushInterface.
EXTRA_EXTRA )) {
if ( TextUtils. isEmpty (String ( JPushInterface.
EXTRA_EXTRA ))) {
Log. i (
TAG , "This message has no Extra data" ) ;
continue;
}
try {
JSONObject json = new JSONObject (String ( JPushInterface.
EXTRA_EXTRA )) ;
Iterator< String> it = json.keys () ;
while (it.hasNext ()) {
String myKey = it.next ().toString () ;
sb.append ( " n key:" + key + ", value: [" +
myKey + " - " +json.optString (myKey ) + "]" ) ;
}
} catch ( JSONException e ) {
Log. e (
TAG , "Get message extra JSON error!" ) ;
}
} else {
sb.append ( " n key:" + key + ", value:" + String (key )) ;
}
}
return sb.toString () ;
}
//send msg to MainActivity
private void processCustomMessage ( Context context , Bundle bundle ) {
if ( JPushActivity.
isForeground ) {
String message = String ( JPushInterface.
EXTRA_MESSAGE ) ;
String extras = String ( 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 = String ( JPushInterface.
EXTRA_EXTRA ) ;
String notification = String ( 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 = String(JPushInterface.EXTRA_NOTIFICATION_TITLE);
String content = String(JPushInterface.EXTRA_ALERT);
}*/
}
}
}
8.创建JPushActivity
package ample.lucian.jpushdemo ;
import t.BroadcastReceiver ;
import t.Context ;
import t.Intent ;
import t.IntentFilter ;
import android.ConnectivityManager ;
import android.NetworkInfo ;
import android.os.Handler ;
import android.t.LocalBroadcastManager ;
import TextUtils ;
import android.util.Log ;
import android.widget.Toast ;
import java.util.LinkedHashSet ;
import java.util.Set ;
import Matcher ;
import 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 = ample.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 (Action ())) {
String message = StringExtra (
KEY_MESSAGE ) ;
String extras = StringExtra (
KEY_EXTRAS ) ;
StringBuilder showMsg = new StringBuilder () ;
showMsg.append (
KEY_MESSAGE + " : " + message + " n " ) ;
if (! ( null == extras )) {
showMsg.append (
KEY_EXTRAS + " : " + extras + " n " ) ;
}
Toast. makeText (
mContext ,String () , Toast.
LENGTH_SHORT ).show () ;
receiveResult = String () ;
}
}
}
/**
* 获取接收到的信息
*/
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 - u9FA5 0-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 ) SystemService ( Context.
CONNECTIVITY_SERVICE ) ;
NetworkInfo info = ActiveNetworkInfo () ;
return (info != null && info.isConnected ()) ;
}
}
9.在需要的地方初始化JPush和注册信息接收器
package ample.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 ) {
Create (savedInstanceState ) ;
setContentView ( R.layout.
activity_main ) ;
mJPush = new JPushActivity ( this ) ;
mJPush.initJPush () ; // 初始化极光推送
isterMessageReceiver () ; // 注册信息接收器
mJPush. setTag ( "admin1,admin2" ) ; // 为设备设置标签
mJPush. setAlias ( "automic" ) ; // 为设备设置别名
}
}
10.通过极光推送开发者服务平台测试,是否能接收到信息,可根据设置的标签,别名,等形式发送,可发送通知和自定义消息
11.推送历史: