集成極光推送
使用jcenter 自動集成步驟
說明 : 使用 jcenter 自動集成,不需要在項目中添加 jar 和 so,jcenter 會自動完成依賴;在 AndroidManifest.xml 中不需要添加任何 JPush SDK 相關(guān)的配置,jcenter 會自動導(dǎo)入。
- 確認(rèn) android studio 的 Project 根目錄的主 gradle 中配置了 jcenter 支持。(新建 project 默認(rèn)配置就支持)
buildscript {
repositories {
jcenter()
}
......
}
allprojets {
repositories {
jcenter()
}
}
- 在 module 的 gradle 中添加依賴和 AndroidManifest 的替換變量。
android {
......
defaultConfig {
applicationId "com.xxx.xxx" //JPush 上注冊的包名.
......
ndk {
//選擇要添加的對應(yīng) cpu 類型的 .so 庫。
abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a'
// 還可以添加 'x86', 'x86_64', 'mips', 'mips64'
}
manifestPlaceholders = [
JPUSH_PKGNAME : applicationId,
JPUSH_APPKEY : "你的 Appkey ", //JPush 上注冊的包名對應(yīng)的 Appkey.
JPUSH_CHANNEL : "developer-default", //暫時填寫默認(rèn)值即可.
]
......
}
......
}
dependencies {
......
compile 'cn.jiguang.sdk:jpush:3.1.6' // 此處以JPush 3.1.6 版本為例。
compile 'cn.jiguang.sdk:jcore:1.2.5' // 此處以JCore 1.2.5 版本為例。
......
}
我的Demo中的build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.maigu.yang.jiguangdemo"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
manifestPlaceholders = [
JPUSH_PKGNAME: applicationId,
JPUSH_APPKEY : "979910224deebd360a0c497b", //JPush上注冊的包名對應(yīng)的appkey.
JPUSH_CHANNEL: "developer-default", //暫時填寫默認(rèn)值即可.
]
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'cn.jiguang.sdk:jpush:3.1.1'
implementation 'cn.jiguang.sdk:jcore:1.1.9'
}
配置 AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.maigu.yang.jiguangdemo">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<!-- Required -->
<permission
android:name="com.maigu.yang.jiguangdemo.permission.JPUSH_MESSAGE"
android:protectionLevel="signature" />
<!-- Required -->
<uses-permission android:name="com.maigu.yang.jiguangdemo.permission.JPUSH_MESSAGE" />
<uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!-- Optional. Required for location feature -->
<!-- 用于開啟 debug 版本的應(yīng)用在6.0 系統(tǒng)上 層疊窗口權(quán)限 -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<!-- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!-- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> -->
<!-- <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> -->
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_TASKS" />
<application
android:name=".App"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- jpush sdk begin -->
<!-- Required SDK 核心功能 -->
<!-- 可配置android:process參數(shù)將PushService放在其他進程中 -->
<service
android:name="cn.jpush.android.service.PushService"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="cn.jpush.android.intent.REGISTER" />
<action android:name="cn.jpush.android.intent.REPORT" />
<action android:name="cn.jpush.android.intent.PushService" />
<action android:name="cn.jpush.android.intent.PUSH_TIME" />
</intent-filter>
</service>
<!-- since 3.0.9 Required SDK 核心功能 -->
<!-- <provider -->
<!-- android:authorities="com.maigu.yang.jiguangdemo.DataProvider" -->
<!-- android:name="cn.jpush.android.service.DataProvider" -->
<!-- android:exported="true" -->
<!-- /> -->
<!-- since 1.8.0 option 可選項。用于同一設(shè)備中不同應(yīng)用的JPush服務(wù)相互拉起的功能。 -->
<!-- 若不啟用該功能可刪除該組件,將不拉起其他應(yīng)用也不能被其他應(yīng)用拉起 -->
<service
android:name="cn.jpush.android.service.DaemonService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="cn.jpush.android.intent.DaemonService" />
<category android:name="com.maigu.yang.jiguangdemo" />
</intent-filter>
</service>
<!-- Required SDK核心功能 -->
<receiver
android:name="cn.jpush.android.service.PushReceiver"
android:enabled="true">
<intent-filter android:priority="1000">
<action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED_PROXY" />
<category android:name="com.maigu.yang.jiguangdemo" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
<!-- Optional -->
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
<!-- Required SDK核心功能 -->
<activity
android:name="cn.jpush.android.ui.PushActivity"
android:configChanges="orientation|keyboardHidden"
android:exported="false"
android:theme="@android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="cn.jpush.android.ui.PushActivity" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="com.maigu.yang.jiguangdemo" />
</intent-filter>
</activity>
<!-- SDK核心功能 -->
<activity
android:name="cn.jpush.android.ui.PopWinActivity"
android:configChanges="orientation|keyboardHidden"
android:exported="false"
android:theme="@style/MyDialogStyle">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<category android:name="com.maigu.yang.jiguangdemo" />
</intent-filter>
</activity>
<!-- Required SDK核心功能 -->
<service
android:name="cn.jpush.android.service.DownloadService"
android:enabled="true"
android:exported="false" />
<!-- Required SDK核心功能 -->
<receiver android:name="cn.jpush.android.service.AlarmReceiver" />
<!-- Required since 3.0.7 -->
<!-- 新的tag/alias接口結(jié)果返回需要開發(fā)者配置一個自定的廣播 -->
<!-- 該廣播需要繼承JPush提供的JPushMessageReceiver類, 并如下新增一個 Intent-Filter -->
<!-- <receiver -->
<!-- android:name=".jpush.MyReceiver" -->
<!-- android:enabled="true" > -->
<!-- <intent-filter> -->
<!-- <action android:name="cn.jpush.android.intent.RECEIVE_MESSAGE" /> -->
<!-- <category android:name="com.maigu.yang.jiguangdemo" /> -->
<!-- </intent-filter> -->
<!-- </receiver> -->
<!-- <!– User defined. 用戶自定義的廣播接收器–> -->
<receiver
android:name=".MyReceiver"
android:enabled="true">
<intent-filter>
<!-- Required 用戶注冊SDK的intent -->
<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 用戶打開自定義通知欄的intent -->
<action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" />
<!-- 接收網(wǎng)絡(luò)變化 連接/斷開 since 1.6.3 -->
<action android:name="cn.jpush.android.intent.CONNECTION" />
<category android:name="com.maigu.yang.jiguangdemo" />
</intent-filter>
</receiver>
<!-- Required. For publish channel feature -->
<!-- JPUSH_CHANNEL 是為了方便開發(fā)者統(tǒng)計APK分發(fā)渠道。 -->
<!-- 例如: -->
<!-- 發(fā)到 Google Play 的APK可以設(shè)置為 google-play; -->
<!-- 發(fā)到其他市場的 APK 可以設(shè)置為 xxx-market。 -->
<meta-data
android:name="JPUSH_CHANNEL"
android:value="developer-default" />
<!-- Required. AppKey copied from Portal -->
<meta-data
android:name="JPUSH_APPKEY"
android:value="979910224deebd360a0c497b" />
<!-- jpush sdk end -->
</application>
</manifest>
小帖士
如果使用 android studio,可在 AndroidManifest 中引用 applicationId 的值,在 build.gradle 配置中 defaultConfig 節(jié)點下配置,如:
defaultConfig {
applicationId "cn.jpush.example" // <--您應(yīng)用的包名
……
}
在 AndroidManifest 中使用 ${applicationId} 引用 gradle 中定義的包名
在極光推送哪里創(chuàng)建賬戶,創(chuàng)建應(yīng)用,如下圖:

AndroidManifest 中使用到到AppKey就是上圖所示的Appkey。
App.java文件
package com.maigu.yang.jiguangdemo;
import android.app.Application;
import android.app.Notification;
import android.content.Context;
import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
public class App extends Application {
public static Context applicationContext;
@Override
public void onCreate() {
super.onCreate();
applicationContext = getApplicationContext();
JPushInterface.init(this);
jpushSet();
}
/**
* 獲取全局上下文
*/
public static Context getContext() {
return applicationContext;
}
private void jpushSet() {
BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(this);
builder.statusBarDrawable = R.mipmap.shenqi;
builder.notificationDefaults = Notification.DEFAULT_SOUND
| Notification.DEFAULT_VIBRATE
| Notification.DEFAULT_LIGHTS; // 設(shè)置為鈴聲、震動、呼吸燈閃爍都要
JPushInterface.setPushNotificationBuilder(1, builder);
/**
* 設(shè)置通知欄樣式 - 定義通知欄Layout
*/
CustomPushNotificationBuilder builder1 =
new CustomPushNotificationBuilder(this, R.layout.customer_notitfication_layout,
R.id.icon, R.id.title, R.id.text);
builder1.layoutIconDrawable = R.mipmap.shenqi;
builder.developerArg0 = "developerArg2";
JPushInterface.setPushNotificationBuilder(2, builder1);
}
}
關(guān)于自定義通知欄樣式
JPush 通知推送到客戶端時,默認(rèn)使用手機的默認(rèn)設(shè)置來顯示通知欄,包括鈴聲、震動等效果。
如果開發(fā)者想要達(dá)到如下的效果,則需要使用“自定義通知欄樣式”功能:
通知欄樣式使用與默認(rèn)不一樣的設(shè)置,比如想要控制:
鈴聲、震動
顯示圖標(biāo)
替換默認(rèn)的通知欄樣式。
推送消息指定通知欄樣式編號
通知欄樣式在服務(wù)器端向下推送時,只體現(xiàn)為一個編號(數(shù)字)。
推送通知的樣式編號,應(yīng)該是在客戶端做了自定義通知欄樣式設(shè)置的。
如果通知上的樣式編號,在客戶端檢查不存在,則使用默認(rèn)的通知欄樣式。
不使用自定義通知欄樣式時,此編號默認(rèn)為 0。如需使用自定義的通知欄樣式,編號應(yīng)大于 0 小于 1000。先在客戶端調(diào) API 設(shè)置通知欄樣式,推送設(shè)置 Builder ID 值即可在收到消息時得到對應(yīng)的樣式效果。
調(diào) API 進行推送時,在 Notification - Android 屬性下設(shè)置 builder_id 值
在 Portal 上發(fā)送通知時,首先選擇推送平臺為 Android,然后展開“可選設(shè)置”,開發(fā)者可指定當(dāng)前要推送的通知的樣式編號。如下圖所示:

客戶端設(shè)置通知欄樣式
自定義的通知欄樣式,是在客戶端進行設(shè)置的。請參考 通知欄樣式定制 API 來看所支持的功能。
自定義通知欄樣式設(shè)計
有個 PushNotificationBuilder 概念,開發(fā)者使用 setPushNotificationBuilder 方法為某種類型的 PushNotificationBuilder 指定編號。
setPushNotificationBuilder 可以在 JPushInterface.init() 之后任何地方調(diào)用,可以是開發(fā)者應(yīng)用的邏輯來觸發(fā)調(diào)用,或者初始化時調(diào)用。
只需要設(shè)置一次,JPush SDK 會記住這個設(shè)置。在下次收到推送通知時,就根據(jù)通知里指定的編號來找到 PushNotificationBuilder 來展現(xiàn)、執(zhí)行。
API - setDefaultPushNotificationBuilder 設(shè)置默認(rèn)
此 API 改變默認(rèn)的編號為 0 的通知欄樣式。
API - setPushNotificationBuilder 指定編號
此 API 為開發(fā)者指定的編號,設(shè)置一個自定義的 PushNotificationBuilder(通知樣式構(gòu)建器)。
App.java文件中使用到到customer_notitfication_layout.xml文件,以及(通知)到小圖標(biāo)。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/shenqi" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:orientation="vertical">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#286CA6"
android:textSize="16sp" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#6FA45E"
android:textSize="14sp" />
</LinearLayout>
<DateTimeView
android:id="@+id/time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:maxLines="1"
android:textColor="#ff0000" />
</LinearLayout>
MyReceiver.java文件
package com.maigu.yang.jiguangdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
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;
/**
* 自定義的廣播接收器
*/
public class MyReceiver extends BroadcastReceiver {
private static final String TAG = "小白陽";
@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())) {
// send the Registration Id to your server...
String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
} 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())) {
String strTitle = bundle.getString(JPushInterface.EXTRA_ALERT);
String strContent = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
Log.d(TAG, "strTitle" + strTitle);
Log.d(TAG, "strContent" + strContent);
Log.d(TAG, "[MyReceiver] 接收到推送下來的通知");
int notificationId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
Log.d(TAG, "[MyReceiver] 接收到推送下來的通知的ID: " + notificationId);
} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
Log.d(TAG, "[MyReceiver] 用戶點擊打開了通知");
} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
// 在這里根據(jù) JPushInterface.EXTRA_EXTRA 的內(nèi)容處理代碼,比如打開新的Activity, 打開一個網(wǎng)頁等..
Log.d(TAG, "[MyReceiver] 用戶收到到RICH PUSH CALLBACK: " + bundle.getString
(JPushInterface.EXTRA_EXTRA));
} else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
Log.d(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
} else {
Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
}
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "拋出異常:" + e.getMessage());
}
}
// 打印所有的 intent extra 數(shù)據(jù)
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.e(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();
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 Activity
private void processCustomMessage(Context context, Bundle bundle) {
String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
Log.d(TAG, "收到了自定義消息--------->:message:" + message);
Log.d(TAG, "收到了自定義消息@@消息extra是extras:" + extras);
if (!TextUtils.isEmpty(extras)) {
try {
JSONObject extraJson = new JSONObject(extras);
if (extraJson.length() > 0) {
String type = "";
try {
JSONObject jsonObject = new JSONObject(extras);
type = jsonObject.getString("type");
Log.d(TAG, "type" + type);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "push json is fail");
}
}
}
}
SharedUtil.java工具類
package com.maigu.yang.jiguangdemo;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* 名稱:SharedUtil.java
* 描述:保存到 SharedPreferences 的數(shù)據(jù).
*/
public class SharedUtil {
private static final String SHARED_PATH = "app_sharedpreferences";
private static SharedPreferences sharedPreferences;
public static SharedPreferences getDefaultSharedPreferences(Context context) {
if (sharedPreferences == null) {
sharedPreferences = context.getSharedPreferences(SHARED_PATH, Context.MODE_PRIVATE);
}
return sharedPreferences;
}
public static void putInt(Context context, String key, int value) {
SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);
Editor edit = sharedPreferences.edit();
edit.putInt(key, value);
edit.apply();
}
public static int getInt(Context context, String key) {
SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);
return sharedPreferences.getInt(key, 0);
}
public static void putString(Context context, String key, String value) {
SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);
Editor edit = sharedPreferences.edit();
edit.putString(key, value);
edit.apply();
}
public static String getString(Context context, String key) {
SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);
return sharedPreferences.getString(key, "");
}
public static void putBoolean(Context context, String key, boolean value) {
SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);
Editor edit = sharedPreferences.edit();
edit.putBoolean(key, value);
edit.apply();
}
public static boolean getBoolean(Context context, String key, boolean defValue) {
SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);
return sharedPreferences.getBoolean(key, defValue);
}
public static void remove(Context context, String key) {
SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);
Editor edit = sharedPreferences.edit();
edit.remove(key);
edit.apply();
}
public static void clear(Context context) {
SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);
Editor edit = sharedPreferences.edit();
edit.clear();
edit.apply();
}
}
MainActivity.java文件
package com.maigu.yang.jiguangdemo;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.HashSet;
import java.util.Set;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
public class MainActivity extends AppCompatActivity {
private static final int MSG_SET_ALIAS = 1001;
private static final int MSG_SET_TAGS = 1002;
Set<String> tags = new HashSet<String>();
private static final String TAG = "小白陽";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedUtil.putInt(this, "userId", 1);
// if (!"success".equals(SharedUtil.getString(this, "alias"))) {
// // 調(diào)用 Handler 來異步設(shè)置別名,一般都是用userId來進行設(shè)置別名(唯一性)。
// mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS,
// SharedUtil.getInt(this, "userId") + ""));
// // 調(diào)用 Handler 來異步設(shè)置標(biāo)簽。
// tags.add("vip");
// mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, tags));
// }
// 調(diào)用 Handler 來異步設(shè)置別名,一般都是用userId來進行設(shè)置別名(唯一性)。
mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS,
SharedUtil.getInt(this, "userId") + ""));
// 調(diào)用 Handler 來異步設(shè)置標(biāo)簽。
tags.add("vip");
mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, tags));
if (JPushInterface.isPushStopped(App.getContext())) {
JPushInterface.resumePush(App.getContext());
}
}
@SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_SET_ALIAS:
// 調(diào)用 JPush 接口來設(shè)置別名。
JPushInterface.setAlias(getApplicationContext(),
(String) msg.obj,
mAliasCallback);
break;
case MSG_SET_TAGS:
// 調(diào)用 JPush 接口來設(shè)置標(biāo)簽。
JPushInterface.setTags(getApplicationContext(),
tags,
mAliasCallback);
break;
default:
break;
}
}
};
private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
@Override
public void gotResult(int code, String alias, Set<String> tags) {
switch (code) {
case 0:
Log.e(TAG, "TagAliasCallback success");
//"Set tag and alias success";
// 建議這里往 SharePreference 里寫一個成功設(shè)置的狀態(tài)。成功設(shè)置一次后,以后不必再次設(shè)置了。
SharedUtil.putString(MainActivity.this, "alias", "success");
break;
case 6002:
// 延遲 60 秒來調(diào)用 Handler 設(shè)置別名,標(biāo)簽
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
break;
default:
break;
}
}
};
}
使用別名
用于給某特定用戶推送消息。別名,可以近似地被認(rèn)為,是用戶帳號里的昵稱。
在代碼中表現(xiàn)為:
// 調(diào)用 JPush 接口來設(shè)置別名。
JPushInterface.setAlias(getApplicationContext(),
(String) msg.obj,
mAliasCallback);
使用標(biāo)簽
用于給某一群人推送消息。
標(biāo)簽類似于博客里為文章打上 tag ,即為某資源分類。
在代碼中表現(xiàn)為:
// 調(diào)用 JPush 接口來設(shè)置標(biāo)簽。
JPushInterface.setTags(getApplicationContext(),
tags,
mAliasCallback);
如果在MainActivity.java文件中一行代碼也不寫。使用剛創(chuàng)建好的MainActivity依舊可以收到通知,但是不能針對于特定人群,以及某個人進行通知推送。如果加上標(biāo)簽或者別名給通知的限制,就可以針對特定對象進行推送了呢。
Demo效果展示:
(一)廣播所有人


(二)推送對象——某一群人(標(biāo)簽)


(三)推送對象——某個人(別名)


嗯,大家還記得我們在App.java文件中自定義通知欄Layout嗎?
看看效果:



最后就是極光推送自定義消息環(huán)節(jié):
介紹
自定義消息
SDK 不會把自定義消息展示到通知欄。所以調(diào)試時,需要到日志里才可以看到服務(wù)器端推送的自定義消息。
自定義消息一定要由開發(fā)者寫接收推送消息 Receiver 來處理收到的消息。
注意:
當(dāng)自定義消息內(nèi)容 msg_content 為空時,SDK 不會對消息進行廣播,使得 App 無法接收到推送的消息,因此建議在使用自定義消息推送時添加內(nèi)容。
看一下自定義消息推送效果:

同樣自定義消息推送也可以使用標(biāo)簽和別名進行推送對象的限制,進行推送到某一特定對象或者某一對象。
查看一下logcat日志打?。?/p>

在代碼中的表現(xiàn)為:

我們可以在processCustomMessage(context, bundle);方法中進行對接收到自定義消息的處理。
到這里這篇文章就結(jié)束了,感謝大家的觀看。