http://www.tuling123.com/ 注册一个账号,申请一个KEY值。此网站也有文档,可以查看。
package com.tulingdemo; import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import com.tulingdemo.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView; public class MainActivity extends Activity implements HttpGetDataListener,
OnClickListener { private HttpData httpData;
private List<ListData> lists;
private ListView lv;
private EditText sendtext;
private Button send_btn;
private String content_str;
private TextAdapter adapter;
private String[] welcome_array;
// 做比对时间;老时间
private double currentTime = 0, oldTime = 0; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
} private void initView() {
lv = (ListView) findViewById(R.id.lv);
sendtext = (EditText) findViewById(R.id.sendText);
send_btn = (Button) findViewById(R.id.send_btn);
lists = new ArrayList<ListData>();
send_btn.setOnClickListener(this);
adapter = new TextAdapter(lists, this);
lv.setAdapter(adapter);
ListData listData;
listData = new ListData(getRandomWelcomeTips(), ListData.RECEIVER,
getTime());
lists.add(listData);
} /** 用户第一次进入,随机获取欢迎语 */
private String getRandomWelcomeTips() {
String welcome_tip = null;
welcome_array = this.getResources()
.getStringArray(R.array.welcome_tips);
int index = (int) (Math.random() * (welcome_array.length - 1));
welcome_tip = welcome_array[index];
return welcome_tip;
} @Override
public void getDataUrl(String data) {
parseText(data);
} public void parseText(String str) {
try {
JSONObject jb = new JSONObject(str);
// System.out.println(jb.getString("code"));
// System.out.println(jb.getString("text"));
ListData listData;
listData = new ListData(jb.getString("text"), ListData.RECEIVER,
getTime());
lists.add(listData);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
} @Override
public void onClick(View v) {
getTime();
content_str = sendtext.getText().toString();
sendtext.setText("");
// 去掉空格
String dropk = content_str.replace(" ", "");
// 去掉回车
String droph = dropk.replace("\n", "");
ListData listData;
listData = new ListData(content_str, ListData.SEND, getTime());
lists.add(listData);
if (lists.size() > 30) {
for (int i = 0; i < lists.size(); i++) {
// 移除数据
lists.remove(i);
}
}
adapter.notifyDataSetChanged();
httpData = (HttpData) new HttpData(
"http://www.tuling123.com/openapi/api?key=6af9822f5491fadfc142b53818bbd63a&info="
+ droph, this).execute();
} /** 获取时间 */
private String getTime() {
currentTime = System.currentTimeMillis();
SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date curDate = new Date();
String str = format.format(curDate);
// 如果超过5分钟.
if (currentTime - oldTime >= 5 * 60 * 1000) {
oldTime = currentTime;
return str;
} else {
return "";
} }
}
activity_main.xml
<LinearLayout 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:orientation="vertical" > <!--
android:transcriptMode="alwaysScroll" 自动向下一直滚动。
-->
<ListView
android:id="@+id/lv"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:divider="@null"
android:listSelector="@android:color/transparent"
android:transcriptMode="alwaysScroll" /> <LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" > <EditText
android:id="@+id/sendText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" /> <Button
android:id="@+id/send_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send" />
</LinearLayout> </LinearLayout>
package com.tulingdemo; import java.util.List;
import com.tulingdemo.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView; public class TextAdapter extends BaseAdapter { private List<ListData> lists;
private Context mContext;
private RelativeLayout layout; public TextAdapter(List<ListData> lists, Context mContext) {
this.lists = lists;
this.mContext = mContext;
} @Override
public int getCount() {
return lists.size();
} @Override
public Object getItem(int position) {
return lists.get(position);
} @Override
public long getItemId(int position) {
return position;
} @Override
public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(mContext); if (lists.get(position).getFlag() == ListData.RECEIVER) {
layout = (RelativeLayout) inflater.inflate(R.layout.leftitem, null);
}
if (lists.get(position).getFlag() == ListData.SEND) {
layout = (RelativeLayout) inflater
.inflate(R.layout.rightitem, null);
}
TextView tv = (TextView) layout.findViewById(R.id.tv);
TextView time = (TextView) layout.findViewById(R.id.time);
tv.setText(lists.get(position).getContent());
time.setText(lists.get(position).getTime());
return layout;
} }
leftitem.xml 接受信息
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" > <TextView
android:id="@+id/time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal" /> <ImageView
android:id="@+id/iv"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_below="@id/time"
android:padding="10dp"
android:src="@drawable/robot" /> <TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/time"
android:layout_marginRight="50dp"
android:layout_toRightOf="@id/iv"
android:background="@drawable/aio_friend_bg_nor_11"
android:gravity="center" /> </RelativeLayout>
rightitem.xml 发送信息
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" > <TextView
android:id="@+id/time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal" /> <ImageView
android:id="@+id/iv"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentRight="true"
android:layout_below="@id/time"
android:padding="10dp"
android:src="@drawable/visitor" /> <TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/time"
android:layout_marginLeft="50dp"
android:layout_toLeftOf="@id/iv"
android:background="@drawable/aio_user_bg_nor_11"
android:gravity="center" /> </RelativeLayout>
package com.tulingdemo; import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask; public class HttpData extends AsyncTask<String, Void, String>{ private HttpClient mHttpClient;
private HttpGet mHttpGet;
private HttpResponse mHttpResponse;
private HttpEntity mHttpEntity;
private InputStream in;
private HttpGetDataListener listener; private String url;
public HttpData(String url,HttpGetDataListener listener) {
this.url = url;
this.listener = listener;
} @Override
protected String doInBackground(String... params) {
try {
mHttpClient = new DefaultHttpClient();
mHttpGet = new HttpGet(url);
mHttpResponse = mHttpClient.execute(mHttpGet);
mHttpEntity = mHttpResponse.getEntity();
in = mHttpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
}
return null;
}
@Override
protected void onPostExecute(String result) {
listener.getDataUrl(result);
super.onPostExecute(result);
}
}
package com.tulingdemo; public interface HttpGetDataListener {
void getDataUrl(String data);
}
package com.tulingdemo; public class ListData { public static final int SEND = 1; // 发送
public static final int RECEIVER = 2; // 接收
private String content;
// 标识,判断是左边,还是右边。
private int flag;
private String time; public ListData(String content,int flag,String time) {
setContent(content);
setFlag(flag);
setTime(time);
} public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources> <string name="app_name">小灵机器人</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="send">发送</string> <!-- 欢迎语 -->
<string-array name="welcome_tips">
<item>主人,奴婢在此等候多时了</item>
<item>主人,近来一切可好</item>
<item>亲爱的,我想死你了</item>
<item>欢迎归来,我亲爱的主人</item>
<item>我是小灵机器人,很高兴为您服务</item>
</string-array> </resources>
完整代码下载:http://pan.baidu.com/s/1pJJR8JD