九:基于xmpp的聊天

分手后的思念是犯贱 2022-08-10 15:53 249阅读 0赞

接着上一篇写, 写完这篇就可以聊天了。也期待了很久了。大笑

start:

1、先看一下效果:

Center

2、布局很简单,把聊天的内容放在了listView里,activity_chat.xml,用的strings.xml就不贴了,因为就有”发送“两个字。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:background="#ffffff"
  6. android:orientation="vertical" >
  7. <ListView
  8. android:id="@+id/lv_content"
  9. android:layout_width="match_parent"
  10. android:layout_height="414dp"
  11. android:background="#cccccc"
  12. android:cacheColorHint="@null"
  13. android:divider="@null"
  14. android:listSelector="@android:color/transparent"
  15. android:stackFromBottom="true" >
  16. </ListView>
  17. <RelativeLayout
  18. android:id="@+id/rl_bottom"
  19. android:layout_width="match_parent"
  20. android:layout_height="wrap_content" >
  21. <Button
  22. android:id="@+id/btn_voice"
  23. android:layout_width="40dp"
  24. android:layout_height="40dp"
  25. android:layout_alignParentLeft="true"
  26. android:layout_alignParentTop="true"
  27. android:background="@drawable/voice_bg" />
  28. <EditText
  29. android:id="@+id/et_sendContent"
  30. android:layout_width="wrap_content"
  31. android:layout_height="wrap_content"
  32. android:layout_centerVertical="true"
  33. android:layout_toLeftOf="@+id/btn_sendMessage"
  34. android:layout_toRightOf="@+id/btn_voice"
  35. android:hint=""
  36. android:ems="10" >
  37. <requestFocus />
  38. </EditText>
  39. <Button
  40. android:id="@+id/btn_face"
  41. android:layout_width="30dp"
  42. android:layout_height="30dp"
  43. android:layout_alignBaseline="@+id/btn_sendMessage"
  44. android:layout_alignBottom="@+id/btn_sendMessage"
  45. android:layout_alignRight="@+id/et_sendContent"
  46. android:background="@drawable/face" />
  47. <Button
  48. android:id="@+id/btn_sendMessage"
  49. android:layout_width="45dp"
  50. android:layout_height="45dp"
  51. android:layout_alignParentRight="true"
  52. android:layout_alignTop="@+id/et_sendContent"
  53. android:text="@string/chat_sendMsg"
  54. android:textSize="10sp" />
  55. </RelativeLayout>
  56. </LinearLayout>

3、聊天的java代码:注释很清楚,相信你明白的。得意

  1. package org.hkby.lwx.activity;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.hkby.lwx.adapter.ChatAdapter;
  5. import org.hkby.lwx.common.Msg;
  6. import org.hkby.lwx.common.SystemTime;
  7. import org.hkby.lwx.common.XmppTool;
  8. import org.jivesoftware.smack.Chat;
  9. import org.jivesoftware.smack.ChatManager;
  10. import org.jivesoftware.smack.ChatManagerListener;
  11. import org.jivesoftware.smack.MessageListener;
  12. import org.jivesoftware.smack.XMPPException;
  13. import org.jivesoftware.smack.packet.Message;
  14. import android.app.Activity;
  15. import android.content.Intent;
  16. import android.content.SharedPreferences;
  17. import android.os.Bundle;
  18. import android.os.Handler;
  19. import android.view.View;
  20. import android.view.Window;
  21. import android.view.View.OnClickListener;
  22. import android.widget.Button;
  23. import android.widget.EditText;
  24. import android.widget.ListView;
  25. /**
  26. * chat
  27. * @author liaowuxing
  28. *
  29. */
  30. public class ChatActivity extends Activity {
  31. private ChatAdapter adapter;
  32. private ListView lv_content;
  33. private Button btn_sendMessage;
  34. private EditText et_sendContent;
  35. private String friendName;
  36. private String account;
  37. // save message
  38. private List<Msg> listMsg = new ArrayList<Msg>();
  39. @Override
  40. protected void onCreate(Bundle savedInstanceState) {
  41. super.onCreate(savedInstanceState);
  42. requestWindowFeature(Window.FEATURE_NO_TITLE);
  43. setContentView(R.layout.activity_chat);
  44. //get the name of friend
  45. Intent intent = getIntent();
  46. Bundle bundle = intent.getBundleExtra("b_name");
  47. friendName = bundle.getString("name");
  48. //get the name of login user
  49. SharedPreferences sp = getSharedPreferences("username",
  50. Activity.MODE_PRIVATE);
  51. account = sp.getString("account", "");
  52. initView();
  53. chatClick();
  54. }
  55. public void initView() {
  56. lv_content = (ListView) this.findViewById(R.id.lv_content);
  57. et_sendContent = (EditText) this.findViewById(R.id.et_sendContent);
  58. btn_sendMessage = (Button) this.findViewById(R.id.btn_sendMessage);
  59. adapter = new ChatAdapter(listMsg, ChatActivity.this);
  60. lv_content.setAdapter(adapter);
  61. }
  62. public void chatClick() {
  63. // create chat
  64. final ChatManager cm = XmppTool.getConnection().getChatManager();
  65. // Listening to the chat messages from friends
  66. cm.addChatListener(new ChatManagerListener() {
  67. @Override
  68. public void chatCreated(Chat chat, boolean able) {
  69. chat.addMessageListener(new MessageListener() {
  70. @Override
  71. public void processMessage(Chat chat2, Message message) {
  72. android.os.Message m = handler.obtainMessage();
  73. m.obj = message;
  74. m.sendToTarget();
  75. }
  76. });
  77. }
  78. });
  79. //send chat message to friends
  80. btn_sendMessage.setOnClickListener(new OnClickListener() {
  81. @Override
  82. public void onClick(View arg0) {
  83. String content = et_sendContent.getText().toString();
  84. if (content.length() > 0) {
  85. Msg msg = new Msg(account, content, SystemTime.getDate(), "To");
  86. listMsg.add(msg);
  87. adapter.notifyDataSetChanged();
  88. try {
  89. Chat newchat = cm.createChat(friendName+"@"+XmppTool.getConnection().getServiceName(), null);
  90. newchat.sendMessage(content);
  91. } catch (XMPPException e) {
  92. e.printStackTrace();
  93. }
  94. }
  95. et_sendContent.setText("");
  96. }
  97. });
  98. }
  99. // Receives the message
  100. private Handler handler = new Handler() {
  101. public void handleMessage(android.os.Message msg) {
  102. Message m = new Message();
  103. m = (Message) msg.obj;
  104. String fromName = m.getFrom().toString().split("@")[0];
  105. Msg msg2 = new Msg(fromName, m.getBody().toString(), SystemTime.getDate(), "From");
  106. listMsg.add(msg2);
  107. adapter.notifyDataSetChanged();
  108. };
  109. };
  110. }

4、我建了类Msg,用来存放聊天人的姓名,信息,时间,是来至好友的还是发给好友的。

  1. package org.hkby.lwx.common;
  2. /**
  3. * chat message
  4. * @author liaowuxing
  5. *
  6. */
  7. public class Msg {
  8. public String username;
  9. public String msg;
  10. public String date;
  11. public String fromOrTo;
  12. public Msg(String username, String msg, String date, String fromOrTo) {
  13. this.username = username;
  14. this.msg = msg;
  15. this.date = date;
  16. this.fromOrTo = fromOrTo;
  17. }
  18. }

5、获取系统时间的类。

  1. package org.hkby.lwx.common;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. /**
  5. * get system time
  6. * @author liaowuxing
  7. *
  8. */
  9. public class SystemTime {
  10. private static SimpleDateFormat formatBuilder;
  11. public static String getDate(String format) {
  12. formatBuilder = new SimpleDateFormat(format);
  13. return formatBuilder.format(new Date());
  14. }
  15. public static String getDate() {
  16. return getDate("hh:mm:ss");
  17. }
  18. }

6、listView的adapter代码:

  1. package org.hkby.lwx.adapter;
  2. import java.util.List;
  3. import org.hkby.lwx.activity.R;
  4. import org.hkby.lwx.common.Msg;
  5. import android.content.Context;
  6. import android.view.LayoutInflater;
  7. import android.view.View;
  8. import android.view.ViewGroup;
  9. import android.widget.BaseAdapter;
  10. import android.widget.TextView;
  11. /**
  12. * chat adapter
  13. * @author liaowuxing
  14. *
  15. */
  16. public class ChatAdapter extends BaseAdapter {
  17. private List<Msg> listMsg;
  18. private LayoutInflater mInflater;
  19. private Context context;
  20. public ChatAdapter(List<Msg> listMsg,Context context) {
  21. super();
  22. this.context = context;
  23. this.listMsg = listMsg;
  24. mInflater = LayoutInflater.from(context);
  25. }
  26. @Override
  27. public int getCount() {
  28. if (listMsg.size() == 0) {
  29. return 0;
  30. }
  31. return listMsg.size();
  32. }
  33. @Override
  34. public Object getItem(int position) {
  35. return listMsg.get(position);
  36. }
  37. @Override
  38. public long getItemId(int position) {
  39. return position;
  40. }
  41. @Override
  42. public View getView(int position, View convertView, ViewGroup parent) {
  43. if (listMsg.get(position).fromOrTo.equals("From")) {
  44. ViewHolder viewHolder = new ViewHolder();
  45. convertView = mInflater.inflate(R.layout.chat_from_item, null);
  46. viewHolder.tv_username = (TextView)convertView.findViewById(R.id.tv_fromUsername);
  47. viewHolder.tv_data = (TextView)convertView.findViewById(R.id.tv_fromDate);
  48. viewHolder.tv_msg = (TextView)convertView.findViewById(R.id.tv_fromMsg);
  49. convertView.setTag(viewHolder);
  50. }else {
  51. ViewHolder viewHolder = new ViewHolder();
  52. convertView = mInflater.inflate(R.layout.chat_to_item, null);
  53. viewHolder.tv_username = (TextView)convertView.findViewById(R.id.tv_toUsername);
  54. viewHolder.tv_data = (TextView)convertView.findViewById(R.id.tv_toDate);
  55. viewHolder.tv_msg = (TextView)convertView.findViewById(R.id.tv_toMsg);
  56. convertView.setTag(viewHolder);
  57. }
  58. ViewHolder vHolder = (ViewHolder)convertView.getTag();
  59. String username = listMsg.get(position).username;
  60. String date = listMsg.get(position).date;
  61. String msg = listMsg.get(position).msg;
  62. if (username != null) {
  63. vHolder.tv_username.setText(username);
  64. }else {
  65. vHolder.tv_username.setText("");
  66. }
  67. if (date != null) {
  68. vHolder.tv_data.setText(date);
  69. }else {
  70. vHolder.tv_data.setText("");
  71. }
  72. if (msg != null) {
  73. vHolder.tv_msg.setText(msg);
  74. }else {
  75. vHolder.tv_msg.setText("");
  76. }
  77. return convertView;
  78. }
  79. private class ViewHolder{
  80. private TextView tv_username;
  81. private TextView tv_data;
  82. private TextView tv_msg;
  83. }
  84. }

7、由于聊天的内容,一左一右,需要两个布局,一个是来至好友的消息布局,chart_from_item.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6. <LinearLayout
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:orientation="horizontal" >
  10. <TextView
  11. android:id="@+id/tv_fromUsername"
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:layout_marginLeft="15.0dp"
  15. android:textColor="#FF666666"
  16. android:textSize="18sp"
  17. android:textStyle="bold" />
  18. <TextView
  19. android:id="@+id/tv_fromDate"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:layout_marginLeft="10.0dp"
  23. android:textColor="#FF666666" />
  24. </LinearLayout>
  25. <LinearLayout
  26. android:layout_width="wrap_content"
  27. android:layout_height="wrap_content"
  28. android:background="@drawable/incoming"
  29. android:paddingBottom="3.0dip"
  30. android:paddingLeft="15.0dip"
  31. android:paddingRight="10.0dip"
  32. android:paddingTop="3.0dip" >
  33. <TextView
  34. android:id="@+id/tv_fromMsg"
  35. android:layout_width="wrap_content"
  36. android:layout_height="wrap_content"
  37. android:textColor="#FF000000" />
  38. </LinearLayout>
  39. </LinearLayout>

8、一个是发送给好友的消息布局,chart_to_item.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6. <LinearLayout
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:layout_gravity="right"
  10. android:orientation="horizontal" >
  11. <TextView
  12. android:id="@+id/tv_toUsername"
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"
  15. android:textStyle="bold"
  16. android:textSize="18sp"
  17. android:textColor="#FF666666" />
  18. <TextView
  19. android:id="@+id/tv_toDate"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:layout_marginLeft="10.0dp"
  23. android:layout_marginRight="20.0dip"
  24. android:textColor="#FF666666" />
  25. </LinearLayout>
  26. <LinearLayout
  27. android:layout_width="wrap_content"
  28. android:layout_height="wrap_content"
  29. android:layout_gravity="right"
  30. android:background="@drawable/outgoing"
  31. android:paddingBottom="3.0dip"
  32. android:paddingLeft="10.0dip"
  33. android:paddingRight="20.0dip"
  34. android:paddingTop="3.0dip" >
  35. <TextView
  36. android:id="@+id/tv_toMsg"
  37. android:layout_width="wrap_content"
  38. android:layout_height="wrap_content"
  39. android:textColor="#FF000000" />
  40. </LinearLayout>
  41. </LinearLayout>

9、项目结构:

Center 1

10、ok,聊天的完成了。

发表评论

表情:
评论列表 (有 0 条评论,249人围观)

还没有评论,来说两句吧...

相关阅读