JPush是大规模APP推送平台 开发者集成SDK后,可以通过调用API推送消息。同时,JPush提供可视化的web端控制台发送通知,统计分析推送效果。

权限配置

|权限 |用途| | - |- | |包名.permission.JPUSH_MESSAGE|官方定义的权限,允许应用接收JPUSH内部代码发送的广播消息。| |RECEIVE_USER_PRESENT| 允许应用可以接收点亮屏幕或解锁广播。| |INTERNET|允许应用可以访问网络。| |WAKE_LOCK| 允许应用在手机屏幕关闭后后台进程仍然运行| |READ_PHONE_STATE| 允许应用访问手机状态。| |WRITE_EXTERNAL_STORAGE |允许应用写入外部存储。| |READ_EXTERNAL_STORAGE| 允许应用读取外部存储。| |WRITE_SETTINGS| 允许应用读写系统设置项。| |VIBRATE| 允许应用震动。| |MOUNT_UNMOUNT_FILESYSTEMS |允许应用挂载/卸载 外部文件系统。| |ACCESS_NETWORK_STATE |允许应用获取网络信息状态,如当前的网络连接是否有效。|

as jcenter 自动集成

defaultConfig{
 ndk {
            //设置支持的SO库架构(开发者可以根据需要,选择一个或多个平台的so)
            abiFilters /*"armeabi",*/ "armeabi-v7a"/*, "arm64-v8a", "x86", "arm64-v8a", "x86_64"*/
        }

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


dependencies {
   implementation 'cn.jiguang.sdk:jpush:版本号'
   implementation 'cn.jiguang.sdk:jcore:版本号'
}

定义接收通知的广播

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Logger.d("[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Logger.d("[MyReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            String type = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            Logger.d("[MyReceiver] 接收到推送下来的自定义消息: " + type);
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Logger.d("[MyReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Logger.d("[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Logger.d("[MyReceiver] 用户点击打开了通知");
        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Logger.d("[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);
            Logger.w("[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            Logger.d("[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    // 打印所有的 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 (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
                    Logger.i("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) {
                    Logger.e("Get message extra JSON error!");
                }
            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }


}

注册广播

在AndroidManifest.xml 中注册

<receiver
    android:name=".MyReceiver"
    android:enabled="true"
    android:exported="false">
    <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.ACTION_RICHPUSH_CALLBACK" /> <!-- Optional 用户接受Rich Push Javascript 回调函数的intent -->
        <action android:name="cn.jpush.android.intent.CONNECTION" /> <!-- 接收网络变化 连接/断开 since 1.6.3 -->
        <category android:name="com.yc.car" />
    </intent-filter>
</receiver>

初始化极光

在自定义的Application中初始化

 //初始化极光
JPushInterface.setDebugMode(true);  //是否打印日志
JPushInterface.init(this); //初始化 JPush。如果已经初始化,但没有登录成功,则执行重新登录。

极光推送有群体的推送和个人推送,因此每个账号都需要和极光进行绑定,可以使用别名和标签进行绑定。别名和标签通过后台获取。

public class JPushHelper {

    /**
     * 设置Alias
     */
    public static void setAlias(String alias){
        setAlias(0, alias);
    }

    private static void setAlias(int delay,final String alias){
        Observable.timer(delay, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        JPushInterface.setAliasAndTags(MyApplication.mContext, alias, null, mAliasCallback);
                    }
                });
    }

    private static final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:    
					//设置成功             
                    Logger.e(JPushInterface.getRegistrationID(MyApplication.mContext));
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 10s.";
                    Logger.i(logs);
                    if (isConnected(MyApplication.mContext)) {
                        setAlias(10, alias);
                    } else {
                        Logger.i("No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Logger.e(logs);
            }

        }

    };

    public static boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }
}

调用setAlias设置别名即可,这样后台就可以区分每个用户进行推送。