`
knight_black_bob
  • 浏览: 857961 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

阅读更多

 

推送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/



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

  • 大小: 27.5 KB
  • 大小: 3.9 KB
  • 大小: 103.7 KB
1
1
分享到:
评论

相关推荐

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

    http://knight-black-bob.iteye.com/blog/2370938 推送sdk (类似百度 推送 ) android mina (待优化... ) 本demo 研究的是原理,不要计较太多。。。。 至于token生成,service 保活,定时启动 不做说明。

    mina消息推送例子

    在这个“mina消息推送例子”中,我们将深入探讨Mina如何实现消息推送,并结合Spring框架进行集成。 首先,Apache Mina提供了一个异步事件驱动的网络应用编程接口(API),它简化了TCP/IP和UDP协议的处理,如HTTP、...

    Android Mina框架使用

    在Android中,Mina可用于实时聊天应用、推送通知、远程控制等场景。通过Mina实现的长连接,可以确保数据实时、稳定地传输,提升用户体验。 7. **优化与注意事项** - 考虑到Android系统特性,如电量和流量限制,...

    基于Mina的Android消息推送系统的研究与实现.pdf

    【基于Mina的Android消息推送系统】是一种针对移动互联网中消息传输实时性和效率优化的技术解决方案。随着智能手机技术的迅速崛起,尤其是iOS和Android操作系统的普及,移动应用的需求日益增长,传统服务器被动接收...

    Android Mina UDP 所需jar包.rar

    在Android开发中,Mina库是一个非常重要的网络通信框架,它为开发者提供了高效、灵活的网络编程接口。Mina支持多种传输协议,包括TCP、UDP等。本资源提供的"Android Mina UDP 所需jar包.rar"正是针对使用UDP协议进行...

    Android Mina UDP数据交互

    在Android开发中,Mina库是一个非常强大的网络通信框架,它允许开发者构建高性能、高效率的网络应用程序。本文将深入探讨如何使用Mina库在Android客户端与Java服务器之间实现UDP(用户数据报协议)的数据交互。 UDP...

    Java-mina实现推送

    在本文中,我们将深入探讨如何利用Java-Mina实现服务端的主动推送功能,结合Spring进行应用集成。 首先,理解Java-Mina的核心概念至关重要。Mina提供了基于I/O多路复用技术(如NIO)的API,使得开发者可以轻松处理...

    Android-MinaSocket一款基于Mina的Socket长连接库

    **Android-MinaSocket:基于Mina的高效Socket长连接库** 在移动应用开发中,尤其是Android平台,实时性与稳定性是许多应用场景的核心需求,比如在线游戏、即时通讯、物联网设备等。在这种背景下,使用Socket进行长...

    学习见证消息推送时刻笔记

    【消息推送笔记】这篇笔记主要记录了学习郭林老师关于消息推送课程时的要点,特别是通过Mina框架实现服务器端的基础架构。Mina是一个轻量级的网络通信框架,广泛用于构建高性能、高可用性的网络应用程序,如消息推送...

    android mina 即时通讯 服务端客户端代码

    标签中提到了"QQ",这暗示了我们的即时通讯系统可能需要实现类似QQ的功能,比如群聊、一对一聊天、消息推送等。在Mina框架下,这些功能可以通过自定义`IoHandler`来实现。`IoHandler`是Mina中的核心接口,负责处理I/...

    android socket 编程 MINA 框架相关jar包

    MINA(Multipurpose Infrastructure for Network Applications)是一个强大的网络应用程序框架,它简化了在Java和Android平台上进行高性能、高效率的网络编程。MINA不仅支持TCP/IP协议,还支持UDP/IP,使得开发者...

    基于Android平台的长连接云推送服务设计.pdf

    在探讨基于Android平台的长连接云推送服务设计过程中,主要涉及以下几个关键技术点和概念: 1. Android平台:指的是由Google主导开发的开源操作系统,广泛应用于智能手机、平板电脑等移动设备。在本文中,它是指...

    mina及时推送客户端服务端实现

    在"mina及时推送客户端服务端实现"的项目中,我们将会探讨如何利用MINA来实现实时推送功能,并保持客户端和服务端的长连接。 1. **实时推送**:实时推送是现代应用中常见的一种需求,如消息通知、直播互动等。MINA...

    基于Android开发MINA框架使用详解

    在Android平台上,MINA可以简化网络通信的实现,帮助开发者专注于业务逻辑,而不是底层通信细节。 本教程将深入探讨如何在Android项目中集成MINA框架,以及如何解决在实际开发中可能遇到的问题,如中文乱码和消息...

    MinaServer for Android

    MinaServer通过优化内存管理和线程模型,能在各种Android设备上稳定运行,包括三星平板、小米手机、华为手机、三星手机和摩托罗拉手机。这表明MinaServer已经充分考虑了Android的平台特性,能够适应不同的硬件配置和...

    udp.rar_MINA udp_android mina UDP_mina_mina u

    标题中的“udp.rar_MINA udp_android mina UDP_mina_mina u”暗示了这是一个关于使用MINA框架在Android平台上实现UDP通信的资源包。MINA(Multipurpose Infrastructure for Network Applications)是一个高性能、...

    mina2推送demo客户端

    《MINA2推送Demo客户端详解及应用》 MINA(Multi-purpose Infrastructure for Network Applications)是一个高性能、异步的网络通信框架,由Apache软件基金会开发,主要用于构建网络应用程序,如TCP/IP和UDP/IP协议...

    apache-mina-2.0.4.rar_apache mina_mina

    这对于优化和重构Mina代码以提升性能将非常有帮助。 对于希望提高网络应用性能或熟悉Java NIO编程的开发者来说,Apache Mina 2.0.4的源码分析是一次宝贵的学习机会。你可以通过阅读源码学习到如何有效地处理高并发...

    基于FLEX,MINA消息推送核心代码

    本话题聚焦于基于FLEX和MINA的消息推送核心技术,这两种技术在构建高效、可靠的网络通信系统中发挥着重要作用。 FLEX是一种开源的富互联网应用程序(Rich Internet Application,RIA)开发框架,主要由Adobe公司...

    mina的Android端全套jar

    《mina在Android开发中的应用详解》 mina是一个开源的、基于Java NIO的网络通信框架,它为构建高性能、高可靠性的网络应用提供了强大的工具。在Android开发中,mina库可以用于实现高效的服务器与客户端之间的数据...

Global site tag (gtag.js) - Google Analytics