標籤:des android style blog http io ar color os
轉載註明出處: http://www.cnblogs.com/frank-zouxu/p/4121601.html
在前幾日,偶然看到新聞,圖靈機器人向開發人員提供了API,API地址為:http://www.tuling123.com/openapi/,因為這個API可以定製自己的聊天機器人,這在我看來,是個很有意思的事情,於是我就試著在Android應用中進行了API測試,如下(圖1):
圖1
主要代碼如下:
public class MainActivity extends Activity implements OnClickListener { private String requesturl; private ListView lv; private EditText et_input; private ChatListAdapter chat_adp; private Context ctx; private InputMethodManager imm; private Button et_sendMsg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ctx = this; imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); setContentView(R.layout.activity_main); initView(); } private void initView() { lv = (ListView) findViewById(R.id.lv_conmunicate); et_input = (EditText) findViewById(R.id.et_input); et_input.setOnClickListener(this); et_sendMsg = (Button) findViewById(R.id.bt_sendMsg); et_sendMsg.setOnClickListener(this); chat_adp = new ChatListAdapter(ctx); lv.setAdapter(chat_adp); }
@Override public void onClick(View v) { switch (v.getId()) { case R.id.bt_sendMsg: new AsyReq().execute(et_input.getText().toString().trim()); break; } } private class AsyReq extends AsyncTask<String, Integer, String> { private String result; private DialogShowStyle dialog; @Override protected void onPreExecute() { // TODO Auto-generated method stub // 隱藏軟鍵盤 if (imm.isActive()) { ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(et_input.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } int netType = new NetWorkUtils(MainActivity.this).getNetType(); switch (netType) { case Configs.NONET: // handler.sendEmptyMessage(Configs.NONET); Toast.makeText(MainActivity.this, "請檢查網路連接", Toast.LENGTH_LONG) .show(); // 取消任務的執行 this.cancel(true); break; case Configs.SLOWNET: // handler.sendEmptyMessage(Configs.SLOWNET); dialog = new DialogShowStyle(MainActivity.this, "小圖靈正在深思..."); dialog.dialogShow(); case Configs.WIFI: chat_adp.add("我:" + et_input.getText().toString()); break; } } @Override protected String doInBackground(String... params) { try { // 防止get請求中出現中文亂碼 String INFO = URLEncoder.encode(params[0], "utf-8"); requesturl = Configs.API_URL + Configs.APIKEY + "&info=" + INFO; HttpGet request = new HttpGet(requesturl); HttpResponse response; response = new DefaultHttpClient().execute(request); if (response.getStatusLine().getStatusCode() == 200) { result = EntityUtils.toString(response.getEntity()); result = JsonUtils.analysisInfo(result); } } catch (Exception e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(String result) { if (dialog != null) { dialog.dialogDismiss(); dialog = null; } chat_adp.add("圖靈:" + result); et_input.setText(""); } }}
Android開發-圖靈聊天機器人介面引用