回覆列表
  • 1 # 歷歷萬世

    1,首先自己下載工具,搭建一個Android開發環境,去百度一下(安卓開發環境搭建),有詳細步驟。

    2,百度搜索“圖靈機器人”,去註冊一個賬號,獲取api key,用來呼叫圖靈機器人的資料。

    2

    把API key 複製下來放在一個記事本,之後要在程式碼中用的。

    3

    先新建一個Android工程,我的工程名為:Person,原始碼在com.shenbin.person包下,MainActivity是Android的activity。

    還包括HttpDate類,HttpGetDateListener類,ListDate類,TextAdapter類

    //MainActivity程式碼:

    /*下面的程式碼修改

    httpDate = (HttpDate) new HttpDate("http://www.tuling123.com/openapi/api?key=********&info=" +droph,this).execute();

    把********替換成自己的API key

    */

    package com.shenbin.person;

    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 android.os.Bundle;import android.app.Activity;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 HttpGetDateListener,OnClickListener{ //實現介面

    private HttpDate httpDate; private List<ListDate> lists; private ListView lv; private EditText getText; private Button send_btn; private String content_str; private TextAdapter adapter; private String [] welcome_array; private double currentTime,oldTime = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); //httpDate = (HttpDate) new HttpDate("http://www.tuling123.com/openapi/api?key=5692c0d167fc5a180d092efaab578617&info=你好", //this).execute(); }

    private void initView() { 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 = new ArrayList<ListDate>(); adapter = new TextAdapter(lists, this); lv.setAdapter(adapter); ListDate listDate = null ; listDate = new ListDate(getRandomWelcomeTips(),listDate.RECEIVER,getTime()); lists.add(listDate);

    } private String getRandomWelcomeTips() { String welcome_tip = null; welcome_array = this.getResources().getStringArray(R.array.welcome_tips); //獲得string。xml的歡迎語 int index = (int) (Math.random()*(welcome_array.length-1)); welcome_tip = welcome_array[index]; return welcome_tip; } @Override public void getDateUrl(String date) { // TODO 自動生成的方法存根 //System.out.println(date); parseText(date); } public void parseText(String str) { try { JSONObject jb = new JSONObject(str); //System.out.println(jb.getString("code")); //System.out.println(jb.getString("text")); ListDate listDate = null; listDate = new ListDate(jb.getString("text"),listDate.RECEIVER,getTime()); lists.add(listDate); adapter.notifyDataSetChanged(); } catch (JSONException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } }

    @Override public void onClick(View v) { getTime(); content_str = getText.getText().toString(); getText.setText(""); String dropk = content_str.replace(" ", ""); String droph = dropk.replace("\n", ""); ListDate listDate; listDate = new ListDate(content_str,ListDate.SEND,getTime()); lists.add(listDate); //如果太多了,就移除一些 if (lists.size() > 30) { for (int i = 0; i < lists.size(); i++) { lists.remove(i); } } adapter.notifyDataSetChanged(); httpDate = (HttpDate) new HttpDate("http://www.tuling123.com/openapi/api?key=********&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); if (currentTime - oldTime > 5*60*1000) { oldTime = currentTime; return str; }else { return ""; } }

    }

    //HttpDate類程式碼

    package com.shenbin.person;

    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 HttpDate extends AsyncTask<String, Void, String>{ private HttpClient mHttpClient; //客戶端 private HttpGet mHttpGet; //請求方式為get private String url; //請求的地址 private HttpResponse mHttpResponse; //請求返還 private HttpEntity mHttpEntity; //建立實體 private InputStream in; private HttpGetDateListener listener; //獲得介面

    public HttpDate(String url,HttpGetDateListener listener) { this.url = url; this.listener = listener; } @Override protected String doInBackground(String... arg0) { // TODO 自動生成的方法存根 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) { // TODO: handle exception } return null; } @Override protected void onPostExecute(String result) { // TODO 自動生成的方法存根 listener.getDateUrl(result); super.onPostExecute(result); }

    }

    //HttpGetDateListener類程式碼

    //介面

    package com.shenbin.person;

    public interface HttpGetDateListener {

    void getDateUrl(String date);}

    //ListDate類程式碼

    package com.shenbin.person;

    import android.R.integer;

    public class ListDate { private String content; public static final int SEND = 1; public static final int RECEIVER = 2; private int flag; private String time; public ListDate(String content,int flag,String time) { // TODO 自動生成的建構函式存根 setContent(content); setFlag(flag); setTime(time); } public void setContent(String content) { this.content = content; }

    public String getContent() { return 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; }

    }

    //TextAdapter類程式碼

    package com.shenbin.person;

    import java.net.ContentHandler;import java.util.List;

    import javax.security.auth.PrivateCredentialPermission;

    import android.R.layout;import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.webkit.WebView.FindListener;import android.widget.BaseAdapter;import android.widget.RelativeLayout;import android.widget.TextView;

    public class TextAdapter extends BaseAdapter{ private List<ListDate> lists; private Context nContext; private RelativeLayout layout; public TextAdapter(List<ListDate> lists,Context nContext) { this.lists = lists; this.nContext = nContext; }

    @Override public int getCount() { // TODO 自動生成的方法存根 return lists.size(); }

    @Override public Object getItem(int pesition) { return lists.get(pesition); }

    @Override public long getItemId(int pesition) { // TODO 自動生成的方法存根 return pesition; }

    @Override public View getView(int pesition, View converView , ViewGroup parent) { LayoutInflater inflater = 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); } TextView tv = (TextView) layout.findViewById(R.id.tv); tv.setText(lists.get(pesition).getContent()); TextView time = (TextView) layout.findViewById(R.id.time); time.setText(lists.get(pesition).getTime()); return layout; }

    }

    activity_main.xml的程式碼:

    <LinearLayout xmlns: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" >

    <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" ></ListView> <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>

    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:gravity="center_horizontal" android:layout_height="wrap_content" /> <ImageView android:layout_below="@id/time" android:id="@+id/iv" android:layout_width="70dp" android:layout_height="70dp" android:padding="10dp" android:src="@drawable/c" /> <TextView android: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程式碼

    <?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:gravity="center_horizontal" android:layout_height="wrap_content" /> <ImageView android: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" /> <TextView android: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程式碼

    <?xml version="1.0" encoding="utf-8"?><resources>

    <string name="app_name">小兵機器人</string> <string name="action_settings">Settings</string> <string name="hello_world">小兵聊天機器人</string> <string name="send">傳送</string> <string-array name="welcome_tips"> <item>主人,奴婢在此等候多時了</item> <item>主人,近來可好</item> <item>歡迎歸來,我親愛的主人</item> <item>主人,我好想你啊</item> <item>主人,你越來越靚啦</item> <item>我是小兵機器人,很高興陪你聊天</item> <item>我就是聰明,可愛的小兵機器人</item> <item>hello,美女(帥鍋)</item> <item>你是我的小呀小蘋果</item> <item>開心的話,可以找我聊天,不開心更要找我聊天啦</item> </string-array>

    </resources>

    AndroidManifest.xml的程式碼

    新增的程式碼為加黑的粗體。

    <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.shenbin.person" android:versionCode="1" android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <uses-permission android:name="android.permission.INTERNET"/>

    <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.shenbin.person.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>

  • 中秋節和大豐收的關聯?
  • 為啥最近有這麼多重疾險,突然就不賣了?是真的嗎?