欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

详解android环境下的即时通讯

程序员文章站 2024-02-26 14:05:40
首先了解一下即时通信的概念。通过消息通道 传输消息对象,一个账号发往另外一账号,只要账号在线,可以即时获取到消息,这就是最简单的即使通讯。消息通道可由tcp/ip udp实...

首先了解一下即时通信的概念。通过消息通道 传输消息对象,一个账号发往另外一账号,只要账号在线,可以即时获取到消息,这就是最简单的即使通讯。消息通道可由tcp/ip udp实现。通俗讲就是把一个人要发送给另外一个人的消息对象(文字,音视频,文件)通过消息通道(c/s实时通信)进行传输的服务。即时通讯应该包括四种形式,在线直传、在线代理、离线代理、离线扩展。在线直传指不经过服务器,直接实现点对点传输。在线代理指消息经过服务器,在服务器实现中转,最后到达目标账号。离线代理指消息经过服务器中转到达目标账号,对方不在线时消息暂存服务器的数据库,在其上线再传发。离线扩展指将暂存消息以其它形式,例如邮件、短信等转发给目标账号。

此外,我们还需要认识一下计算机网络相关的概念。经典的计算机网络四层模型中,tcp和udp是传输层协议,包含着消息通信内容。ip为网络层协议,是一种网络地址。tcp/ip,即传输控制协议/网间协议,定义了主机如何连入因特网及数据如何在它们之间传输的标准。socket,又称“套接字”, 在应用层和传输层之间的一个抽象层,用于描述 ip 地址和端口,是一个通信连的句柄,应用程序通常通过“套接字”向网络发送请求或者应答网络请求,它就是网络通信过程中端点的抽象表示。它把tcp/ip层复杂的操作抽象为几个简单的接口供应用层调用已实现进程在网络中通信。xmpp(可扩展消息处理现场协议)是基于可扩展标记语言(xml)的协议,应用于即时通讯场景的应用层协议,底层通过socket实现。它用于即时消息(im)以及在线现场探测。它在促进服务器之间的准即时操作。这个协议可能最终允许因特网用户向因特网上的其他任何人发送即时消息, 即使其操作系统和浏览器不同。这样实现即时通讯就有两种方案,一是从套接字入手,直接利用socket提供的接口进行数据的传送。二是借助开源工具(服务器openfire),用xmppconnection创建连接。

xmpp是实现即时通讯使用较为普遍的做法。xmpp中,各项工作都是通过在一个 xmpp 流上发送和接收 xmpp 节来完成的。核心 xmpp 工具集由三种基本节组成,这三种节分别为<presence>、出席<message>、<iq>。xmpp 流由两份 xml 文档组成,通信的每个方向均有一份文档。这份文档有一个根元素<stream:stream>,这个根元素的子元素由可路由的节以及与流相关的*子元素构成。xmpp协议同样包括客户端和服务器。客户端基于 android 平台进行开发。负责初始化通信过程,进行即时通信时,由客户端负责向服务器发起创建连接请求。系统通过 gprs 无线网络与internet 网络建立连接,通过服务器实现与 android 客户端的即时通信脚。服务器端则采用 openfire 作为服务器。 允许多个客户端同时登录并且并发的连接到一个服务器上。服务器对每个客户端的连接进行认证,对认证通过的客户端创建会话,客户端与服务器端之间的通信就在该会话的上下文中进行。使用了 asmark 开源框架实现的即时通讯功能.该框架基于开源的 xmpp 即时通信协议,采用 c/s 体系结构,通过 gprs 无线网络用tcp 协议连接到服务器,以架设开源的 openfn'e 服务器作为即时通讯平台。xmpp消息通道的创建:

 先配置通道信息进行连接

connectionconfiguration configuration = new connectionconfiguration(host, port)

设置debug信息和安全模式

configuration.setdebuggerenabled(true);

configuration.setsecuritymode(securitymode.disabled)

最后才是建立连接

conn.connect();

在contentobserver的实现类中观察消息变化。xmppconnection.getroster()获取联系人列表对象。用xmpp协议编写通讯协议的大致思路可以如下。进入登陆界面,通过xmppconnection的login方法实现登陆,登陆成功进入主界面。主界面包含两个fragment,分别用来显示联系人和聊天记录。创建联系人和短信的数据观察者,在联系人、短信服务中分别设定监听rosterlistener()、chatmanagerlistener(),接受联系人和短信信息,同时将相关信息添加到内容提供者中。在内容提供者中设定一个内容观察者,当数据发生变化时通知界面更新。

本文的重点是利用socket的接口实现即时通讯,因为绝大多数即时通讯的底层都是通过socket实现的。其基本的业务逻辑可描述如下。用户进入登陆界面后,提交账号密码 经服务端确定,返回相关参数用于确定连接成功。进入聊天界面或好友界面。点击联系人或聊天记录的条目,进入聊天界面。当移动端再次向服务器发送消息时,由服务器转发消息内容给目标账号。同时更新界面显示。这样就完成即时通讯的基本功能。当然,也可以添加一个后台服务,当用户推出程序时,在后台接受消息。不难看出,对于即时通讯来讲,有三个关注点:消息通道、消息内容、消息对象。因此,主要逻辑也是围绕这三个点展开。消息通道实现传输消息对象的发送和接收。为socket(string host, int port)传入服务其地址和端口号,即可创建连接。消息内容的格式应该与服务器保持一致。接受数据时,获取输入流并用datainputstream包装,通过输入流读取server发来的数据。发送数据时,获取输出流并用dataoutputstream包装,通过输出流往server发送数据。消息内容中应该包括发送者、接受者信息、数据类型等。消息对象就是消息的发送者和消息的接受者。接下来在代码中进行详细的讲解。

创建一个消息的基类,实现xml文件和字符串的转换,用到xsream第三方jar包。这样当创建消息类时,继承该方法,就可以直接在类中实现数据的转换。

/**
 * created by huang on 2016/12/3.
 */
public class protacolobjc implements serializable {
  public string toxml() {
    xstream stream = new xstream();
    //将根节点转换为类名
    stream.alias(this.getclass().getsimplename(), this.getclass());
    return stream.toxml(this);
  }

  public object fromxml(string xml) {
    xstream x = new xstream();
    x.alias(this.getclass().getsimplename(), this.getclass());
    return x.fromxml(xml);
  }
  
  //创建gson数据和字符串之间转换的方法,适应多种数据
  public string togson() {
    gson gson = new gson();
    return togson();
  }

  public object fromgson(string result) {
    gson gson = new gson();
    return gson.fromjson(result, this.getclass());
  }
}

创建线程工具,指定方法运行在子线程和主线程中。由于网络操作需要在子线程中,界面更新需要在主线程中,创建线程工具可以方便选择线程。

import android.os.handler;
/**
 * created by huang on 2016/12/5.
 */
public class threadutils {
  private static handler handler = new handler();
  public static void runuithread(runnable r){
    handler.post(r);
  }
  public static void runinthread(runnable r){
    new thread(r).start();
  }
}

创建消息的工具类,包括消息内容、消息类型、消息本省等。由于服务器返回的内容中包含消息的包名信息所以消息本身的包名应该于服务其保持一直。

/**
 * created by huang on 2016/12/3.
 * 消息内容
 */
public class qqmessage extends protacolobjc {
  public string type = qqmessagetype.msg_type_chat_p2p;// 类型的数据 chat login
  public long from = 0;// 发送者 account
  public string fromnick = "";// 昵称
  public int fromavatar = 1;// 头像
  public long to = 0; // 接收者 account
  public string content = ""; // 消息的内容 约不?
  public string sendtime = gettime(); // 发送时间

  public string gettime() {
    date date = new date(system.currenttimemillis());
    java.text.simpledateformat format = new java.text.simpledateformat("mm-dd hh:mm:ss");
    return format.format(date);
  }

  public string gettime(long time) {
    date date = new date(time);
    java.text.simpledateformat format = new java.text.simpledateformat("mm-dd hh:mm:ss");
    return format.format(date);
  }
}

/**
 * created by huang on 2016/12/3.
 * 消息类型
 */
public class qqmessagetype {
  public static final string msg_type_register = "register";// 注册
  public static final string msg_type_login = "login";// 登录
  public static final string msg_type_login_out = "loginout";// 登出
  public static final string msg_type_chat_p2p = "chatp2p";// 聊天
  public static final string msg_type_chat_room = "chatroom";// 群聊
  public static final string msg_type_offline = "offline";// 下线
  public static final string msg_type_success = "success";//成功
  public static final string msg_type_buddy_list = "buddylist";// 好友
  public static final string msg_type_failure = "failure";// 失败
}

import com.example.huang.imsocket.bean.protacolobjc;
/*
 *消息本身 包括 账号、头像和昵称
 *
 */
public class qqbuddy extends protacolobjc {
  public long account;
  public string nick;
  public int avatar;
}

/**
 * created by huang on 2016/12/3.
 */

public class qqbuddylist extends protacolobjc {
  public arraylist<qqbuddy> buddylist = new arraylist<>();
}

关于socket的创建连接和发送消息、接受消息。

import android.util.log;
import com.example.huang.imsocket.bean.qqmessage;
import java.io.datainputstream;
import java.io.dataoutputstream;
import java.io.ioexception;
import java.net.socket;
import java.util.arraylist;
import java.util.list;

/**
 * created by huang on 2016/12/3.
 * 连接 服务器
 */
public class qqconnection extends thread {
  private static final string tag = "qqconnection";
  private socket client;
  private dataoutputstream write;
  private datainputstream read;
  public static final string host = "192.168.23.48";
  public static final int post = 5225;

  private boolean flag = true;

  private list<onqqmwssagereceivelisener> monqqmwssagereceivelisener = new arraylist<>();

  public void addonqqmwssagereceivelisener(onqqmwssagereceivelisener lisener) {
    monqqmwssagereceivelisener.add(lisener);
  }

  public void removeonqqmwssagereceivelisener(onqqmwssagereceivelisener lisener) {
    monqqmwssagereceivelisener.remove(lisener);
  }

  public interface onqqmwssagereceivelisener {
    public void onreiceive(qqmessage qq);
  }

  @override
  public void run() {
    super.run();
    while (flag) {
      try {
        string utf = read.readutf();
        qqmessage message = new qqmessage();
        qqmessage msg = (qqmessage) message.fromxml(utf);
        if (msg != null) {
          for (onqqmwssagereceivelisener lisner : monqqmwssagereceivelisener)
            lisner.onreiceive(msg);
        }
      } catch (ioexception e) {
        e.printstacktrace();
      }
    }
  }

  public void connect() {
      try {
        if (client == null) {
          client = new socket(host, post);
          write = new dataoutputstream(client.getoutputstream());
          read = new datainputstream(client.getinputstream());
          flag = true;
          this.start();
          log.e(tag, "connect: "+(write==null)+"---"+ (read == null));
        }
      } catch (exception e) {
        e.printstacktrace();
      }
  }

  public void disconnect() {
    if (client != null) {
      flag = false;
      this.stop();
      try {
        read.close();
      } catch (ioexception e) {
        e.printstacktrace();
      }

      try {
        write.close();
      } catch (ioexception e) {
        e.printstacktrace();
      }

      try {
        client.close();
      } catch (ioexception e) {
        e.printstacktrace();
      }
    }
  }

  public void send(string xml) throws ioexception {
    write.writeutf(xml);
    write.flush();
  }

  public void send(qqmessage qq) throws ioexception {
    write.writeutf(qq.toxml());
    write.flush();
  }
}

 闪屏界面的布局

<?xml version="1.0" encoding="utf-8"?>
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/activity_splash"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@mipmap/splash_bg">

  <imageview
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerinparent="true"
    android:src="@mipmap/conversation_bg_logo" />
</relativelayout>

 闪屏界面,保持4秒钟进入登陆界面。一般来见,闪屏界面可以加载数据、获取版本号、更新版本等操作。这里没有做的那么复杂。

import com.example.huang.imsocket.r;

public class splashactivity extends appcompatactivity {

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    getsupportactionbar().hide();  //隐藏标栏
    getwindow().setflags(windowmanager.layoutparams.flag_fullscreen, windowmanager.layoutparams.flag_fullscreen); //全屏显示
    setcontentview(r.layout.activity_splash);

    new handler().postdelayed(new runnable() {
      @override
      public void run() {
        startactivity(new intent(splashactivity.this, loginactivity.class));
        finish();
      }
    }, 4000);
  }
}

登陆界面的布局

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#aabbdd"
  android:gravity="center"
  android:orientation="vertical">

  <tablelayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <imageview
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@mipmap/conversation_bg_logo" />

    <tablerow
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginleft="20dp"
      android:layout_marginright="20dp"
      android:layout_margintop="8dp"
      android:gravity="center_horizontal">

      <textview
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="账号:"
        android:textcolor="#000" />

      <edittext
        android:id="@+id/et_accoun"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:gravity="center"
        android:hint="输入账号" />
    </tablerow>

    <tablerow
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginleft="20dp"
      android:layout_marginright="20dp"
      android:layout_margintop="4dp"
      android:gravity="center_horizontal">

      <textview
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="密码:"
        android:textcolor="#000" />

      <edittext
        android:id="@+id/et_pwd"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:gravity="center"
        android:hint="输入密码" />
    </tablerow>

    <button
      android:id="@+id/btn_login"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginleft="80dp"
      android:layout_marginright="80dp"
      android:layout_margintop="8dp"
      android:onclick="sendmessage"
      android:text="登录" />

  </tablelayout>
</linearlayout>

 登陆界面,创建和服务器的连接,向服务器发送登陆信息,接受服务器返回的信息。

import android.app.activity;
import android.content.intent;
import android.os.bundle;
import android.util.log;
import android.view.view;
import android.widget.edittext;
import android.widget.toast;

import com.example.huang.imsocket.r;
import com.example.huang.imsocket.bean.myapp;
import com.example.huang.imsocket.bean.qqbuddylist;
import com.example.huang.imsocket.bean.qqmessage;
import com.example.huang.imsocket.bean.qqmessagetype;
import com.example.huang.imsocket.core.qqconnection;
import com.example.huang.imsocket.service.imservice;
import com.example.huang.imsocket.util.threadutils;

import java.io.ioexception;

/**
 * created by huang on 2016/12/3.
 */
public class loginactivity extends activity {
  private static final string tag = "loginactivity";

  private edittext et_accoun;
  private edittext et_pwd;

  private string accoun;
  private qqconnection conn;
  private qqconnection.onqqmwssagereceivelisener lisener = new qqconnection.onqqmwssagereceivelisener() {
    @override
    public void onreiceive(final qqmessage qq) {

      final qqbuddylist list = new qqbuddylist();
      final qqbuddylist list2 = (qqbuddylist) list.fromxml(qq.content);
      if (qqmessagetype.msg_type_buddy_list.equals(qq.type)) {
        threadutils.runuithread(new runnable() {
          @override
          public void run() {
            toast.maketext(getbasecontext(), "成功", toast.length_short).show();

            myapp.me = conn;
            myapp.username = accoun;
            myapp.account = accoun + "@qq.com";

            intent intent = new intent(loginactivity.this, contactactivity.class);
            intent.putextra("list", list2);
            startactivity(intent);

            intent data = new intent(loginactivity.this, imservice.class);
            startservice(data);
            finish();
          }
        });
      } else {
        threadutils.runuithread(new runnable() {
          @override
          public void run() {
            toast.maketext(getbasecontext(), "登陆失败", toast.length_short).show();
          }
        });
      }
    }
  };

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_login);
    et_accoun = (edittext) findviewbyid(r.id.et_accoun);
    et_pwd = (edittext) findviewbyid(r.id.et_pwd);
    threadutils.runinthread(new runnable() {
      @override
      public void run() {
        try {
          conn = new qqconnection();
          conn.addonqqmwssagereceivelisener(lisener);
          conn.connect();
        } catch (exception e) {
          e.printstacktrace();
        }
      }
    });
  }

  public void sendmessage(view view) {
    accoun = et_accoun.gettext().tostring().trim();
    final string password = et_pwd.gettext().tostring().trim();
    log.i(tag, "sendmessage: " + accoun + "#" + password);
    threadutils.runinthread(new runnable() {
      @override
      public void run() {
        qqmessage message = new qqmessage();
        message.type = qqmessagetype.msg_type_login;
        message.content = accoun + "#" + password;
        string xml = message.toxml();
        if (conn != null) {
          try {
            conn.send(xml);
          } catch (ioexception e) {
            e.printstacktrace();
          }
        }
      }
    });
  }

  @override
  protected void ondestroy() {
    super.ondestroy();
    conn.removeonqqmwssagereceivelisener(lisener);
  }
}

好友列表界面

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#aabbcc"
  android:orientation="vertical">

  <textview
    android:id="@+id/tv_title"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:gravity="center"
    android:text="联系人列表"
    android:textcolor="#6d00"
    android:textsize="23dp" />

  <listview
    android:id="@+id/lv_contact"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></listview>
</linearlayout>

好友列表及时收到从哪个服务其发挥的好友更新信息,点击条目跳到聊天界面。

import android.app.activity;
import android.content.intent;
import android.graphics.color;
import android.os.bundle;
import android.view.view;
import android.view.viewgroup;
import android.widget.adapterview;
import android.widget.arrayadapter;
import android.widget.imageview;
import android.widget.listview;
import android.widget.textview;
import android.widget.toast;

import com.example.huang.imsocket.r;
import com.example.huang.imsocket.bean.myapp;
import com.example.huang.imsocket.bean.qqbuddylist;
import com.example.huang.imsocket.bean.qqmessage;
import com.example.huang.imsocket.bean.qqmessagetype;
import com.example.huang.imsocket.core.qqconnection;
import com.example.huang.imsocket.util.threadutils;

import java.util.arraylist;

import butterknife.bind;
import butterknife.butterknife;
import cn.itcast.server.bean.qqbuddy;

/**
 * created by huang on 2016/12/5.
 */

public class contactactivity extends activity {
  private static final string tag = "contactactivity";
  @bind(r.id.tv_title)
  textview tv_title;
  @bind(r.id.lv_contact)
  listview lv_contact;
  private qqbuddylist list;
  private arraylist<qqbuddy> buddylist = new arraylist<>();
  private arrayadapter adapter = null;

  private qqconnection.onqqmwssagereceivelisener listener = new qqconnection.onqqmwssagereceivelisener() {
    @override
    public void onreiceive(qqmessage qq) {
      if (qqmessagetype.msg_type_buddy_list.equals(qq.type)) {
        qqbuddylist qqlist = new qqbuddylist();
        qqbuddylist qqm = (qqbuddylist) qqlist.fromxml(qq.content);
        buddylist.clear();
        buddylist.addall(qqm.buddylist);
        threadutils.runuithread(new runnable() {
          @override
          public void run() {
            saveandnotify();
          }
        });
      }
    }
  };

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_contact);
    butterknife.bind(this);
    myapp.me.addonqqmwssagereceivelisener(listener);
    intent intent = getintent();
    list = (qqbuddylist) intent.getserializableextra("list");
    buddylist.clear();
    buddylist.addall(list.buddylist);
    saveandnotify();
  }

  @override
  protected void ondestroy() {
    super.ondestroy();
    myapp.me.removeonqqmwssagereceivelisener(listener);
  }

  private void saveandnotify() {
    if (buddylist.size() < 1) {
      return;
    }
    if (adapter == null) {
      adapter = new arrayadapter<qqbuddy>(getbasecontext(), 0, buddylist) {
        @override
        public view getview(int position, view convertview, viewgroup parent) {
          viewholder holder;
          if (convertview == null) {
            convertview = view.inflate(getcontext(), r.layout.item_contacts, null);
            holder = new viewholder(convertview);
            convertview.settag(holder);
          } else {
            holder = (viewholder) convertview.gettag();
          }
          qqbuddy qqbuddy = buddylist.get(position);
          holder.tv_nick.settext(qqbuddy.nick);
          holder.tv_account.settext(qqbuddy.account + "@qq.com");

          if (myapp.username.equals(qqbuddy.account + "")) {
            holder.tv_nick.settext("[自己]");
            holder.tv_nick.settextcolor(color.gray);
          } else {
            holder.tv_nick.settextcolor(color.red);
          }
          return convertview;
        }
      };
      lv_contact.setadapter(adapter);

      lv_contact.setonitemclicklistener(new adapterview.onitemclicklistener() {
        @override
        public void onitemclick(adapterview<?> parent, view view, int position, long id) {
          qqbuddy qqbuddy = buddylist.get(position);
          if (myapp.username.equals(qqbuddy.account + "")) {
            toast.maketext(getbasecontext(), "不能和自己聊天", toast.length_short).show();
          } else {
            intent intent = new intent(contactactivity.this, chatactivity.class);
            intent.putextra("account", qqbuddy.account + "");
            intent.putextra("nick", qqbuddy.nick + "");
            startactivity(intent);
          }
        }
      });
    } else {
      adapter.notifydatasetchanged();
    }
  }

  static class viewholder {
    @bind(r.id.iv_contact)
    imageview iv_contact;
    @bind(r.id.tv_nick)
    textview tv_nick;
    @bind(r.id.tv_account)
    textview tv_account;
    public viewholder(view view) {
      butterknife.bind(this, view);
    }
  }
}

 聊天界面

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">

  <textview
    android:id="@+id/tv_name"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:background="#aa119988"
    android:gravity="center"
    android:text="和谁谁聊天中........."
    android:textsize="19dp" />

  <listview
    android:id="@+id/lv_chat"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

  <linearlayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <edittext
      android:id="@+id/et_sms"
      android:layout_width="0dp"
      android:layout_height="40dp"
      android:layout_weight="1"
      android:hint="输入聊天" />

    <button
      android:id="@+id/btn_send"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="发送" />
  </linearlayout>
</linearlayout>

聊天界面中消息接收和消息发送都需要及时更新列表。

import android.app.activity;
import android.content.intent;
import android.os.bundle;
import android.text.textutils;
import android.view.view;
import android.view.viewgroup;
import android.widget.arrayadapter;
import android.widget.edittext;
import android.widget.listview;
import android.widget.textview;
import android.widget.toast;

import com.example.huang.imsocket.r;
import com.example.huang.imsocket.bean.myapp;
import com.example.huang.imsocket.bean.qqmessage;
import com.example.huang.imsocket.bean.qqmessagetype;
import com.example.huang.imsocket.core.qqconnection;
import com.example.huang.imsocket.util.threadutils;

import java.io.ioexception;
import java.util.arraylist;

import butterknife.bind;
import butterknife.butterknife;
import butterknife.onclick;

/**
 * created by huang on 2016/12/3.
 */
public class chatactivity extends activity {
  private static final string tag = "chatactivity";
  @bind(r.id.tv_name)
  textview tv_name;
  @bind(r.id.lv_chat)
  listview lv_chat;
  @bind(r.id.et_sms)
  edittext et_sms;

  private arrayadapter<qqmessage> adapter = null;
  private arraylist<qqmessage> list = new arraylist<>();
  private string account;

  @onclick(r.id.btn_send)
  public void send(view view) {
    string sendsms = et_sms.gettext().tostring().trim();
    if (textutils.isempty(sendsms)) {
      toast.maketext(this, "消息不能为空", toast.length_short).show();
      return;
    }
    et_sms.settext("");
    final qqmessage qq = new qqmessage();
    qq.type = qqmessagetype.msg_type_chat_p2p;
    qq.content = sendsms;
    qq.from = long.parselong(myapp.username);
    qq.to = long.parselong(account);
    list.add(qq);
    setadapteornotify();
    threadutils.runinthread(new runnable() {
      @override
      public void run() {
        try {
          myapp.me.send(qq);
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
    });
  }

  private qqconnection.onqqmwssagereceivelisener listener = new qqconnection.onqqmwssagereceivelisener() {
    @override
    public void onreiceive(final qqmessage qq) {
      if (qqmessagetype.msg_type_chat_p2p.equals(qq.type)) {
        threadutils.runuithread(new runnable() {
          @override
          public void run() {
            list.add(qq);
            setadapteornotify();
          }
        });
      }
    }
  };

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_chat);
    butterknife.bind(this);
    myapp.me.addonqqmwssagereceivelisener(listener);
    intent intent = getintent();
    account = intent.getstringextra("account");
    string nick = intent.getstringextra("nick");
    tv_name.settext("和" + nick + "聊天中......");
    setadapteornotify();
  }

  @override
  protected void ondestroy() {
    super.ondestroy();
    myapp.me.removeonqqmwssagereceivelisener(listener);
  }

  private void setadapteornotify() {
    if (list.size() < 1) {
      return;
    }
    if (adapter == null) {
      adapter = new arrayadapter<qqmessage>(this, 0, list) {

        @override
        public int getviewtypecount() {
          return 2;
        }

        @override
        public int getitemviewtype(int position) {
          qqmessage msg = list.get(position);
          long fromid = long.parselong(myapp.username);
          if (fromid == msg.from) {
            return 0;
          }
          return 1;
        }

        @override
        public view getview(int position, view convertview, viewgroup parent) {
          int type = getitemviewtype(position);
          if (type == 0) {
            viewholder holder1 = null;
            if (convertview == null) {
              holder1 = new viewholder();
              convertview = view.inflate(getbasecontext(), r.layout.item_sms_send, null);
              holder1.tv_send_time = (textview) convertview.findviewbyid(r.id.tv_send_time);
              holder1.tv_send = (textview) convertview.findviewbyid(r.id.tv_send);
              convertview.settag(holder1);
            } else {
              holder1 = (viewholder) convertview.gettag();
            }
            qqmessage qqmessage = list.get(position);
            holder1.tv_send_time.settext(qqmessage.sendtime);
            holder1.tv_send.settext(qqmessage.content);
            return convertview;
          } else if (type == 1) {
            viewholder holder2 = null;
            if (convertview == null) {
              holder2 = new viewholder();
              convertview = view.inflate(getbasecontext(), r.layout.item_sms_receive, null);
              holder2.tv_receive_time = (textview) convertview.findviewbyid(r.id.tv_receive_time);
              holder2.tv_receive = (textview) convertview.findviewbyid(r.id.tv_receive);
              convertview.settag(holder2);
            } else {
              holder2 = (viewholder) convertview.gettag();
            }
            qqmessage qqmessage = list.get(position);
            holder2.tv_receive_time.settext(qqmessage.sendtime);
            holder2.tv_receive.settext(qqmessage.content);
            return convertview;
          }
          return convertview;
        }
      };
      lv_chat.setadapter(adapter);
    } else {
      adapter.notifydatasetchanged();
    }

    if (lv_chat.getcount() > 0) {
      lv_chat.setselection(lv_chat.getcount() - 1);
    }
  }

  class viewholder {
    textview tv_send_time;
    textview tv_send;
    textview tv_receive_time;
    textview tv_receive;
  }
}

 最后可以添加一个服务当程序退出时,接受消息。

import android.app.service;
import android.content.intent;
import android.os.ibinder;
import android.widget.toast;

import com.example.huang.imsocket.bean.myapp;
import com.example.huang.imsocket.bean.qqmessage;
import com.example.huang.imsocket.core.qqconnection;
import com.example.huang.imsocket.util.threadutils;

/**
 * created by huang on 2016/12/7.
 */

public class imservice extends service {
  private qqconnection.onqqmwssagereceivelisener lisener = new qqconnection.onqqmwssagereceivelisener() {
    @override
    public void onreiceive(final qqmessage qq) {
      threadutils.runuithread(new runnable() {
        @override
        public void run() {
          toast.maketext(getbasecontext(), "收到好友消息: " + qq.content, toast.length_short).show();
        }
      });
    }
  };

  @override
  public ibinder onbind(intent intent) {
    return null;
  }

  @override
  public void oncreate() {
    super.oncreate();
    toast.maketext(getbasecontext(), "服务开启", toast.length_short).show();
    myapp.me.addonqqmwssagereceivelisener(lisener);
  }

  @override
  public void ondestroy() {
    myapp.me.removeonqqmwssagereceivelisener(lisener);
    super.ondestroy();
  }
}

activity和service节点配置,以及相应的权限。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.huang.imsocket">

  <uses-permission android:name="android.permission.internet" />
  <application
    android:allowbackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsrtl="true"
    android:theme="@style/apptheme">

    <activity android:name="com.example.huang.imsocket.activity.splashactivity">
      <intent-filter>
        <action android:name="android.intent.action.main" />

        <category android:name="android.intent.category.launcher" />
      </intent-filter>
    </activity>
    <activity
      android:name="com.example.huang.imsocket.activity.loginactivity"
      android:theme="@android:style/theme.notitlebar"></activity>
    <activity
      android:name="com.example.huang.imsocket.activity.chatactivity"
      android:theme="@android:style/theme.notitlebar"></activity>
    <activity
      android:name="com.example.huang.imsocket.activity.contactactivity"
      android:theme="@android:style/theme.notitlebar"></activity>

    <service android:name=".service.imservice" />
  </application>

</manifest>


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。