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

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

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

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

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

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

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

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);
    }
}

捐助开发者 

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


推送sdk (类似百度 推送 ) android  mina (待优化... )推送sdk (类似百度 推送 ) android  mina (待优化... )推送sdk (类似百度 推送 ) android  mina (待优化... )
 
 
 谢谢您的赞助,我会做的更好!

相关推荐