//mainActivity
package com.example.duihua;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.zzy.bean.ChatMessage;
import com.zzy.bean.ChatMessage.Type;
import com.zzy.utils.HttpUtils;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ListView mMsgs;
private ChatMessageAdapter mAdapter;
private List<ChatMessage> mDatas;
private EditText mInputMsg;
private Button mSendMsg;
private Handler mHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
//等待接受子线程完成数据的返回
ChatMessage fromMessage = (ChatMessage) msg.obj;
mDatas.add(fromMessage);
mAdapter.notifyDataSetChanged();
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initView();
initDatas();
//初始化事件
initListener();
}
private void initListener() {
mSendMsg.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final String toMsg = mInputMsg.getText().toString();
if(TextUtils.isEmpty(toMsg)){
Toast.makeText(MainActivity.this, "发送消息不能为空", 0).show();
return;
}
ChatMessage toMessage = new ChatMessage();
toMessage.setDate(new Date());
toMessage.setMsg(toMsg);
toMessage.setType(Type.OUTCOMING);
mDatas.add(toMessage);
mAdapter.notifyDataSetChanged();
mInputMsg.setText("");
new Thread(){
public void run() {
ChatMessage fromMessage = HttpUtils.sendMessage(toMsg);
Message m = Message.obtain();
m.obj = fromMessage;
mHandler.sendMessage(m);
};
}.start();
}
});
}
private void initDatas() {
mDatas = new ArrayList<ChatMessage>();
mDatas.add(new ChatMessage("你好,仔仔为您服务",Type.INCOMING,new Date()));
// mDatas.add(new ChatMessage("你好",Type.OUTCOMING,new Date()));
mAdapter = new ChatMessageAdapter(this, mDatas);
mMsgs.setAdapter(mAdapter);
}
private void initView() {
mMsgs = (ListView) findViewById(R.id.id_listview_msgs);
mInputMsg = (EditText) findViewById(R.id.id_input_msg);
mSendMsg = (Button) findViewById(R.id.id_send_msg);
}
}
//HttpUtil
package com.zzy.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Date;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.zzy.bean.ChatMessage;
import com.zzy.bean.ChatMessage.Type;
import com.zzy.bean.Result;
public class HttpUtils {
private static final String URL = "http://www.tuling123.com/openapi/api";
private static final String API_KEY = "dc636b36e89235f004fe375a0ad3df69";
// 534dc342ad15885dffc10d7b5f81
/*
* 发送一个消息。得到返回的消息
*/
public static ChatMessage sendMessage(String msg){
ChatMessage chatMessage = new ChatMessage();
String jsonRes = doGet(msg);
Gson gson = new Gson();
Result result = null;
try {
result = gson.fromJson(jsonRes, Result.class);
chatMessage.setMsg(result.getText());
} catch (JsonSyntaxException e) {
chatMessage.setMsg("服务器繁忙,请稍后再试");
}
chatMessage.setDate(new Date());
chatMessage.setType(Type.INCOMING);
return chatMessage;
}
public static String doGet(String msg){
String result = "";
String url = setParams(msg);
InputStream is = null;
ByteArrayOutputStream baos = null;
java.net.URL urlNet = null;
try {
urlNet = new java.net.URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection conn;
try {
conn = (HttpURLConnection) urlNet.openConnection();
conn.setReadTimeout(5*1000);
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("GET");
is = conn.getInputStream();
int len = -1;
byte[] buf = new byte[128];
baos = new ByteArrayOutputStream();
while((len = is.read(buf))!=-1){
baos.write(buf,0,len);
}
baos.flush();
result = new String(baos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}finally{
if(baos!=null){
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null){
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
private static String setParams(String msg) {
String url = "";
try {
url = URL + "?key="+API_KEY+"&info="+URLEncoder.encode(msg,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return url;
}
}
//TestHttpUtils
package com.zzy.test;
import android.test.AndroidTestCase;
import android.util.Log;
import com.zzy.utils.HttpUtils;
public class TestHttpUtils extends AndroidTestCase{
public void testSendInfo(){
String res = HttpUtils.doGet("给我讲个笑话");
Log.i("TAG", res);
res = HttpUtils.doGet("给我讲个鬼故事");
Log.i("TAG", res);
res = HttpUtils.doGet("你好");
Log.i("TAG", res);
res = HttpUtils.doGet("你真美");
Log.i("TAG", res);
}
}
//bean
package com.zzy.bean;
public class Result {
private int code;
private String text;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
package com.zzy.bean;
import java.util.Date;
public class ChatMessage {
private String name;
private String msg;
private Type type;
private Date date;
public ChatMessage() {
super();
// TODO Auto-generated constructor stub
}
public ChatMessage(String msg, Type type, Date date) {
super();
this.msg = msg;
this.type = type;
this.date = date;
}
public enum Type{
INCOMING,OUTCOMING
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
//ChatMessageAdapter
package com.example.duihua;
import java.text.SimpleDateFormat;
import java.util.List;
import com.zzy.bean.ChatMessage;
import com.zzy.bean.ChatMessage.Type;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ChatMessageAdapter extends BaseAdapter{
private LayoutInflater mInflater;
private List<ChatMessage> mDatas;
public ChatMessageAdapter(Context context,List<ChatMessage> mDatas) {
mInflater = LayoutInflater.from(context);
this.mDatas = mDatas;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mDatas.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mDatas.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public int getItemViewType(int position) {
ChatMessage chatMessage = mDatas.get(position);
if(chatMessage.getType() == Type.INCOMING){
return 0;
}
return 1;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ChatMessage chatMessage = mDatas.get(position);
ViewHolder vh = null;
if(convertView == null){
if(getItemViewType(position) == 0){
convertView = mInflater.inflate(R.layout.item_from_msg, parent,false);
vh = new ViewHolder();
vh.mData = (TextView) convertView.findViewById(R.id.id_from_msg_date);
vh.mMsg = (TextView) convertView.findViewById(R.id.id_from_msg_info);
}else{
convertView = mInflater.inflate(R.layout.item_to_msg, parent,false);
vh = new ViewHolder();
vh.mData = (TextView) convertView.findViewById(R.id.id_to_msg_date);
vh.mMsg = (TextView) convertView.findViewById(R.id.id_to_msg_info);
}
convertView.setTag(vh);
}else{
vh = (ViewHolder) convertView.getTag();
}
//设置数据
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
vh.mData.setText(df.format(chatMessage.getDate()));
vh.mMsg.setText(chatMessage.getMsg());
return convertView;
}
private final class ViewHolder{
TextView mData;
TextView mMsg;
}
}
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<instrumentation
android:targetPackage="com.example.duihua"
android:label="this is a test"
android:name="android.test.InstrumentationTestRunner">
</instrumentation>