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



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

目录
相关文章
|
3月前
|
移动开发 监控 前端开发
构建高效Android应用:从优化布局到提升性能
【7月更文挑战第60天】在移动开发领域,一个流畅且响应迅速的应用程序是用户留存的关键。针对Android平台,开发者面临的挑战包括多样化的设备兼容性和性能优化。本文将深入探讨如何通过改进布局设计、内存管理和多线程处理来构建高效的Android应用。我们将剖析布局优化的细节,并讨论最新的Android性能提升策略,以帮助开发者创建更快速、更流畅的用户体验。
63 10
|
3月前
|
JavaScript 前端开发 Java
[Android][Framework]系统jar包,sdk的制作及引用
[Android][Framework]系统jar包,sdk的制作及引用
79 0
|
6天前
|
Java Linux API
Android SDK
【10月更文挑战第21天】
27 1
|
16天前
|
程序员 开发工具 Android开发
Android|使用阿里云推流 SDK 实现双路推流不同画面
本文记录了一种使用没有原生支持多路推流的阿里云推流 Android SDK,实现同时推送两路不同画面的流的方法。
40 7
|
25天前
|
调度 Android开发 开发者
构建高效Android应用:探究Kotlin多线程优化策略
【10月更文挑战第11天】本文探讨了如何在Kotlin中实现高效的多线程方案,特别是在Android应用开发中。通过介绍Kotlin协程的基础知识、异步数据加载的实际案例,以及合理使用不同调度器的方法,帮助开发者提升应用性能和用户体验。
40 4
|
2月前
|
存储 缓存 编解码
Android经典面试题之图片Bitmap怎么做优化
本文介绍了图片相关的内存优化方法,包括分辨率适配、图片压缩与缓存。文中详细讲解了如何根据不同分辨率放置图片资源,避免图片拉伸变形;并通过示例代码展示了使用`BitmapFactory.Options`进行图片压缩的具体步骤。此外,还介绍了Glide等第三方库如何利用LRU算法实现高效图片缓存。
61 20
Android经典面试题之图片Bitmap怎么做优化
|
7天前
|
安全 Android开发 iOS开发
深入探索iOS与Android系统的差异性及优化策略
在当今数字化时代,移动操作系统的竞争尤为激烈,其中iOS和Android作为市场上的两大巨头,各自拥有庞大的用户基础和独特的技术特点。本文旨在通过对比分析iOS与Android的核心差异,探讨各自的优势与局限,并提出针对性的优化策略,以期为用户提供更优质的使用体验和为开发者提供有价值的参考。
|
2月前
|
Java Android开发 UED
安卓应用开发中的内存管理优化技巧
在安卓开发的广阔天地里,内存管理是一块让开发者既爱又恨的领域。它如同一位严苛的考官,时刻考验着开发者的智慧与耐心。然而,只要我们掌握了正确的优化技巧,就能够驯服这位考官,让我们的应用在性能和用户体验上更上一层楼。本文将带你走进内存管理的迷宫,用通俗易懂的语言解读那些看似复杂的优化策略,让你的开发之路更加顺畅。
55 2
|
2月前
|
Java Android开发 开发者
安卓应用开发中的线程管理优化技巧
【9月更文挑战第10天】在安卓开发的海洋里,线程管理犹如航行的风帆,掌握好它,能让应用乘风破浪,反之则可能遭遇性能的暗礁。本文将通过浅显易懂的语言和生动的比喻,带你探索如何优雅地处理安卓中的线程问题,从基础的线程创建到高级的线程池运用,让你的应用运行更加流畅。
|
3月前
|
Ubuntu Android开发
安卓系统调试与优化:(一)bootchart 的配置和使用
本文介绍了如何在安卓系统中配置和使用bootchart工具来分析系统启动时间,包括安装工具、设备端启用bootchart、PC端解析数据及分析结果的详细步骤。
176 0
安卓系统调试与优化:(一)bootchart 的配置和使用