极光推送相关步骤

Anroid 部分:

    1.https://www.jpush.cn/apps/35125a964f7bf1019dee3d1b/detail/,进入极光推送平台创建应用

应用包名跟AndroidManifest.xml中的包名一致

   创建成功之后会生成你的appkey和 master secret,下面AndroidManifest.xml会用到你的appkey

  

     2、导入 SDK 开发包到你自己的应用程序项目

      

     3.配置AndroidManifest.xml

       

 AndroidManifest.xml权限配置:
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="Your Package"
    android:versionCode="100"
    android:versionName="1.0.0"
    >
    <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="17" />

    <!-- Required -->
    <permission android:name="Your Package.permission.JPUSH_MESSAGE" android:protectionLevel="signature" />

    <!-- Required -->
    <uses-permission android:name="You Package.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" /> 

    <!-- Optional. Required for location feature -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <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" />

应用包名及appkey替换:    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:name="Your Application">

        <!-- Required -->
        <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>

        <!-- Required SDK 核心功能-->
         <!-- since 1.8.0 -->
         <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="Your Package"/>
             </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="Your Package"/> 
            </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="Your Package" />
            </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. 用户自定义的广播接收器  
           如果全部类型的广播都接收,则需要在 AndroidManifest.xml 里添加如下的配置信息:
-->
 <receiver android:name="您自己定义的Receiver" android:enabled="true"> <intent-filter> <!--Required 用户注册SDKintent--> <action android:name="cn.jpush.android.intent.REGISTRATION" /> <action android:name="cn.jpush.android.intent.UNREGISTRATION" /> <!--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="您应用的包名" /> </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="Your AppKey"/> </application></manifest>
               4.添加代码

           

         在Application中   JPushInterface.init(this);             // 初始化 JPush

        设置别名:

                    为安装了应用程序的用户,取个别名来标识。以后给该用户 Push 消息时,就可以用此别名来指定。每个用户只能指定一个别名。

                    同一个应用程序内,对不同的用户,建议取不同的别名。这样,尽可能根据别名来唯一确定用户。

                    系统不限定一个别名只能指定一个用户。如果一个别名被指定到了多个用户,当给指定这个别名发消息时,服务器端API会同时给这多个用户发送消息。

        JPushInterface.setAlias(getApplicationContext(),
                                String.valueOf(userInfo.userID), mAliasCallback);

        private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

         @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);

                    //设置别名失败,60秒后重新设置别名

                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        Log.i(TAG, "No network");
                    }
                    break;

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

            //  ExampleUtil.showToast(logs, getApplicationContext());
        }

    };
         
       5.接收消息Receiver

package com.glodon.androidlibraryandframwork.push;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.glodon.androidlibraryandframwork.activity.LoginActivity;
import com.glodon.androidlibraryandframwork.activity.MainActivity;
import com.glodon.androidlibraryandframwork.activity.NewsActivity;
import com.glodon.androidlibraryandframwork.activity.UsersNewsActivity;
import com.glodon.androidlibraryandframwork.utils.SharePreferenceUtils;
import com.glodon.androidlibraryandframwork.utils.ToastUtils;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 *
 * 如果不定义这个 Receiver,则:
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";
    private SharePreferenceUtils share;

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        share = new SharePreferenceUtils(context);
        Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

        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] 用户点击打开了通知");
          //  ToastUtils.showShort(context,"有新消息,快去查看消息吧!!"+share.getString("name",""));
            if(share.getString("usersType","").equals("1")){
                Intent i = new Intent(context, UsersNewsActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS );
                context.startActivity(i);
            }else {
                //打开自定义的Activity
                Intent i = new Intent(context, NewsActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                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 {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    //send msg to MainActivity
    private void processCustomMessage(Context context, Bundle bundle) {
        if (MainActivity.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);
        }
    }
}


java后台部分:

    需要的jar包:slf4j-api-1.7.5.jar,jpush-client-2.4.1.jar,gson-2.2.4.jar

   在你需要推送的地方加上 JPushClientExample.testMain(); 就可以推送啦 

   代码:

 package com.lonuery.jpush;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.DeviceEnum;
import cn.jpush.api.push.CustomMessageParams;
import cn.jpush.api.push.MessageResult;
import cn.jpush.api.push.NotificationParams;
import cn.jpush.api.push.ReceiverTypeEnum;
import cn.jpush.api.report.ReceivedsResult;

public class JPushClientExample {
    protected static final Logger LOG = LoggerFactory.getLogger(JPushClientExample.class);
    
    // demo App defined in resources/jpush-api.conf
    private static final String appKey ="fbf92ca87ea46b0bafa1b2d3";
    private static final String masterSecret = "6ab20b6e4b05dceca3fc9d33";
    
    public static final String TITLE = "Test from API example";
    public static final String CONTENT = "[{\"t_id\":\"64\",\"u_id\":\"183\",\"m_contant\":\"\u6b22\u8fce\u548c\u6c11\u603b\u8385\u4e34\u6307\u5bfc\uff01\",\"type\":\"1\"}]";
    public static final String REGISTRATION_ID = "0900e8d85ef";
    public static final String TAG = "ponpay";
    
    private static long timeDelay = 24*60*60;
    
    public static void testMain() {
        testSend();
        testGetReport();
    }
    
    //推送样例
    private static void testSend() {
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, timeDelay, DeviceEnum.Android, false);
        
//        NotificationParams params = new NotificationParams();
//        params.setReceiverType(ReceiverTypeEnum.TAG);
//        params.setReceiverValue(TAG);
//                
//        params.setReceiverType(ReceiverTypeEnum.TAG);
//        params.setReceiverValue(TAG);

//        MessageResult msgResult = jpushClient.sendNotification(CONTENT, params,null);//推送通知给指定的app        
        //MessageResult msgResult = jpushClient.sendCustomMessage(TITLE, CONTENT, params, null);//推送消息给指定的app
        
        MessageResult msgResult = jpushClient.sendCustomMessageAll(TITLE, CONTENT);
//        MessageResult msgResult = jpushClient.sendNotificationAll(CONTENT);
        LOG.debug("responseContent - " + msgResult.responseResult.responseContent);
        if(msgResult!=null){
            if (msgResult.isResultOK()) {
                LOG.info("msgResult - " + msgResult);
                LOG.info("messageId - " + msgResult.getMessageId());
            } else {
                if (msgResult.getErrorCode() > 0) {
                    //业务异常
                    LOG.warn("Service error - ErrorCode: "
                            + msgResult.getErrorCode() + ", ErrorMessage: "
                            + msgResult.getErrorMessage());
                } else {
                    //未到达JPush
                    LOG.error("Other excepitons - "
                            + msgResult.responseResult.exceptionString);
                }
            }
        }else{
            System.out.println("MessageResult msgResult is null");
        }
        System.out.println("推送推出");
    }
    
    //统计获取样例
    public static void testGetReport() {
        JPushClient jpushClient = new JPushClient(masterSecret, appKey);
        ReceivedsResult receivedsResult = jpushClient.getReportReceiveds("1708010723,1774452771");
        LOG.debug("responseContent - " + receivedsResult.responseResult.responseContent);
        if (receivedsResult.isResultOK()) {
            LOG.info("Receiveds - " + receivedsResult);
        } else {
            if (receivedsResult.getErrorCode() > 0) {
                //业务异常
                LOG.warn("Service error - ErrorCode: "
                        + receivedsResult.getErrorCode() + ", ErrorMessage: "
                        + receivedsResult.getErrorMessage());
            } else {
                // 未到达JPush
                LOG.error("Other excepitons - "
                        + receivedsResult.responseResult.exceptionString);
            }
        }
        System.out.println("joe我的身份为");
    }
    public static final int MAX = Integer.MAX_VALUE;
    public static final int MIN = (int) MAX/2;
    
    public static int getRandomSendNo() {
        return (int) (MIN + Math.random() * (MAX - MIN));
    }
}


        


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值