极光推送的简单使用

来源:互联网 发布:树莓派有线网络设置 编辑:程序博客网 时间:2024/05/16 10:59

1.创建应用,android 只需要一个应用包名即可:

2 填写包名

3.下载android sdk解压

4.加入so文件和jar

5.上一步骤是直接复制的,那样需要在gradle文件中加入:jniLibs.srcDirs=['libs']


apply plugin: 'com.android.application'android {    compileSdkVersion 23    buildToolsVersion "23.0.3"    defaultConfig {        applicationId "myapplication.com.jpushcom"        minSdkVersion 15        targetSdkVersion 23        versionCode 1        versionName "1.0"    }    buildTypes {        release {            minifyEnabled false            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }    }   <strong> sourceSets{        main{            jniLibs.srcDirs=['libs']        }    }</strong>}dependencies {    compile fileTree(include: ['*.jar'], dir: 'libs')    testCompile 'junit:junit:4.12'    compile 'com.android.support:appcompat-v7:23.3.0'    compile 'com.android.support:appcompat-v7:23.3.0'    compile files('libs/jpush-android-2.2.0.jar')}
6.加入权限,配置

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="myapplication.com.jpushcom">    <!-- Required -->    <permission        android:name="myapplication.com.jpushcom.permission.JPUSH_MESSAGE"        android:protectionLevel="signature" />    <!-- Required -->    <uses-permission android:name="myapplication.com.jpushcom.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.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" />    <!-- Optional. Required for location feature -->    <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:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        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-->        <!-- Required SDK 核心功能-->        <!-- option since 2.0.5 可配置PushService,DaemonService,PushReceiver,AlarmReceiver的android:process参数 将JPush相关组件设置为一个独立进程 -->        <!-- 如:android:process=":remote" -->        <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>        <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="myapplication.com.jpushcom"/>            </intent-filter>        </service>        <!-- Required -->        <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="myapplication.com.jpushcom"/>            </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" >            <intent-filter>                <action android:name="cn.jpush.android.ui.PushActivity" />                <category android:name="android.intent.category.DEFAULT" />                <category android:name="myapplication.com.jpushcom" />            </intent-filter>        </activity>        <!-- Required SDK核心功能-->        <service            android:name="cn.jpush.android.service.DownloadService"            android:enabled="true"            android:exported="false" >        </service>        <!-- Required SDK核心功能-->        <receiver android:name="cn.jpush.android.service.AlarmReceiver" />        <!-- 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" />                <!--Optional 用户接受Rich Push Javascript 回调函数的intent-->                <action android:name="cn.jpush.android.intent.ACTION_RICHPUSH_CALLBACK" />                <!-- 接收网络变化 连接/断开 since 1.6.3 -->                <action android:name="cn.jpush.android.intent.CONNECTION" />                <category android:name="myapplication.com.jpushcom" />            </intent-filter>        </receiver>        <meta-data android:name="JPUSH_CHANNEL" android:value="developer-default"/>        <!-- Required. AppKey copied from Portal -->        <meta-data android:name="JPUSH_APPKEY" android:value="ca0064dd201645762a56361d"/>    </application></manifest>

7.自定义的Myreceiver,有来处理接收到推送时的动作

package myapplication.com.jpushcom;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.os.Bundle;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";    //static String  bts_id;    @Override    public void onReceive(Context context, Intent intent) {        Bundle bundle = intent.getExtras();        //jia+0        Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras1: " + printBundle(bundle));        try {            JSONObject json1 = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));            String s=json1.getString("careline");            Log.d("ssssssssss",s);        } catch (JSONException e) {            e.printStackTrace();        }        //jia+ 1        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);            Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);            //send the Registration Id to your server...                                } 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())) {            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] 用户点击打开了通知");                        //打开自定义的Activity            Intent i = new Intent(context, MainActivity.class);            Bundle bundle1=intent.getExtras();            String extras=bundle1.getString(JPushInterface.EXTRA_EXTRA);            //得到附加信息值key 和value{"careline":"123"}            System.out.println("JPush1"+extras);            //intent.putExtra("id",bts_id);            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())) {            Log.d(TAG, "[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);            Log.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);        } else {            Log.d(TAG, "[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()) {                    Log.i(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()) {                        // 得到mykey                        String myKey = it.next().toString();                     //  bts_id=json.optString(myKey);                        sb.append("\nkey:" + key + ", value: [" +                                myKey + " - " +json.optString(myKey) + "]");                        Log.d("MYR", sb.toString());                    }                } 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 MainActivity//    private void processCustomMessage(Context context, Bundle bundle) {//        if (Owers_Activity.isForeground) {//            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);//            String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);//            Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);//            msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);//            if (!ExampleUtil.isEmpty(extras)) {//                try {//                    JSONObject extraJson = new JSONObject(extras);//                    if (null != extraJson && extraJson.length() > 0) {//                        msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);//                    }//                } catch (JSONException e) {////                }////            }//            context.sendBroadcast(msgIntent);//        }//    }}

8. 在mainactivity里面

注册下

package myapplication.com.jpushcom;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import cn.jpush.android.api.JPushInterface;public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        JPushInterface.setDebugMode(true);        JPushInterface.init(this);    }}

9.到此就可以成功推送了!

 

<!-  ---------------------------------->

10.上面的MyReceiver代码改一下:

package myapplication.com.jpushcom;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.os.Bundle;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";    //static String  bts_id;    @Override    public void onReceive(Context context, Intent intent) {        Bundle bundle = intent.getExtras();        //jia+0        Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras1: " + printBundle(bundle));        try {//            JSONObject json1 = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));//            String s=json1.getString("careline");//            Log.d("ssssssssss",s);        } catch (Exception e) {            e.printStackTrace();        }        //jia+ 1        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);            Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);            //send the Registration Id to your server...                                } 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())) {            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] 用户点击打开了通知");           /**            * 下面的代码就是处理点击通知栏后的动作,            * 这里就是简单的跳转到mainactivity,            * 在这里可以得到附加值            * ***/            //打开自定义的Activity            Intent i = new Intent(context, MainActivity.class);            Bundle bundle1=intent.getExtras();            String extras=bundle1.getString(JPushInterface.EXTRA_EXTRA);            //得到附加信息值key 和value{"careline":"123"}            System.out.println("JPush1"+extras);            //intent.putExtra("id",bts_id);            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())) {            Log.d(TAG, "[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);            Log.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);        } else {            Log.d(TAG, "[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()) {                    Log.i(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()) {                        // 得到mykey                        String myKey = it.next().toString();                     //  bts_id=json.optString(myKey);                        sb.append("\nkey:" + key + ", value: [" +                                myKey + " - " +json.optString(myKey) + "]");                        Log.d("MYR", sb.toString());                    }                } catch (JSONException e) {                    Log.e(TAG, "Get message extra JSON error!");                }            } else {                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));            }        }        return sb.toString();    }    }

11.在mainactivity中设置tag,可以实现针对性推送。

package myapplication.com.jpushcom;import android.os.Handler;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.text.TextUtils;import android.util.Log;import java.util.LinkedHashSet;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_TAGS = 1002;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        JPushInterface.setDebugMode(true);        JPushInterface.init(this);        setTag("gali");    }    // jiguan Tag    private 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) {            tagSet.add(sTagItme);        }        //调用JPush API设置Tag        mHandler3.sendMessage(mHandler3.obtainMessage(MSG_SET_TAGS, tagSet));    }    private final Handler mHandler3 = new Handler() {        @Override        public void handleMessage(android.os.Message msg) {            super.handleMessage(msg);            switch (msg.what) {                case MSG_SET_TAGS:                    //  Log.d(TAG, "在handler里面设置tags");                    JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, mTagsCallback);                    break;                default:                    //  Log.i(TAG, "handler没有内容 - " + msg.what);            }        }    };    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {        @Override        public void gotResult(int code, String alias, Set<String> tags) {            String logs ;            switch (code) {                case 0:                    logs = "设置别名和标签成功!";                    Log.d("Tag","oversuccess");                    break;                case 6002:                    logs = "设置超时,60s后重试!";                    Log.i("Tag", logs);                    break;                default:                    logs = "失败代码 = " + code;            }        }    };}

12.到这里基本是实现了,推送,设置tag,结束附加值,处理点击通知栏事件。

 

13.代码:http://pan.baidu.com/s/1jIsc5Hs



0 0
原创粉丝点击