1,首先自己下載工具,搭建一個(gè)Android開(kāi)發(fā)環(huán)境,去百度一下(安卓開(kāi)發(fā)環(huán)境搭建),有詳細(xì)步驟。
2,百度搜索“圖靈機(jī)器人”,去注冊(cè)一個(gè)賬號(hào),獲取apikey,用來(lái)調(diào)用圖靈機(jī)器人的數(shù)據(jù)。
- 2
把APIkey復(fù)制下來(lái)放在一個(gè)記事本,之后要在代碼中用的。
- 3
先新建一個(gè)Android工程,我的工程名為:Person,源代碼在com.shenbin.person包下,MainActivity是Android的activity。
還包括HttpDate類,HttpGetDateListener類,ListDate類,TextAdapter類
//MainActivity代碼:
/*下面的代碼修改
httpDate=(HttpDate)newHttpDate("http://www.tuling123.com/openapi/api?key=********&info="+droph,this).execute();
把********替換成自己的APIkey
*/
packagecom.shenbin.person;
importjava.text.SimpleDateFormat;importjava.util.ArrayList;importjava.util.Date;importjava.util.List;
importorg.json.JSONException;importorg.json.JSONObject;
importandroid.os.Bundle;importandroid.app.Activity;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.ListView;
publicclassMainActivityextendsActivityimplementsHttpGetDateListener,OnClickListener{//實(shí)現(xiàn)接口
privateHttpDatehttpDate;privateList<ListDate>lists;privateListViewlv;privateEditTextgetText;privateButtonsend_btn;privateStringcontent_str;privateTextAdapteradapter;privateString[]welcome_array;privatedoublecurrentTime,oldTime=0;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();//httpDate=(HttpDate)newHttpDate("http://www.tuling123.com/openapi/api?key=5692c0d167fc5a180d092efaab578617&info=你好",//this).execute();}
privatevoidinitView(){lv=(ListView)findViewById(R.id.lv);getText=(EditText)findViewById(R.id.sendText);send_btn=(Button)findViewById(R.id.send_btn);//send_btn.setOnClickListener((android.view.View.OnClickListener)this);send_btn.setOnClickListener(this);lists=newArrayList<ListDate>();adapter=newTextAdapter(lists,this);lv.setAdapter(adapter);ListDatelistDate=null;listDate=newListDate(getRandomWelcomeTips(),listDate.RECEIVER,getTime());lists.add(listDate);
}privateStringgetRandomWelcomeTips(){Stringwelcome_tip=null;welcome_array=this.getResources().getStringArray(R.array.welcome_tips);//獲得string。xml的歡迎語(yǔ)intindex=(int)(Math.random()*(welcome_array.length-1));welcome_tip=welcome_array[index];returnwelcome_tip;}@OverridepublicvoidgetDateUrl(Stringdate){//TODO自動(dòng)生成的方法存根//System.out.println(date);parseText(date);}publicvoidparseText(Stringstr){try{JSONObjectjb=newJSONObject(str);//System.out.println(jb.getString("code"));//System.out.println(jb.getString("text"));ListDatelistDate=null;listDate=newListDate(jb.getString("text"),listDate.RECEIVER,getTime());lists.add(listDate);adapter.notifyDataSetChanged();}catch(JSONExceptione){//TODO自動(dòng)生成的catch塊e.printStackTrace();}}
@OverridepublicvoidonClick(Viewv){getTime();content_str=getText.getText().toString();getText.setText("");Stringdropk=content_str.replace("","");Stringdroph=dropk.replace("\n","");ListDatelistDate;listDate=newListDate(content_str,ListDate.SEND,getTime());lists.add(listDate);//如果太多了,就移除一些if(lists.size()>30){for(inti=0;i<lists.size();i++){lists.remove(i);}}adapter.notifyDataSetChanged();httpDate=(HttpDate)newHttpDate("http://www.tuling123.com/openapi/api?key=********&info="+droph,this).execute();
}privateStringgetTime(){currentTime=System.currentTimeMillis();SimpleDateFormatformat=newSimpleDateFormat("yyyy年MM月dd日HH:mm:ss");DatecurDate=newDate();Stringstr=format.format(curDate);if(currentTime-oldTime>5*60*1000){oldTime=currentTime;returnstr;}else{return"";}}
}
//HttpDate類代碼
packagecom.shenbin.person;
importjava.io.BufferedReader;importjava.io.InputStream;importjava.io.InputStreamReader;
importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.client.HttpClient;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.impl.client.DefaultHttpClient;importandroid.os.AsyncTask;
publicclassHttpDateextendsAsyncTask<String,Void,String>{privateHttpClientmHttpClient;//客戶端privateHttpGetmHttpGet;//請(qǐng)求方式為getprivateStringurl;//請(qǐng)求的地址privateHttpResponsemHttpResponse;//請(qǐng)求返還privateHttpEntitymHttpEntity;//創(chuàng)建實(shí)體privateInputStreamin;privateHttpGetDateListenerlistener;//獲得接口
publicHttpDate(Stringurl,HttpGetDateListenerlistener){this.url=url;this.listener=listener;}@OverrideprotectedStringdoInBackground(String...arg0){//TODO自動(dòng)生成的方法存根try{mHttpClient=newDefaultHttpClient();//實(shí)例化客戶端mHttpGet=newHttpGet(url);mHttpResponse=mHttpClient.execute(mHttpGet);mHttpEntity=mHttpResponse.getEntity();in=mHttpEntity.getContent();BufferedReaderbr=newBufferedReader(newInputStreamReader(in));Stringline=null;//獲取數(shù)據(jù)StringBuffersb=newStringBuffer();while((line=br.readLine())!=null){sb.append(line);}returnsb.toString();}catch(Exceptione){//TODO:handleexception}returnnull;}@OverrideprotectedvoidonPostExecute(Stringresult){//TODO自動(dòng)生成的方法存根listener.getDateUrl(result);super.onPostExecute(result);}
}
//HttpGetDateListener類代碼
//接口
packagecom.shenbin.person;
publicinterfaceHttpGetDateListener{
voidgetDateUrl(Stringdate);}
//ListDate類代碼
packagecom.shenbin.person;
importandroid.R.integer;
publicclassListDate{privateStringcontent;publicstaticfinalintSEND=1;publicstaticfinalintRECEIVER=2;privateintflag;privateStringtime;publicListDate(Stringcontent,intflag,Stringtime){//TODO自動(dòng)生成的構(gòu)造函數(shù)存根setContent(content);setFlag(flag);setTime(time);}publicvoidsetContent(Stringcontent){this.content=content;}
publicStringgetContent(){returncontent;}
publicintgetFlag(){returnflag;}
publicvoidsetFlag(intflag){this.flag=flag;}
publicStringgetTime(){returntime;}
publicvoidsetTime(Stringtime){this.time=time;}
}
//TextAdapter類代碼
packagecom.shenbin.person;
importjava.net.ContentHandler;importjava.util.List;
importjavax.security.auth.PrivateCredentialPermission;
importandroid.R.layout;importandroid.content.Context;importandroid.view.LayoutInflater;importandroid.view.View;importandroid.view.ViewGroup;importandroid.webkit.WebView.FindListener;importandroid.widget.BaseAdapter;importandroid.widget.RelativeLayout;importandroid.widget.TextView;
publicclassTextAdapterextendsBaseAdapter{privateList<ListDate>lists;privateContextnContext;privateRelativeLayoutlayout;publicTextAdapter(List<ListDate>lists,ContextnContext){this.lists=lists;this.nContext=nContext;}
@OverridepublicintgetCount(){//TODO自動(dòng)生成的方法存根returnlists.size();}
@OverridepublicObjectgetItem(intpesition){returnlists.get(pesition);}
@OverridepubliclonggetItemId(intpesition){//TODO自動(dòng)生成的方法存根returnpesition;}
@OverridepublicViewgetView(intpesition,ViewconverView,ViewGroupparent){LayoutInflaterinflater=LayoutInflater.from(nContext);if(lists.get(pesition).getFlag()==ListDate.RECEIVER){layout=(RelativeLayout)inflater.inflate(R.layout.leftitem,null);}if(lists.get(pesition).getFlag()==ListDate.SEND){layout=(RelativeLayout)inflater.inflate(R.layout.rightitem,null);}TextViewtv=(TextView)layout.findViewById(R.id.tv);tv.setText(lists.get(pesition).getContent());TextViewtime=(TextView)layout.findViewById(R.id.time);time.setText(lists.get(pesition).getTime());returnlayout;}
}
activity_main.xml的代碼:
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context=".MainActivity">
<ListViewandroid: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"></ListView><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"><EditTextandroid:id="@+id/sendText"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"/><Buttonandroid:id="@+id/send_btn"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/send"/></LinearLayout>
</LinearLayout>
leftitem.xml代碼
<?xmlversion="1.0"encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:id="@+id/time"android:layout_width="fill_parent"android:gravity="center_horizontal"android:layout_height="wrap_content"/><ImageViewandroid:layout_below="@id/time"android:id="@+id/iv"android:layout_width="70dp"android:layout_height="70dp"android:padding="10dp"android:src="@drawable/c"/><TextViewandroid:layout_below="@id/time"android:layout_toRightOf="@id/iv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/tv"android:gravity="center"android:background="@drawable/d"/>
</RelativeLayout>
rightitem.xml代碼
<?xmlversion="1.0"encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:id="@+id/time"android:layout_width="fill_parent"android:gravity="center_horizontal"android:layout_height="wrap_content"/><ImageViewandroid:layout_below="@id/time"android:layout_alignParentRight="true"android:id="@+id/iv"android:layout_width="70dp"android:layout_height="70dp"android:padding="10dp"android:src="@drawable/b"/><TextViewandroid:layout_below="@id/time"android:layout_toLeftOf="@id/iv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/tv"android:gravity="center"android:background="@drawable/d"/>
</RelativeLayout>
values文件下的strings.xml代碼
<?xmlversion="1.0"encoding="utf-8"?><resources>
<stringname="app_name">小兵機(jī)器人</string><stringname="action_settings">Settings</string><stringname="hello_world">小兵聊天機(jī)器人</string><stringname="send">發(fā)送</string><string-arrayname="welcome_tips"><item>主人,奴婢在此等候多時(shí)了</item><item>主人,近來(lái)可好</item><item>歡迎歸來(lái),我親愛(ài)的主人</item><item>主人,我好想你啊</item><item>主人,你越來(lái)越靚啦</item><item>我是小兵機(jī)器人,很高興陪你聊天</item><item>我就是聰明,可愛(ài)的小兵機(jī)器人</item><item>hello,美女(帥鍋)</item><item>你是我的小呀小蘋果</item><item>開(kāi)心的話,可以找我聊天,不開(kāi)心更要找我聊天啦</item></string-array>
</resources>
AndroidManifest.xml的代碼
添加的代碼為加黑的粗體。
<?xmlversion="1.0"encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"package="com.shenbin.person"android:versionCode="1"android:versionName="1.0">
<uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="18"/><uses-permissionandroid:name="android.permission.INTERNET"/>
<applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme"><activityandroid:name="com.shenbin.person.MainActivity"android:label="@string/app_name"><intent-filter><actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/></intent-filter></activity>
網(wǎng)站導(dǎo)航
- zblogPHP模板zbpkf
- zblog免費(fèi)模板zblogfree
- zblog模板學(xué)習(xí)zblogxuexi
- zblogPHP仿站zbpfang