[关闭]
@Tyhj 2016-11-28T14:20:17.000000Z 字数 12386 阅读 1461

Asmark+openFire开发Android聊天

实验班作业


利用asmark提供的方法来进行用户注册,查找,发送

消息和接收消息,我整理成了一个静态类具体方法如下:

  1. package publicinfo;
  2. import android.content.Context;
  3. import android.content.Intent;
  4. import android.content.SharedPreferences;
  5. import android.graphics.Bitmap;
  6. import android.graphics.drawable.BitmapDrawable;
  7. import android.graphics.drawable.Drawable;
  8. import android.util.Log;
  9. import com.avos.avoscloud.AVException;
  10. import com.avos.avoscloud.AVObject;
  11. import com.avos.avoscloud.AVQuery;
  12. import com.avos.avoscloud.DeleteCallback;
  13. import com.avos.avoscloud.FindCallback;
  14. import com.avos.avoscloud.GetCallback;
  15. import com.tyhj.myfist_2016_6_29.MyTime;
  16. import org.jivesoftware.smack.AccountManager;
  17. import org.jivesoftware.smack.ConnectionConfiguration;
  18. import org.jivesoftware.smack.Roster;
  19. import org.jivesoftware.smack.RosterEntry;
  20. import org.jivesoftware.smack.XMPPConnection;
  21. import org.jivesoftware.smack.XMPPException;
  22. import org.jivesoftware.smack.packet.Presence;
  23. import org.jivesoftware.smack.provider.ProviderManager;
  24. import org.jivesoftware.smack.util.StringUtils;
  25. import org.jivesoftware.smackx.Form;
  26. import org.jivesoftware.smackx.ReportedData;
  27. import org.jivesoftware.smackx.ServiceDiscoveryManager;
  28. import org.jivesoftware.smackx.packet.VCard;
  29. import org.jivesoftware.smackx.search.UserSearchManager;
  30. import java.io.BufferedReader;
  31. import java.io.ByteArrayInputStream;
  32. import java.io.ByteArrayOutputStream;
  33. import java.io.File;
  34. import java.io.InputStreamReader;
  35. import java.net.URL;
  36. import java.net.URLConnection;
  37. import java.util.ArrayList;
  38. import java.util.Collection;
  39. import java.util.HashMap;
  40. import java.util.Iterator;
  41. import java.util.List;
  42. import api.File2Bytes;
  43. import api.FormatTools;
  44. import service.ChatService;
  45. /**
  46. * Created by Tyhj on 2016/10/16.
  47. */
  48. public class UserInfo {
  49. private static int SERVER_PORT = 5222;
  50. private static String SERVER_HOST = "120.27.49.173";
  51. private static String SERVER_NAME = "120.27.49.173";
  52. public static boolean canDo() {
  53. if (xmppConnection != null && xmppConnection.isConnected())
  54. return true;
  55. else
  56. return false;
  57. }
  58. static {
  59. try {
  60. Class.forName("org.jivesoftware.smack.ReconnectionManager");
  61. } catch (Exception e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. //名字
  66. static String name;
  67. //id
  68. static String id;
  69. //连接
  70. static XMPPConnection xmppConnection;
  71. // 加入组的名字
  72. static String groupName;
  73. //
  74. private static void setXmppConnection() {
  75. try {
  76. Class.forName("org.jivesoftware.smack.ReconnectionManager");
  77. } catch (Exception e) {
  78. e.printStackTrace();
  79. }
  80. XMPPConnection conn;
  81. ConnectionConfiguration config = new ConnectionConfiguration(
  82. SERVER_HOST, SERVER_PORT, SERVER_NAME);
  83. config.setReconnectionAllowed(true);
  84. config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
  85. config.setSASLAuthenticationEnabled(false);
  86. conn = new XMPPConnection(config);
  87. try {
  88. conn.connect();
  89. xmppConnection = conn;
  90. } catch (XMPPException e) {
  91. e.printStackTrace();
  92. }
  93. }
  94. public static void setXmppConnection(XMPPConnection xmppConnection) {
  95. UserInfo.xmppConnection = xmppConnection;
  96. }
  97. //登陆
  98. public static synchronized boolean Login(String name, String pas, Context context) {
  99. try {
  100. if (!MyFunction.isIntenet(context, null))
  101. return false;
  102. setXmppConnection();
  103. if (xmppConnection == null || !xmppConnection.isConnected())
  104. return false;
  105. xmppConnection.login(name, pas);
  106. Presence presence = new Presence(Presence.Type.available);
  107. xmppConnection.sendPacket(presence);
  108. SharedPreferences shared = context.getSharedPreferences("login", Context.MODE_PRIVATE);
  109. SharedPreferences.Editor editor = shared.edit();
  110. editor.putString("name", name);
  111. editor.putString("pas", pas);
  112. editor.commit();
  113. UserInfo.id = name;
  114. UserInfo.groupName = name + MyFunction.getTime();
  115. return true;
  116. } catch (XMPPException e) {
  117. e.printStackTrace();
  118. }
  119. return false;
  120. }
  121. //重新连接
  122. public static synchronized boolean reLogin(Context context) {
  123. try {
  124. if (!MyFunction.isIntenet(context, null))
  125. return false;
  126. if (MyFunction.isServiceRun(context, "service.ChatService")) {
  127. xmppConnection = ChatService.getConnection();
  128. return true;
  129. }
  130. SharedPreferences shared = context.getSharedPreferences("login", Context.MODE_PRIVATE);
  131. UserInfo.id = shared.getString("name", null);
  132. UserInfo.groupName = id + MyFunction.getTime();
  133. if (!canDo())
  134. setXmppConnection();
  135. if (!canDo())
  136. return false;
  137. xmppConnection.login(id, shared.getString("pas", null));
  138. Presence presence = new Presence(Presence.Type.available);
  139. xmppConnection.sendPacket(presence);
  140. return true;
  141. } catch (Exception e) {
  142. e.printStackTrace();
  143. }
  144. return false;
  145. }
  146. //注册
  147. public static boolean Register(String account, String password, Context context) {
  148. if (!MyFunction.isIntenet(context, null))
  149. return false;
  150. setXmppConnection();
  151. if (xmppConnection == null)
  152. return false;
  153. AccountManager manager = new AccountManager(xmppConnection);
  154. try {
  155. manager.createAccount(account, password);
  156. } catch (XMPPException e) {
  157. return false;
  158. }
  159. return true;
  160. }
  161. //退出登录
  162. public static void logout(Context context) {
  163. SharedPreferences shared = context.getSharedPreferences("login", Context.MODE_PRIVATE);
  164. shared.edit().clear().commit();
  165. shared = context.getSharedPreferences("chat_date", Context.MODE_PRIVATE);
  166. shared.edit().clear().commit();
  167. if (UserInfo.canDo())
  168. xmppConnection.disconnect();
  169. final AVQuery<AVObject> query = new AVQuery<>("Image");
  170. query.whereEqualTo("user", UserInfo.getId());
  171. query.findInBackground(new FindCallback<AVObject>() {
  172. @Override
  173. public void done(List<AVObject> list, AVException e) {
  174. if (e == null && list.size() > 0) {
  175. for (int i = 0; i < list.size(); i++) {
  176. list.get(i).deleteInBackground();
  177. }
  178. }
  179. }
  180. });
  181. final AVQuery<AVObject> query1 = new AVQuery<>("Record");
  182. query1.whereEqualTo("user", UserInfo.getId());
  183. query1.findInBackground(new FindCallback<AVObject>() {
  184. @Override
  185. public void done(List<AVObject> list, AVException e) {
  186. if (e == null && list.size() > 0) {
  187. for (int i = 0; i < list.size(); i++) {
  188. list.get(i).deleteInBackground();
  189. }
  190. }
  191. }
  192. });
  193. Intent intent = new Intent(context, ChatService.class);
  194. context.stopService(intent);
  195. }
  196. //强制下线
  197. public static void logoutFore(Context context) {
  198. SharedPreferences shared = context.getSharedPreferences("login", Context.MODE_PRIVATE);
  199. SharedPreferences.Editor editor = shared.edit();
  200. editor.clear();
  201. editor.commit();
  202. if (xmppConnection.isConnected())
  203. xmppConnection.disconnect();
  204. Intent intent = new Intent(context, ChatService.class);
  205. context.stopService(intent);
  206. }
  207. //修改密码
  208. public static boolean changePassword(Context context, String pwd, String prepas, boolean b) {
  209. SharedPreferences shared = context.getSharedPreferences("login", Context.MODE_PRIVATE);
  210. String pas = shared.getString("pas", null);
  211. if (!canDo())
  212. return false;
  213. if (b && pas != null) {
  214. try {
  215. xmppConnection.getAccountManager().changePassword(pwd);
  216. return true;
  217. } catch (XMPPException e) {
  218. return false;
  219. }
  220. } else if (pas != null) {
  221. if (pas.equals(prepas)) {
  222. try {
  223. xmppConnection.getAccountManager().changePassword(pwd);
  224. return true;
  225. } catch (XMPPException e) {
  226. return false;
  227. }
  228. } else
  229. return false;
  230. }
  231. return false;
  232. }
  233. //查询用户
  234. public static List<HashMap<String, String>> searchUsers(String userName) {
  235. if (!canDo())
  236. return null;
  237. HashMap<String, String> user = null;
  238. List<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();
  239. try {
  240. new ServiceDiscoveryManager(xmppConnection);
  241. UserSearchManager usm = new UserSearchManager(xmppConnection);
  242. Form searchForm = usm.getSearchForm(xmppConnection.getServiceName());
  243. Form answerForm = searchForm.createAnswerForm();
  244. answerForm.setAnswer("userAccount", true);
  245. answerForm.setAnswer("userPhote", userName);
  246. ReportedData data = usm.getSearchResults(answerForm, xmppConnection.getServiceName());
  247. Iterator<ReportedData.Row> it = data.getRows();
  248. ReportedData.Row row = null;
  249. while (it.hasNext()) {
  250. user = new HashMap<String, String>();
  251. row = it.next();
  252. user.put("userAccount", row.getValues("userAccount").next()
  253. .toString());
  254. Log.e("获取的东西", row.getValues("userAccount").next().toString());
  255. user.put("userPhote", row.getValues("userPhote").next().toString());
  256. Log.e("获取的东西", row.getValues("userPhote").next().toString());
  257. results.add(user);
  258. // 若存在,则有返回,UserName一定非空,其他两个若是有设,一定非空
  259. }
  260. Log.e("my=没有", "哈哈哈哈哈哈哈");
  261. } catch (XMPPException e) {
  262. e.printStackTrace();
  263. }
  264. return results;
  265. }
  266. //获取用户信息
  267. public VCard getUserVCard(String user) {
  268. if (!canDo())
  269. return null;
  270. VCard vcard = new VCard();
  271. try {
  272. vcard.load(xmppConnection, user);
  273. } catch (XMPPException e) {
  274. e.printStackTrace();
  275. }
  276. Log.e("获取的东西", vcard.getNickName());
  277. return vcard;
  278. }
  279. //添加好友
  280. public static void addUser(String userName) {
  281. if (!canDo())
  282. return;
  283. Presence subscription = new Presence(Presence.Type.subscribe);
  284. subscription.setTo(userName + "@" + xmppConnection.getServiceName());
  285. xmppConnection.sendPacket(subscription);
  286. }
  287. //同意添加好友并添加对方为好友
  288. public static void agreeAdd(String from) {
  289. if (!canDo())
  290. return;
  291. Presence reSubscription = new Presence(Presence.Type.subscribe);
  292. reSubscription.setTo(from);
  293. xmppConnection.sendPacket(reSubscription);
  294. }
  295. //获取好友状态
  296. public int IsUserOnLine(String user) {
  297. String url = "http://" + SERVER_HOST + ":9090/plugins/presence/status?" +
  298. "jid=" + user + "@" + SERVER_NAME + "&type=xml";
  299. // System.out.println(url);
  300. int shOnLineState = 0; // 不存在
  301. try {
  302. URL oUrl = new URL(url);
  303. URLConnection oConn = oUrl.openConnection();
  304. if (oConn != null) {
  305. BufferedReader oIn = new BufferedReader(new InputStreamReader(
  306. oConn.getInputStream()));
  307. if (null != oIn) {
  308. String strFlag = oIn.readLine();
  309. oIn.close();
  310. System.out.println("strFlag" + strFlag);
  311. if (strFlag.indexOf("type=\"unavailable\"") >= 0) {
  312. shOnLineState = 2;
  313. }
  314. if (strFlag.indexOf("type=\"error\"") >= 0) {
  315. shOnLineState = 0;
  316. } else if (strFlag.indexOf("priority") >= 0
  317. || strFlag.indexOf("id=\"") >= 0) {
  318. shOnLineState = 1;
  319. }
  320. }
  321. }
  322. } catch (Exception e) {
  323. e.printStackTrace();
  324. }
  325. return shOnLineState;
  326. }
  327. //设置昵称
  328. public static void setNickName(String nickName) {
  329. VCard vCard1 = new VCard();
  330. vCard1.setNickName(nickName);
  331. try {
  332. vCard1.save(xmppConnection);
  333. } catch (XMPPException e) {
  334. e.printStackTrace();
  335. }
  336. }
  337. //获取昵称
  338. public static String getNickName(String name) {
  339. if (!canDo())
  340. return null;
  341. VCard vCard = new VCard();
  342. try {
  343. vCard.load(xmppConnection, name + SERVER_HOST);
  344. } catch (XMPPException e) {
  345. e.printStackTrace();
  346. return null;
  347. }
  348. return vCard.getNickName();
  349. }
  350. //获取用户头像
  351. public static byte[] getUserImage(String user) {
  352. if (!canDo()) {
  353. return null;
  354. }
  355. ByteArrayInputStream bais = null;
  356. try {
  357. VCard vcard = new VCard();
  358. // 加入这句代码,解决No VCard for
  359. ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp",
  360. new org.jivesoftware.smackx.provider.VCardProvider());
  361. vcard.load(xmppConnection, user + "@" + xmppConnection.getServiceName());
  362. if (vcard == null || vcard.getAvatar() == null)
  363. return null;
  364. bais = new ByteArrayInputStream(vcard.getAvatar());
  365. } catch (Exception e) {
  366. e.printStackTrace();
  367. }
  368. if (bais == null)
  369. return null;
  370. Drawable drawable = FormatTools.getInstance().InputStream2Drawable(bais);
  371. return getPicture(drawable);
  372. }
  373. //修改用户头像
  374. public static boolean changeImage(File file) {
  375. if (!canDo())
  376. return false;
  377. try {
  378. VCard vcard = new VCard();
  379. vcard.load(xmppConnection);
  380. byte[] bytes;
  381. bytes = File2Bytes.getFileBytes(file);
  382. String encodedImage = StringUtils.encodeBase64(bytes);
  383. vcard.setAvatar(bytes);
  384. vcard.setEncodedImage(encodedImage);
  385. vcard.setField("PHOTO", "<TYPE>image/jpg</TYPE><BINVAL>"
  386. + encodedImage + "</BINVAL>", true);
  387. ByteArrayInputStream bais = new ByteArrayInputStream(
  388. vcard.getAvatar());
  389. vcard.save(xmppConnection);
  390. return true;
  391. } catch (Exception e) {
  392. e.printStackTrace();
  393. return false;
  394. }
  395. }
  396. //修改用户头像
  397. public static boolean changeImage(byte[] bytes) {
  398. if (!canDo())
  399. return false;
  400. try {
  401. VCard vcard = new VCard();
  402. vcard.load(xmppConnection);
  403. String encodedImage = StringUtils.encodeBase64(bytes);
  404. vcard.setAvatar(bytes);
  405. vcard.setEncodedImage(encodedImage);
  406. vcard.setField("PHOTO", "<TYPE>image/jpg</TYPE><BINVAL>"
  407. + encodedImage + "</BINVAL>", true);
  408. ByteArrayInputStream bais = new ByteArrayInputStream(
  409. vcard.getAvatar());
  410. vcard.save(xmppConnection);
  411. return true;
  412. } catch (Exception e) {
  413. e.printStackTrace();
  414. return false;
  415. }
  416. }
  417. //删除好友
  418. public static boolean removeUser(String userName) {
  419. try {
  420. RosterEntry entry;
  421. if (userName.contains("@"))
  422. entry = xmppConnection.getRoster().getEntry(userName);
  423. else
  424. entry = xmppConnection.getRoster().getEntry(
  425. userName + "@" + xmppConnection.getServiceName());
  426. if (entry == null)
  427. entry = xmppConnection.getRoster().getEntry(userName);
  428. xmppConnection.getRoster().removeEntry(entry);
  429. return true;
  430. } catch (Exception e) {
  431. e.printStackTrace();
  432. return false;
  433. }
  434. }
  435. //获取好友列表
  436. public static List<RosterEntry> getAllEntries() {
  437. if (!canDo())
  438. return null;
  439. Roster roster = xmppConnection.getRoster();
  440. List<RosterEntry> Entrieslist = new ArrayList<RosterEntry>();
  441. Collection<RosterEntry> rosterEntry = roster.getEntries();
  442. Iterator<RosterEntry> i = rosterEntry.iterator();
  443. while (i.hasNext()) {
  444. Entrieslist.add(i.next());
  445. }
  446. return Entrieslist;
  447. }
  448. private static List<Group> groups;
  449. public static List<Group> getMyGroups() {
  450. return groups;
  451. }
  452. public static void setMyGroups(List<Group> groups) {
  453. UserInfo.groups = groups;
  454. }
  455. public static void addGroup(Group group) {
  456. if (!groups.contains(group)) groups.add(group);
  457. }
  458. public static void deleteGroup(Group group) {
  459. if (groups.contains(group))
  460. groups.remove(group);
  461. }
  462. public static String getName() {
  463. return name;
  464. }
  465. public static String getId() {
  466. return id;
  467. }
  468. public static XMPPConnection getXmppConnection() {
  469. return xmppConnection;
  470. }
  471. public static String getGroupName() {
  472. return groupName;
  473. }
  474. //将drawable转换成可以用来存储的byte[]类型
  475. public static byte[] getPicture(Drawable drawable) {
  476. if (drawable == null) {
  477. return null;
  478. }
  479. BitmapDrawable bd = (BitmapDrawable) drawable;
  480. Bitmap bitmap = bd.getBitmap();
  481. ByteArrayOutputStream os = new ByteArrayOutputStream();
  482. bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
  483. return os.toByteArray();
  484. }
  485. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注