Android即时智能聊天软件

      本项目主要实现的是即时智能聊天的功能,主要用的是图灵机器人作为服务端网站,对客户端发送的信息进行处理以及回复,其效果如下图所示(由于资源是网上找的卡通形象,故整体效果比较的卡通):若有需要代码的可以去http://download.csdn.net/detail/q394895302/9104417下载(编码方式UTF-8),有问题的地方请指出,共同学习。



该项目应用于Android 4.0以上版本,主要目的是为了熟悉Android 常用UI控件,网络链接,以及用消息处理机制实现客户端与服务端的通讯。

     其部分代码如下:


    此部分代码主要是为了链接服务端即图灵智能机器人

<span style="font-size:18px;"><span style="font-size:18px;">/**
	 * 发送一个消息,并得到返回的消息
	 * 
	 * @param msg
	 * @return
	 */
	public static ChatMessgeBean sendMsg(String msg) {
		ChatMessgeBean message = new ChatMessgeBean();
		String url = setParams(msg);
		String res = doGet(url);
		Gson gson = new Gson();
		Result result = gson.fromJson(res, Result.class);

		if (result.getCode() > 400000 || result.getText() == null
				|| result.getText().trim().equals("")) {
			message.setMsg("该功能等待开发...");
		} else {
			message.setMsg(result.getText());
		}
		message.setType(Type.INPUT);
		message.setDate(new Date());

		return message;
	}

	/**
	 * 拼接Url
	 * 
	 * @param msg
	 * @return
	 */
	private static String setParams(String msg) {
		try {
			msg = URLEncoder.encode(msg, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return URL + "?key=" + API_KEY + "&info=" + msg;
	}

	/**
	 * Get请求,获得返回数据
	 * 
	 * @param urlStr
	 * @return
	 */
	private static String doGet(String urlStr) {
		URL url = null;
		HttpURLConnection conn = null;
		InputStream is = null;
		ByteArrayOutputStream baos = null;
		try {
			url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(5 * 1000);
			conn.setConnectTimeout(5 * 1000);
			conn.setRequestMethod("GET");
			if (conn.getResponseCode() == 200) {
				is = conn.getInputStream();
				baos = new ByteArrayOutputStream();
				int len = -1;
				byte[] buf = new byte[128];

				while ((len = is.read(buf)) != -1) {
					baos.write(buf, 0, len);
				}
				baos.flush();
				return baos.toString();
			} else {
				throw new CommonException("服务器连接错误!");
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new CommonException("服务器连接错误!");
		} finally {
			try {
				if (is != null)
					is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			try {
				if (baos != null)
					baos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			conn.disconnect();
		}

	}</span></span>

      该部分代码就是主要的聊天实现的主体部分:

<span style="font-size:18px;"><span style="font-size:18px;">private ListView mMsgList;// 展示消息的listview

	private EditText mSendMsgEdit;// 文本域

	private List<ChatMessgeBean> mList = new ArrayList<ChatMessgeBean>();// 存储聊天消息

	private ChatMessgeBeanAdapter mAdapter;// 适配器

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			ChatMessgeBean from = (ChatMessgeBean) msg.obj;
			mList.add(from);
			mAdapter.notifyDataSetChanged();
			mMsgList.setSelection(mList.size() - 1);
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_chatting);

		initView();

		mAdapter = new ChatMessgeBeanAdapter(this, mList);
		mMsgList.setAdapter(mAdapter);

	}

	private void initView() {
		mMsgList = (ListView) findViewById(R.id.chat_listView);
		mSendMsgEdit = (EditText) findViewById(R.id.chat_send_msg_edit);
		mList.add(new ChatMessgeBean(ChatMessgeBean.Type.INPUT,
				"我是潴潴壞寶唄,很高兴为您服务"));
	}

	public void sendMessage(View view) {
		final String msg = mSendMsgEdit.getText().toString();
		if (TextUtils.isEmpty(msg)) {
			Toast.makeText(this, "您还没有填写信息呢...", Toast.LENGTH_SHORT).show();
			return;
		}

		ChatMessgeBean to = new ChatMessgeBean(Type.OUTPUT, msg);
		to.setDate(new Date());
		mList.add(to);

		mAdapter.notifyDataSetChanged();
		mMsgList.setSelection(mList.size() - 1);

		mSendMsgEdit.setText("");

		// 关闭软键盘
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		// 得到InputMethodManager的实例
		if (imm.isActive()) {
			// 如果开启
			imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
					InputMethodManager.HIDE_NOT_ALWAYS);
			// 关闭软键盘,开启方法相同,这个方法是切换开启与关闭状态的
		}

		new Thread() {
			public void run() {
				ChatMessgeBean from = null;
				try {
					from = HttpConnectionUntil.sendMsg(msg);
				} catch (Exception e) {
					from = new ChatMessgeBean(Type.INPUT, "服务器挂了呢...");
				}
				Message message = Message.obtain();
				message.obj = from;
				mHandler.sendMessage(message);
			};
		}.start();

	}

	/**
	 * 自定义适配器
	 */
	class ChatMessgeBeanAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private List<ChatMessgeBean> mDatas;

		public ChatMessgeBeanAdapter(Context context, List<ChatMessgeBean> datas) {
			mInflater = LayoutInflater.from(context);
			mDatas = datas;
		}

		@Override
		public int getCount() {
			return mDatas.size();
		}

		@Override
		public Object getItem(int position) {
			return mDatas.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		/**
		 * 接受到消息为1,发送消息为0
		 */
		@Override
		public int getItemViewType(int position) {
			ChatMessgeBean msg = mDatas.get(position);
			return msg.getType() == Type.INPUT ? 1 : 0;
		}

		@Override
		public int getViewTypeCount() {
			return 2;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ChatMessgeBean ChatMessgeBean = mDatas.get(position);

			ViewHolder viewHolder = null;

			if (convertView == null) {
				viewHolder = new ViewHolder();
				if (ChatMessgeBean.getType() == Type.INPUT) {
					convertView = mInflater.inflate(
							R.layout.activity_chat_from_msg, parent, false);
					viewHolder.createDate = (TextView) convertView
							.findViewById(R.id.chat_from_createDate);
					viewHolder.content = (TextView) convertView
							.findViewById(R.id.chat_from_content);
					convertView.setTag(viewHolder);
				} else {
					convertView = mInflater.inflate(
							R.layout.activity_chat_send_msg, null);

					viewHolder.createDate = (TextView) convertView
							.findViewById(R.id.chat_send_createDate);
					viewHolder.content = (TextView) convertView
							.findViewById(R.id.chat_send_content);
					convertView.setTag(viewHolder);
				}

			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}

			viewHolder.content.setText(ChatMessgeBean.getMsg());
			viewHolder.createDate.setText(ChatMessgeBean.getDateStr());

			return convertView;
		}
</span></span>

    上述的练习主要是实现线程间的通讯以及网络连接,对Android的UI控件的使用;实现客户端与服务端的即时通讯,故没有对聊天的内容进行保存,退出聊天界面后再次进入时之前的内容将不会被保存。由于主要是为了实现聊天功能,故登录界面的信息是被设置好的,点击记住密码是将会实现自动登录,下次打开应用时将直接进入主界面,跳过登录界面和引导界面。上述的界面中对于More更多里面的功能没有实现,只是为了对界面进行包装,使其不显得太单调所以。


你可能感兴趣的:(Android即时智能聊天软件)