接收并处理经由网络推送过来的消息(极光推送SDK)

极光推送官网:Android SDK 概述 - 极光文档 http://docs.jiguang.cn/jpush/client/Android/android_sdk/

先看看入门指南,然后下载demo研究一番,就会恍然大悟明白啦~~~

最关键的就是配置app的build.gradle和AndroidManifest.xml文件,相信引进jar等文件应该不是啥难事儿吧(就像平时那样引进就行啦)

================================================================
1.在官网填写信息时,有一个地方需要你填写你的应用包名,记得千万别填错了,填写后是不能修改的。比如这个是我的包名:
这里写图片描述
图片中的jniLibs文件夹里就是我引进的jar等的文件结构。

2.在官网创建好应用后拿到key。

3.根据官网指南和demo配置好app的build.gradle和AndroidManifest.xml文件。我就不一一讲解了,下面我给出我配置好后的结果。
build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "你的包名"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        ndk {
            //选择要添加的对应cpu类型的.so库。
            abiFilters 'armeabi', 'armeabi-v7a', 'arm64-v8a'
            // 还可以添加 'x86', 'x86_64', 'mips', 'mips64'
        }
        manifestPlaceholders = [
                JPUSH_PKGNAME : applicationId,
                JPUSH_APPKEY : "你的key", //JPush上注册的包名对应的appkey.
                JPUSH_CHANNEL : "developer-default", //暂时填写默认值即可.
        ]
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
    repositories {
        flatDir {
            dirs 'libs'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    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'

    //极光推送jar
    implementation files('libs/jcore-android-1.2.0.jar')
    implementation files('libs/jpush-android-3.1.2.jar')      
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="你的包名">

    <!-- Required -->
    <permission
        android:name="你的包名.permission.JPUSH_MESSAGE"
        android:protectionLevel="signature" />
    <!-- Required  一些系统要求的权限,如访问网络等-->
    <uses-permission android:name="你的包名.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.WAKE_LOCK" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <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.ACCESS_WIFI_STATE" />

    <!-- Optional for location -->
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <!-- 用于开启 debug 版本的应用在6.0 系统上 层叠窗口权限 -->
    <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=".BaseApplication"
        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="你应用的主页">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


        <!-- Required SDK核心功能-->
        <activity
            android:name="cn.jpush.android.ui.PushActivity"
            android:configChanges="orientation|keyboardHidden"
            android:theme="@android:style/Theme.NoTitleBar"
            android:exported="false">
            <intent-filter>
                <action android:name="cn.jpush.android.ui.PushActivity" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="你的包名" />
            </intent-filter>
        </activity>

        <!-- Required SDK 核心功能-->
        <!-- 可配置android:process参数将PushService放在其他进程中 -->
        <service
            android:name="cn.jpush.android.service.PushService"
            android:process=":mult"
            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="你的包名.DataProvider"
            android:name="cn.jpush.android.service.DataProvider"
            android:exported="false"
            />
        <!-- since 3.1.0 Required SDK 核心功能-->
        <provider
            android:authorities="你的包名.DownloadProvider"
            android:name="cn.jpush.android.service.DownloadProvider"
            android:exported="true"
            />
        <!-- Required SDK核心功能-->
        <receiver
            android:name="cn.jpush.android.service.PushReceiver"
            android:enabled="true"
            android:exported="false">
            <intent-filter android:priority="1000">
                <action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED_PROXY" />   <!--Required  显示通知栏 -->
                <category android:name="你的包名" />
            </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核心功能-->
        <receiver android:name="cn.jpush.android.service.AlarmReceiver" android:exported="false"/>

        <!-- User defined.  For test only  用户自定义的广播接收器-->
        <receiver
            android:name="你自定义的广播接收器"
            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="你的包名" />
            </intent-filter>
        </receiver>

        <!-- Required  . Enable it you can get statistics data with channel -->
        <!-- Required  . Enable it you can get statistics data with channel -->
        <meta-data
            android:name="JPUSH_CHANNEL"
            android:value="developer-default"/>
        <meta-data
            android:name="JPUSH_APPKEY"
            android:value="你的key" />
    </application>

</manifest>

4.我使用了BaseApplication来进行极光的注册,为整个应用准备好,这个可以看你自己的需要。


import android.app.Application;
import cn.jpush.android.api.JPushInterface;

public class BaseApplication extends Application{

    private static BaseApplication mInstance;
    public  static String appName ;
    public static boolean isNotify = true;//通知栏是否提醒新消息

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        appName = getApplicationInfo().name;
        //请求权限
        //JPushInterface.requestPermission(this);
        //开启极光推送:
        //1.debug 为true则会打印debug级别的日志,false则只会打印warning级别以上的日志。
        JPushInterface.setDebugMode(false);
        JPushInterface.init(this);
        /*//停止极光推送:
        //1.JPush SDK 提供的推送服务是默认开启的;
        //2.如果停止推送服务后,开发者App被卸载重新安装,JPush SDK 会恢复正常的默认行为。
        JPushInterface.stopPush(this);
        //恢复极光推送:
        //1.调用了此 API 后,极光推送完全恢复正常工作。
        JPushInterface.resumePush(this);
        //用来检查 Push Service 是否已经被停止
        JPushInterface.isPushStopped(this);
        //JPush SDK开启和关闭省电模式,默认为关闭
        JPushInterface.setPowerSaveMode(this,false);
        //获得注册的key
        //String rid = JPushInterface.getRegistrationID(this);*/
    }
    public static BaseApplication getAppContext() {
        return mInstance;
    }

    public static boolean isIsNotify() {
        return isNotify;
    }

    public static void setIsNotify(boolean isNotify) {
        BaseApplication.isNotify = isNotify;
    }
}

5.自定义的广播接收器:

 @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            Logger.d(TAG, "[MessageReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                Logger.d(TAG, "[MessageReceiver] 接收Registration Id : " + regId);
                //send the Registration Id to your server...

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                Logger.d(TAG, "[MessageReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
                //自定义消息不会展示在通知栏,完全要开发者写代码去处理

                processCustomMessage(context, bundle);

            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                Logger.d(TAG, "[MessageReceiver] 接收到推送下来的通知");
                //如果通知的内容为空,则在通知栏上不会展示通知。
                //但是,这个广播 Intent 还是会有。开发者可以取到通知内容外的其他信息。
                //int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
                //Logger.d(TAG, "[MessageReceiver] 接收到推送下来的通知的ID: " + notifactionId);

            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                Logger.d(TAG, "[MessageReceiver] 用户点击打开了通知");

                //1. 一般情况下,用户不需要配置此 receiver action。
                //2.如果开发者在 AndroidManifest.xml 里未配置此 receiver action,
                // 那么,SDK 会默认打开应用程序的主 Activity,相当于用户点击桌面图标的效果。
                //3.如果开发者在 AndroidManifest.xml 里配置了此 receiver action,
                // 那么,当用户点击通知时,SDK 不会做动作。开发者应该在自己写的 BroadcastReceiver 类里处理,比如打开某 Activity 。
                //String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
                /*//打开自定义的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);*/

            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                Logger.d(TAG, "[MessageReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码,比如打开新的Activity, 打开一个网页等..

            } else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                //JPush 服务的连接状态发生变化。(注:不是指 Android 系统的网络连接状态。)
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                Logger.w(TAG, "[MessageReceiver]" + intent.getAction() +" connected state change to "+connected);
            } else {
                Logger.d(TAG, "[MessageReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

自定义消息处理方法(因为自定义消息不会展示在通知栏,完全要开发者写代码去处理):

//处理自定义消息
    private void processCustomMessage(Context context, Bundle bundle) {
        String title = bundle.getString(JPushInterface.EXTRA_TITLE);
        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        String jsonStr = bundle.getString(JPushInterface.EXTRA_EXTRA);//Json字符串
        //解析出消息内容后,你可以判断是否进行通知栏提醒消息等等处理啦    
    }

补充:
极光推送还有服务端的SDK,后台可以控制消息的推送、推送对象、推送的消息内容,经过后台的介入,就可以存储所有推送的消息内容了。当然是否需要后台的介入,这肯定要根据需求来定咯。

猜你喜欢

转载自blog.csdn.net/an_nal/article/details/80309855