openfire+asmack搭建的安卓即时通讯(一) 15.4.7

来源:互联网 发布:mobi格式软件ios 编辑:程序博客网 时间:2024/06/02 04:15

  最进开始做一些android的项目,除了一个新闻客户端的搭建,还需要一个实现一个即时通讯的功能,参考了很多大神成型的实例,了解到operfire+asmack是搭建简易即时通讯比较方便,所以就写了这篇博客。

一、基础知识(这是复制别人的)

XMPP协议简介

XMPP协议(Extensible Messaging and PresenceProtocol,可扩展消息处理现场协议)是一种基于XML的协议,目的是为了解决及时通信标准而提出来的,最早是在Jabber上实现的。它继承了在XML环境中灵活的发展性。因此,基于XMPP的应用具有超强的可扩展性。并且XML很易穿过防火墙,所以用XMPP构建的应用不易受到防火墙的阻碍。利用XMPP作为通用的传输机制,不同组织内的不同应用都可以进行有效的通信。

这篇文章有基本的介绍,http://blog.csdn.net/xutaozero21/article/details/4873439

IM

Instant Messenger,及时通信软件,就是大家使用的QQ、MSN Messenger和Gtalk等等。其中Gtalk 就是基于XMPP 协议的一个实现,其他的则不是。当前IM 几乎作为每个上网者必然使用的工具,在国外的大型企业中有一些企业级的IM应用,但是其商业价值还没完全发挥出来。设想既然XMPP 协议是一个公开的协议,那么每个企业都可以利用它来开发适合本身企业工作,提高自身生产效率的IM;甚至,你还可以在网络游戏中集成这种通信软件,不但让你可以边游戏边聊天,也可以开发出适合游戏本身的IM 应用,比如说一些游戏关键场景提醒功能,团队语音交流等等都可以基于IM来实现。

本文主要讲解在android使用xmpp协议进行即时通信,所涉及3个主要的东西,它们是openfire、smack和spark,这个三个东东结合起来就是完整的xmpp IM实现,这里简单介绍一下这3个东东在下文的作用:

openfire主要是作为服务器,负责管理客户端的通信连接,以及提供客户端一些通信信息和连接信息。

Smack主要是xmpp协议的实现,提供了一套很好的api,所以下面操作xmpp都是通过使用smack的api来实现,当然因为是在android里,所以使用的是asmack这个包,里面方法跟smack包差不多。

Spark 是IM客户端的实现,其实就是使用了smack 的api实现的。

Openfire的安装和配置:

    可参考http://www.cnblogs.com/hoojo/archive/2012/05/17/2506769.html

 二、实现第一步登录

    

做好了一系列的前期准备之后我们就能看到这样的用户后台管理了,其中注册了两个用户用来测试。

1.首先可以搭建简易的样式:

 

 够丑吧=-=

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">    <TextView        android:id="@+id/textview"        android:text="@string/hello_world"        android:textSize="48dp"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <TableLayout        android:layout_below="@id/textview"        android:id="@+id/tablelayout"        android:layout_width="match_parent"        android:layout_height="wrap_content">        <TableRow>            <TextView                android:layout_height="wrap_content"                android:text="Name:"                />            <EditText                android:id="@+id/login_name"                android:hint="Input your Name "                android:layout_height="wrap_content"                />        </TableRow>        <TableRow>            <TextView                android:layout_width="wrap_content"                android:text="Password:"                />            <EditText                android:id="@+id/login_password"                android:hint="Input your Password "                android:layout_height="wrap_content"                />        </TableRow>    </TableLayout>    <Button        android:id="@+id/buttonlogin"        android:layout_below="@id/tablelayout"        android:layout_width="wrap_content"        android:layout_height="48dp"        android:text="login in"/></RelativeLayout>

一个标题,两个输入,一个Login in的按钮够简单吧!!

2.代码实现:

首先将一些要用的方法封装到工具类里。

 1 public class connect { 2     private static ConnectionConfiguration connConfig;  3     private static XMPPConnection con; 4  5     public static XMPPConnection getConnection() {//获取连接 6         if (con == null || !con.isConnected()) { 7             openConnection(); 8         } 9         return con;10     }11     public static boolean openConnection() {//连接方法12         try {13             connConfig = new ConnectionConfiguration("192.168.252.1", 5222);   //5222是客户端和服务端的连接端口,其中的ip是我的内网ip15             // 设置登录状态为离线16             connConfig.setSendPresence(false);17             // 断网重连18             connConfig.setReconnectionAllowed(true);19             con = new XMPPConnection(connConfig);20             con.connect();21             return true;22         } catch (Exception e) {23             // TODO: handle exception24         }25         return false;26     }27     public static void closeConnection() {//断开连接28         con.disconnect();29     }
 1     public static boolean login(String account, String password) { 2         try { 3             if (connect.getConnection() == null) 4                 return false; 5             /** 登录 */ 6             SASLAuthentication.supportSASLMechanism("PLAIN", 0); 7             connect.getConnection().login(account, password); 8             // 设置登录状态:在线 9             // Presence presence = new Presence(Presence.Type.available);10             // connect.getConnection().sendPacket(presence);11             return true;12         } catch (Exception e) {13             e.printStackTrace();14         }15         return false;16     }
 1 public class MainActivity extends ActionBarActivity implements View.OnClickListener {//主函数 2     public static final int FAIL_CON=0; 3     public static final int SUCC_CON=0; 4     private String Tag = "MainAcy"; 5     private String account; 6     private String pwd; 7     @Override 8     protected void onCreate(Bundle savedInstanceState) { 9         super.onCreate(savedInstanceState);10         setContentView(R.layout.activity_main);11 12      //绑定按钮13         findViewById(R.id.buttonlogin).setOnClickListener(this);14 15     }16 17     private android.os.Handler insHandler = new android.os.Handler() {18         public void handleMessage(android.os.Message msg) {19             switch (msg.what) {20                 // 登录成功21                 case 1:22                     Toast.makeText(MainActivity.this,"SUCCESS",Toast.LENGTH_SHORT).show();23                     Log.d(Tag, "login suc");
              //跳转页面
24 Intent intent=new Intent();25 intent.putExtra("usename", account);
              //传值
26 intent.setClass(MainActivity.this, useractivity.class);27 startActivity(intent);28 break;29 case 0:30 Toast.makeText(MainActivity.this,"FAIL",Toast.LENGTH_SHORT).show();31 Log.d(Tag, "login fail");32 accountLogin();33 default:34 break;35 }36 }37 };38 39 private void accountLogin() {40 new Thread() {41 public void run() {42 account = ((EditText) findViewById(R.id.login_name))43 .getText().toString();44 pwd = ((EditText) findViewById(R.id.login_password)).getText()45 .toString();46 boolean is = ConnecMethod.login(account, pwd);47 if (is) {48 insHandler.sendEmptyMessage(1);49 // 保存用户名50 user.UserName = account;51 } else {52 insHandler.sendEmptyMessage(0);53 }54 };55 }.start();56 }57 58 @Override59 public void onClick(View v) {60 // TODO Auto-generated method stub61 switch (v.getId()) {62 case R.id.buttonlogin:63 accountLogin();64 default:65 break;66 }67 }68 }

 

我们为下一个页面传递了一个值就是我们登陆的用户名,所以在用户页面要:

 1     @Override 2     protected void onCreate(Bundle savedInstanceState) { 3         super.onCreate(savedInstanceState); 4         setContentView(R.layout.useractivity); 5         Intent intent =getIntent(); 6         String username=intent.getStringExtra("usename");//接收用户名 7         TextView textView= (TextView) findViewById(R.id.username);再体现在用户页的一个textiew里 8         textView.setText(username); 9         connect.closeConnection();
      //使用的连接服务要在登录成功后,即时销毁,否则下一次就会登陆错误。
10 }

这就是第一步的完成,近期不忙就会做下一步的完成。

  

 

1 0