推送sdk (类似百度 推送 ) android mina (待优化... )

简介:   推送sdk (类似百度 推送 ) android  mina (待优化... )   本demo 研究的是原理,不要计较太多。。。。 至于token生成,service 保活,定时启动 不做说明。

 

推送sdk (类似百度 推送 ) android  mina (待优化... )

 

本demo 研究的是原理,不要计较太多。。。。 至于token生成,service 保活,定时启动 不做说明。

 

下载http://download.csdn.net/download/knight_black_bob/9823413

 

 


 

 

 

双开模拟器  进行验证。。。。


 
 
 

 

 

package cn.baoyou.curiousby.com.imsdk.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.alibaba.fastjson.JSON;

import org.apache.mina.core.session.IoSession;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import cn.baoyou.curiousby.com.imsdk.core.ClientSocket;
import cn.baoyou.curiousby.com.imsdk.core.ServerSocket;
import cn.baoyou.curiousby.com.imsdk.core.callback.IRecieveCallBack;
import cn.baoyou.curiousby.com.imsdk.message.Message;
import cn.baoyou.curiousby.com.imsdk.session.SessionManager;

/**
 * Created by cmcc-B100036 on 2017/4/18.
 */

public class MinaService extends Service{




    public static boolean send(Message msg){
        Log.i("baoy","--------------------");
        if (SessionManager.getInstance().isConnectable()){
            try {
                Log.i("baoy","write start" + msg.toString());
                SessionManager.getInstance().write(msg);
                Log.i("baoy","write end");
                return  true;
            } catch (Exception e) {
                return false;
            }
        }
        return false;
    }

    private IRecieveCallBack iRecieveCallBack = new IRecieveCallBack() {
        @Override
        public void recieve(Message msg) {
            Log.i("baoy","recievie msg ==== service " + msg.toString());
            Intent intent=new Intent();
            intent.setAction("cn.baoyou.curiousby.com.imsdk.msgrecieve");
            intent.putExtra("recieveMsg", JSON.toJSONString( msg));
            intent.putExtra("recieveMsgBytes",JSON.toJSONString( msg).getBytes());
            sendBroadcast(intent);
        }
    };


    public final class MinaBinder extends Binder {
        public MinaService getService() {
            return MinaService.this;
        }
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    ClientSocket instance = null;
    ServerSocket instancee = null;
    @Override
    public void onCreate() {
        super.onCreate();
        ExecutorService  service =   Executors.newFixedThreadPool(2);
        service.execute(new Runnable() {
            @Override
            public void run() {
                instance = ClientSocket.getInstance();
                instance.setiRecieveCallBack(iRecieveCallBack);
                instance.init();
                IoSession ioSession = null;
                try {
                    instance.start();
                }catch (Exception e) {

                }
            }
        });
        service.execute(new Runnable() {
            @Override
            public void run() {
                instancee = ServerSocket.getInstance();
                instancee.init();
                IoSession ioSession = null;
                try {
                    instancee.start();
                }catch (Exception e) {

                }
            }
        });


        service.shutdown();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        instance.stop();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }





}

 

 

package cn.baoyou.curiousby.com.imsdk.broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.SyncStateContract;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.baoyou.curiousby.com.imsdk.constants.Constants;
import cn.baoyou.curiousby.com.imsdk.message.Message;
import cn.baoyou.curiousby.com.imsdk.message.MessageFactory;
import cn.baoyou.curiousby.com.imsdk.operater.IMOriginalCallBack;

/**
 * Created by cmcc-B100036 on 2017/4/19.
 */

public class MsgReciever extends BroadcastReceiver {

    private IMOriginalCallBack iMOriginalCallBack;

    private static Map<Class,IMOriginalCallBack> map = new HashMap<>();

    public   MsgReciever setRecieve(Class clazz ,IMOriginalCallBack iMOriginalCallBack) {
         this.iMOriginalCallBack = iMOriginalCallBack;
        MsgReciever.map.put(clazz,iMOriginalCallBack);
        return this;
    }

    @Override
    public void onReceive(Context context, Intent intent) {

       if(Constants.ACTION .equals(intent.getAction())){
           String recieveMsg = intent.getStringExtra("recieveMsg");
           Log.i("baoy","=========msgrecieve==================="+recieveMsg);
           Message msg = MessageFactory.build(recieveMsg);
           for (   Map.Entry<Class,IMOriginalCallBack> entry : map.entrySet()) {
               Log.i("baoy","=========msgrecieve callback==================="+msg);
               Log.i("baoy","=========msgrecieve callback==================="+entry.getKey());
               Log.i("baoy","=========msgrecieve callback==================="+entry.getValue());
               ((IMOriginalCallBack) entry.getValue()).recieve(msg);
           }
       }

    }
}

 

package cn.baoyou.curiousby.com.imsdk.core;

import android.util.Log;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import cn.baoyou.curiousby.com.imsdk.core.callback.IRecieveCallBack;
import cn.baoyou.curiousby.com.imsdk.core.callback.IReconnect;
import cn.baoyou.curiousby.com.imsdk.message.ConnectionMessage;
import cn.baoyou.curiousby.com.imsdk.message.Message;
import cn.baoyou.curiousby.com.imsdk.message.MessageFactory;
import cn.baoyou.curiousby.com.imsdk.message.ShortMessage;
import cn.baoyou.curiousby.com.imsdk.message.enums.MessageTag;
import cn.baoyou.curiousby.com.imsdk.session.SessionManager;


public class ClientHandler extends IoHandlerAdapter  {
   // private static Logger log = Logger.getLogger(ClientHandler.class);

    private IRecieveCallBack iRecieveCallBack;
    private IReconnect iReconnect;

    volatile static boolean isConnected = false;

    public ClientHandler(IReconnect iReconnect,IRecieveCallBack iRecieveCallBack) {
        this.iRecieveCallBack = iRecieveCallBack;
        this.iReconnect = iReconnect;
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        Log.i("baoy","session created opened");
        super.sessionOpened(session);
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        Log.i("baoy","session created start");
        super.sessionCreated(session);
        Log.i("baoy","session created  end");
        isConnected = true;
        buildConnection(session);
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        Log.i("baoy","session created closed");
        super.sessionClosed(session);
        isConnected = false;
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        Log.i("baoy","session created sent");
        super.messageSent(session, message);
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        Log.i("baoy","session created caught");
        super.exceptionCaught(session, cause);
        isConnected = false;

    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        Log.i("baoy","session created idle");
        super.sessionIdle(session, status);
    }

    @Override
    public void messageReceived(IoSession session, Object json)
            throws Exception {

        super.messageReceived(session, json);
        Log.i("baoy","recievie msg       00 === (" + json.toString() +")MessageFactory.isChecked(json.toString()"+MessageFactory.isChecked(json.toString()) );
        if(MessageFactory.isChecked(json.toString()).equals( MessageTag.msg)) {
            Log.i("baoy","recievie msg       01 === " );
            Message build = MessageFactory.build(json.toString());
            if (iRecieveCallBack != null) {
                Log.i("baoy", "recievie msg  1 ===" + json.toString());
                iRecieveCallBack.recieve(build);
                Log.i("baoy", "recievie msg  2 ===" + json.toString());
            }
        }
    }



    public void buildConnection(IoSession session){
         if(session.isConnected()) {
             ConnectionMessage msg = new ConnectionMessage();
             msg.setUserKey("2");
             msg.setJson("connect");
             session.write(com.alibaba.fastjson.JSON.toJSONString(msg));

         }
    }
}

 

package cn.baoyou.curiousby.com.imsdk.core;

import android.util.Log;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import cn.baoyou.curiousby.com.imsdk.codec.CodecFactory;
import cn.baoyou.curiousby.com.imsdk.constants.Constants;
import cn.baoyou.curiousby.com.imsdk.core.callback.IRecieveCallBack;
import cn.baoyou.curiousby.com.imsdk.core.callback.IReconnect;
import cn.baoyou.curiousby.com.imsdk.message.ConnectionMessage;
import cn.baoyou.curiousby.com.imsdk.service.MinaService;


public class ClientSocket implements  IReconnect{

	IoConnector connector=null;
	
	private ClientSocket(){}
	private static ClientSocket instance = new ClientSocket();
	public static ClientSocket getInstance(){
		return instance;
	}

	private static IRecieveCallBack iRecieveCallBack;

	public static void  setiRecieveCallBack(IRecieveCallBack iRecieveCallBack) {
		ClientSocket.iRecieveCallBack = iRecieveCallBack;
	}

	public void init(){
		  connector = new NioSocketConnector();
		  ClientHandler handler = new ClientHandler(this,iRecieveCallBack);
		connector.setHandler(handler);

		IoFilter filter = new ProtocolCodecFilter(new CodecFactory());
		connector.getFilterChain().addLast("codec", filter);
		connector.getFilterChain().addLast("logging", new LoggingFilter());
	}
	public boolean start(){
		ConnectFuture connect = connector.connect(new InetSocketAddress(Constants.CLIENT_SOCKET_ADDRESS,Constants.CLIENT_SOCKET_PORT));
		connect.awaitUninterruptibly();
		return true;
	}



	public void stop(){
		if(connector != null){
			connector.dispose();
		}
	}


	@Override
	public void reconnection() {
		while(true) {

			if (!ClientHandler.isConnected) {
                 start();
			}

			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

 

package cn.baoyou.curiousby.com.imorginal;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import cn.baoyou.curiousby.com.imsdk.broadcastreceiver.MsgReciever;
import cn.baoyou.curiousby.com.imsdk.message.Message;
import cn.baoyou.curiousby.com.imsdk.message.ShortMessage;
import cn.baoyou.curiousby.com.imsdk.operater.IMOriginalCallBack;
import cn.baoyou.curiousby.com.imsdk.service.MinaService;

public class MainActivity extends AppCompatActivity implements View.OnClickListener ,IMOriginalCallBack{


    private EditText sendText;
    private TextView recieveText;

    private MsgReciever  reciever = new  MsgReciever().setRecieve(MainActivity.class , this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Intent intent =  new Intent(getApplicationContext(), MinaService.class);
        this.startService(intent);

        this.findViewById(R.id.bt_send_button).setOnClickListener(this);
        recieveText = (TextView) this.findViewById(R.id.id_recieveMsg);
        sendText = (EditText) this.findViewById(R.id.id_sendmsg);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_send_button:
                Log.i("baoy","=========================send"+sendText.getText().toString());
                ShortMessage shortMessage = new ShortMessage();
                shortMessage.setUserKey("2");
                shortMessage.setForm("2");
                shortMessage.setTo("1");
                shortMessage.setJson(sendText.getText().toString());

                blackboard +=  ""+((ShortMessage)shortMessage ).getForm()+"对" +((ShortMessage)shortMessage ).getTo() +" 说:"+shortMessage.getJson() +"\n";
                recieveText.setText(blackboard);

                MinaService.send(shortMessage);
                Log.i("baoy","========================");
                break;
        }
    }

    static String blackboard = "";
    @Override
    public void recieve(Message msg) {
        Log.i("baoy","=====main activity callback===================" + msg);
        blackboard +=  ""+((ShortMessage)msg ).getForm()+"对" +((ShortMessage)msg ).getTo() +" 说:"+msg.getJson() +"\n";
        recieveText.setText(blackboard);
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者 

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(支持支付宝和微信 以及扣扣群),没钱捧个人场,谢谢各位。

 

个人主页http://knight-black-bob.iteye.com/



 
 
 谢谢您的赞助,我会做的更好!

目录
相关文章
|
6月前
|
JavaScript Java Maven
云效产品使用常见问题之android sdk 构建出aar后,上传到私有maven仓库失败如何解决
云效作为一款全面覆盖研发全生命周期管理的云端效能平台,致力于帮助企业实现高效协同、敏捷研发和持续交付。本合集收集整理了用户在使用云效过程中遇到的常见问题,问题涉及项目创建与管理、需求规划与迭代、代码托管与版本控制、自动化测试、持续集成与发布等方面。
|
3月前
|
JavaScript 前端开发 Java
[Android][Framework]系统jar包,sdk的制作及引用
[Android][Framework]系统jar包,sdk的制作及引用
65 0
|
5天前
|
程序员 开发工具 Android开发
Android|使用阿里云推流 SDK 实现双路推流不同画面
本文记录了一种使用没有原生支持多路推流的阿里云推流 Android SDK,实现同时推送两路不同画面的流的方法。
21 7
|
3月前
|
开发工具 Android开发
解决Android运行出现NDK at /Library/Android/sdk/ndk-bundle did not have a source.properties file
解决Android运行出现NDK at /Library/Android/sdk/ndk-bundle did not have a source.properties file
155 4
解决Android运行出现NDK at /Library/Android/sdk/ndk-bundle did not have a source.properties file
|
3月前
|
Dart 开发工具 Android开发
Android Studio导入Flutter项目提示Dart SDK is not configured
Android Studio导入Flutter项目提示Dart SDK is not configured
236 4
|
3月前
|
开发工具 Android开发
Flutter: Android SDK not found at this location,Android Studio not found at xxx
Flutter: Android SDK not found at this location,Android Studio not found at xxx
145 2
|
3月前
|
开发工具 Android开发
[Android Studio]please select android sdk
[Android Studio]please select android sdk
55 1
|
3月前
|
移动开发 JavaScript 开发工具
Mac 10.9x下安装配置phonegap3.0开发环境 (涉及android sdk配置)
Mac 10.9x下安装配置phonegap3.0开发环境 (涉及android sdk配置)
|
4月前
|
存储 JSON JavaScript
小程序优化:第三方SDK过大解决方案
小程序开发中,项目目录中存放过大的js包,会被警告影响手机端性能,同时让开发编译启动变得很慢。慢是其次,单是影响性能这一点,就需要解决一下。
|
3月前
|
开发工具 Android开发
Android项目架构设计问题之SDK内部减少每次回调时的冗余判断逻辑如何解决
Android项目架构设计问题之SDK内部减少每次回调时的冗余判断逻辑如何解决
35 0