Android快速集成极光推送,内含自定义通知,通知推送对象到某一个人,或者某一群人

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ShenQiXiaYang/article/details/83042641

集成极光推送
使用jcenter 自动集成步骤
说明 : 使用 jcenter 自动集成,不需要在项目中添加 jar 和 so,jcenter 会自动完成依赖;在 AndroidManifest.xml 中不需要添加任何 JPush SDK 相关的配置,jcenter 会自动导入。

  • 确认 android studio 的 Project 根目录的主 gradle 中配置了 jcenter 支持。(新建 project 默认配置就支持)
buildscript {
    repositories {
        jcenter()
    }
    ......
}

allprojets {
    repositories {
        jcenter()
    }
}
  • 在 module 的 gradle 中添加依赖和 AndroidManifest 的替换变量。
android {
    ......
    defaultConfig {
        applicationId "com.xxx.xxx" //JPush 上注册的包名.
        ......

        ndk {
            //选择要添加的对应 cpu 类型的 .so 库。
            abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a'
            // 还可以添加 'x86', 'x86_64', 'mips', 'mips64'
        }

        manifestPlaceholders = [
            JPUSH_PKGNAME : applicationId,
            JPUSH_APPKEY : "你的 Appkey ", //JPush 上注册的包名对应的 Appkey.
            JPUSH_CHANNEL : "developer-default", //暂时填写默认值即可.
        ]
        ......
    }
    ......
}

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上注册的包名对应的appkey.
                JPUSH_CHANNEL: "developer-default", //暂时填写默认值即可.
        ]

    }
    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 版本的应用在6.0 系统上 层叠窗口权限 -->
    <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参数将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 可选项。用于同一设备中不同应用的JPush服务相互拉起的功能。 -->
        <!-- 若不启用该功能可删除该组件,将不拉起其他应用也不能被其他应用拉起 -->
        <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接口结果返回需要开发者配置一个自定的广播 -->
        <!-- 该广播需要继承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> -->


        <!-- &lt;!&ndash; User defined. 用户自定义的广播接收器&ndash;&gt; -->
        <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" />
                <!-- 接收网络变化 连接/断开 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 是为了方便开发者统计APK分发渠道。 -->
        <!-- 例如: -->
        <!-- 发到 Google Play 的APK可以设置为 google-play; -->
        <!-- 发到其他市场的 APK 可以设置为 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 节点下配置,如:

defaultConfig {
      applicationId "cn.jpush.example" // <--您应用的包名
      ……
 }

在 AndroidManifest 中使用 ${applicationId} 引用 gradle 中定义的包名

在极光推送哪里创建账户,创建应用,如下图:
在这里插入图片描述
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;  // 设置为铃声、震动、呼吸灯闪烁都要
        JPushInterface.setPushNotificationBuilder(1, builder);

        /**
         * 设置通知栏样式 - 定义通知栏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);
    }
}

关于自定义通知栏样式
JPush 通知推送到客户端时,默认使用手机的默认设置来显示通知栏,包括铃声、震动等效果。

如果开发者想要达到如下的效果,则需要使用“自定义通知栏样式”功能:

通知栏样式使用与默认不一样的设置,比如想要控制:
铃声、震动
显示图标
替换默认的通知栏样式。
推送消息指定通知栏样式编号
通知栏样式在服务器端向下推送时,只体现为一个编号(数字)。

推送通知的样式编号,应该是在客户端做了自定义通知栏样式设置的。
如果通知上的样式编号,在客户端检查不存在,则使用默认的通知栏样式。

不使用自定义通知栏样式时,此编号默认为 0。如需使用自定义的通知栏样式,编号应大于 0 小于 1000。先在客户端调 API 设置通知栏样式,推送设置 Builder ID 值即可在收到消息时得到对应的样式效果。

调 API 进行推送时,在 Notification - Android 属性下设置 builder_id 值

在 Portal 上发送通知时,首先选择推送平台为 Android,然后展开“可选设置”,开发者可指定当前要推送的通知的样式编号。如下图所示:
在这里插入图片描述
客户端设置通知栏样式
自定义的通知栏样式,是在客户端进行设置的。请参考 通知栏样式定制 API 来看所支持的功能。

自定义通知栏样式设计
有个 PushNotificationBuilder 概念,开发者使用 setPushNotificationBuilder 方法为某种类型的 PushNotificationBuilder 指定编号。
setPushNotificationBuilder 可以在 JPushInterface.init() 之后任何地方调用,可以是开发者应用的逻辑来触发调用,或者初始化时调用。
只需要设置一次,JPush SDK 会记住这个设置。在下次收到推送通知时,就根据通知里指定的编号来找到 PushNotificationBuilder 来展现、执行。
API - setDefaultPushNotificationBuilder 设置默认
此 API 改变默认的编号为 0 的通知栏样式。

API - setPushNotificationBuilder 指定编号
此 API 为开发者指定的编号,设置一个自定义的 PushNotificationBuilder(通知样式构建器)。

App.java文件中使用到到customer_notitfication_layout.xml文件,以及(通知)到小图标。
在这里插入图片描述

<?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 notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
                Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                // 在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码,比如打开新的Activity, 打开一个网页等..
                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 数据
    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 的数据.
 */
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"))) {
//            // 调用 Handler 来异步设置别名,一般都是用userId来进行设置别名(唯一性)。
//            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS,
//                    SharedUtil.getInt(this, "userId") + ""));
//            // 调用 Handler 来异步设置标签。
//            tags.add("vip");
//            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, tags));
//        }
        
        // 调用 Handler 来异步设置别名,一般都是用userId来进行设置别名(唯一性)。
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS,
                SharedUtil.getInt(this, "userId") + ""));
        // 调用 Handler 来异步设置标签。
        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:
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAlias(getApplicationContext(),
                            (String) msg.obj,
                            mAliasCallback);
                    break;
                case MSG_SET_TAGS:
                    // 调用 JPush 接口来设置标签。
                    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 里写一个成功设置的状态。成功设置一次后,以后不必再次设置了。
                    SharedUtil.putString(MainActivity.this, "alias", "success");
                    break;
                case 6002:
                    // 延迟 60 秒来调用 Handler 设置别名,标签
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
                    break;
                default:
                    break;
            }
        }
    };

}

使用别名
用于给某特定用户推送消息。别名,可以近似地被认为,是用户帐号里的昵称。
在代码中表现为:

// 调用 JPush 接口来设置别名。
                    JPushInterface.setAlias(getApplicationContext(),
                            (String) msg.obj,
                            mAliasCallback);

使用标签
用于给某一群人推送消息。
标签类似于博客里为文章打上 tag ,即为某资源分类。
在代码中表现为:

// 调用 JPush 接口来设置标签。
                    JPushInterface.setTags(getApplicationContext(),
                            tags,
                            mAliasCallback);

如果在MainActivity.java文件中一行代码也不写。使用刚创建好的MainActivity依旧可以收到通知,但是不能针对于特定人群,以及某个人进行通知推送。如果加上标签或者别名给通知的限制,就可以针对特定对象进行推送了呢。

Demo效果展示:
(一)广播所有人
在这里插入图片描述
在这里插入图片描述
(二)推送对象——某一群人(标签)
在这里插入图片描述
在这里插入图片描述
(三)推送对象——某个人(别名)
在这里插入图片描述
在这里插入图片描述
嗯,大家还记得我们在App.java文件中自定义通知栏Layout吗?
看看效果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

到这里这篇文章就结束了,感谢大家的观看。

猜你喜欢

转载自blog.csdn.net/ShenQiXiaYang/article/details/83042641