极光推送---JPush---服务器端和android端怎么做

最近需要推送功能,就是一个人申请了,消息要立马传递给发布的人,就这么一个需求,而且是点对点的推送   就想到了用极光算了


后台采用的是  thinkcmf 开源框架  第三方插件官网也有说怎么做:http://www.thinkcmf.com/document/article/id/395.html  


那么先说服务端的:

simplewind/Core/Library/Vendor   在thinkcmf里面找到这样的地方,然后把第三方的包放在这个下面就可以了

这里并不采用像 官网上说的那种做法,而是这样的,

<?php
class pusher{
    //发送的应用程序
    private $app_key = '你在极光上申请的key';
    //密码
    private $master_secret = '你在极光上申请的那个密码';
    //推送地址
    private $url = 'https://api.jpush.cn/v3/push';
    
    public function __construct($app_key,$master_secret,$url){
        if($app_key) $this->app_key = $app_key;
        if($master_secret) $this->master_secret = $master_secret;
        if($url) $this->url = $url;
    }
    
    /*
     * 需要参数
     * $receive = 'all'  //全部
     * $receive = array('tag'=>array());
     * $receive = array('alias'=>array());  //别名
     * $content = '';   //测试数据
     * $m_type = 'http';    //推送附加字段的类型
     * $m_txt = '';     //推送附加字段类型对应的文字
     * $m_time = '86400';//离线保留时间
     */
    public function send_pub($receive,$content,$m_type,$m_txt,$m_time){
        $m_type = 'http';
        $m_txt = '';
        $m_time = '';
        $message = '';
        $result = $this->push($receive,$content,$m_type,$m_txt,$m_time);
        if($result){
            $res_arr = json_decode($result,true);
            //echo $res_arr['error']['message'];
            $message = '';  //存储推送状态
            if(isset($res_arr['error'])){
                $error_code = $res_arr['error']['code'];
                switch($error_code){
                    case 200:
                        $message = '发送成功';
                        break;
                    case 1000:
                        $message = '失败';
                        break;
                    case 1001:
                        $message = '不支持GET方法';
                        break;
                    case 1002:
                        $message = '缺少了必须参数';
                        break;
                    case 1003:
                        $message = '参数不合法';
                        break;
                    case 1004:
                        $message = '验证失败';
                        break;
                    case 1005:
                        $message = '消息体太大';
                        break;
                    case 1008:
                        $message = 'appkey参数非法';
                        break;
                    case 1020:
                        $message = '只支持https';
                        break;
                    case 1030:
                        $message = '内部服务器超时';
                        break;
                    default:
                        $message = '失败 (其他状态)';
                        break;
                } 
            }else{
                $message = '发送成功';
            }
        }else{
            $message = '接口调用失败或者无响应';
        }
        echo "<script>alert('推送消息:{$message}')</script>";
    }
    
    
    //
    public function push($receiver = 'all',$content = '' , $m_type , $m_txt , $m_time){
        $base64 = base64_encode("{$this->app_key}:{$this->master_secret}");
        $header = array(
            "Authorization:Basic $base64","Content-Type:application/json"
        );
        $data['platform'] = 'all';
        $data['audience'] = $receiver;
        $data['notification'] = array(
            "alert"=>$content,
            "android"=>array(
                'alert'=>$content,
                'title'=>'',
                'builder_id'=>1,
                'extras'=>array('type'=>$m_type,'txt'=>$m_txt)
            ),
            "ios"=>array(
                'alert'=>$content,
                'badge'=>1,
                'sound'=>'default',
                'extras'=>array('type'=>$m_type,'txt'=>$m_txt)
            )
        );
        $data['message'] = array(
            'msg_content'=>$content,
            'extras'=>array('type'=>$m_type,'txt'=>$m_txt)
        );
        $data['option'] = array(
            'sendno'=>time(),
            'time_to_live'=>$m_time,
            'apns_production'=>fals,    //当前是开发环境还是生产环境
        );
        $param = json_encode($data);
        $res = $this->push_curl($param,$header);
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    
    //通过curl进行推送
    public function push_curl($param = '',$header = ''){
        if(empty($param)) return false;
        $postUrl = $this->url;
        $curlPost = $param;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL ,$postUrl);
        curl_setopt($ch, CURLOPT_HEADER , 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST , 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost );
        curl_setopt($ch, CURLOPT_HTTPHEADER , $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }  
}

把这个文件放在Vendor 下面就可以 其他的不用管,

接下来就是在application下面建一个模块  暂时定为 JPush

写一个控制器

<?php
namespace JPusher\Controller;
use Common\Controller\HomeBaseController;
class JPusherController extends HomeBaseController{
   public function push(){
            vendor('pusher');
            $pusher = new \pusher();
            $a = array(
                'id'=>12,
                'msg'=>'hello world',
                'name'=>'呵呵'
            );
            $pusher->send_pub('all', json_encode($a), 'http', 'http://www.baidu.com', '12000');

   }

}

测试的时候采用的是广播形式推送  你可以把那个all改成  tag传送  ;改成alais别名推送 等

服务器端就写好了,接下来就是android端:

客户端首先是清单文件要把  在极光上申请的demo 全部copy一份到你现在的工程里面,主要包名要一致的哦,

然后是在自定义的application全局变量onCreate()里面加上这样两句:

         //极光推送
         JPushInterface.setDebugMode(true);
         JPushInterface.init(this);


接下来是建个包或者在工具包里面写个接收的工具类:

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 cn.jpush.android.api.JPushInterface;

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

	@Override
	public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
		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] 用户点击打开了通知");
            
        	//打开自定义的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())) {
            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);
		}
	}
}

这里面是你自己想要啥就保留啥,这是官网给的demo 

接下来就是点对点推送需要在用户登录的时候或者注册的时候你把用户的昵称  (别名)到极光那边注册下

	//初始化jpush
	private void initJpush()
	{
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				JPushInterface.setAliasAndTags(getApplicationContext(), uid, null, mTagAliasCallback);
			}
		}).start();
	}
	
	//下面是极光注册别名的时候的回调函数
	private final TagAliasCallback mTagAliasCallback = new TagAliasCallback() {
		
		@Override
		public void gotResult(int arg0, String arg1, Set<String> arg2) 
		{
			// TODO Auto-generated method stub
			switch(arg0)
			{
			case 0:
				cacheFunction.upDateCache(Constants.INIT_JPUSH, "1");
				handler.sendEmptyMessage(INIT_JPUSH);
				break;
			default:
				handler.sendEmptyMessage(INIT_JPUSH_FAILURE);
				break;
			}
		}
	};

这个代码是放在注册或者登录里面的,当你注册成功之后服务器返回状态码,判断之后就调用initJpush就可以了,

其他的还有几个小地方就不说了 大致上就这样


你可能感兴趣的:(Android开发,极光推送)