android 聊天机器人
相关信息全写在代码中,很详细
一 、界面展示
做了图标适配 感觉还可以。。。emmm nice
二 、代码
遇到的坑也都在代码中做了解释,下面是我查阅的一些资料
demo下载地址:
https://download.csdn.net/download/qq_42733641/12026256
1、mainActivity.java
http://api.qingyunke.com/ 青云客聊天机器人API 也可以找其他的,但是要注册实名之类的
https://www.jianshu.com/p/4e8e4fd13cf7 ListView与AdapterView全面解析
https://blog.csdn.net/sinat_37064286/article/details/86537354 Java-IO流 数据在网络传输中的类型
https://blog.csdn.net/csxypr/article/details/92378336 String、StringBuffer和StringBuilder的区别
https://www.jianshu.com/p/da6af26b7483
https://blog.csdn.net/github_36217929/article/details/78435026 文字转语音 TextToSpeech类的简单使用
https://blog.csdn.net/lucasxu01/article/details/80764114 json踩坑
package cn.itcast.robot_alpha;import androidx.appcompat.app.AppCompatActivity;import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;import org.json.JSONException;
import org.json.JSONObject;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;public class MainActivity extends AppCompatActivity {private EditText editText;private Button btText;private ListView lvitem;private Button btsetTts;private SeekBar sbSpeedRate;private SeekBar sbPitch;public static String URL = "http://api.qingyunke.com/api.php?key=free&appid=0&msg="; //智能机器人API//listview 适配器private List<String> list = new ArrayList<>();ArrayAdapter<String> adapter;//文字转语音 TTS 使用原生 TextToSpeechprivate TextToSpeech tts;float SpeedRate = 1.0f; //语速float Pitch = 1.5f; //音调boolean flag = false; //0 关 1 开 //语音播报开关//handler 接受子线程的消息并控制播报 语音播报不能放在子线程 会闪退@SuppressLint("HandlerLeak")private Handler handler = new Handler(){public void handleMessage(Message msg){if(msg.what == 1){Log.d("接受 = ", "ok");//使用Bundle 携带信息Bundle bundle = msg.getData();String result = bundle.getString("msg");//语音播报开关标志 ,由按钮控制if(flag == true){if(result == null){tts.speak("输入为空",TextToSpeech.QUEUE_FLUSH,null);}//不能在子线程进行,会闪退tts.speak(result,TextToSpeech.QUEUE_FLUSH,null);}}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//控件初始化initview();//listview的适配器 可以自定义 这里使用原生ArrayAdapetradapter = new ArrayAdapter<String>(MainActivity.this,R.layout.support_simple_spinner_dropdown_item,list);list.add("欢迎回来,Alpha!");//speek("欢迎回来,Alpha!");lvitem.setAdapter(adapter);//TextToSpeech 创建及监听TextToSpeech.OnInitListener listener;tts = new TextToSpeech(this, new OnInitListener() {@Overridepublic void onInit(int i) {//是否支持播报if(i == TextToSpeech.SUCCESS){//是否支持中文播报 ,可以在手机设置搜“语音”,查看是否有中文库(有语音助手的一般都会有)int result = tts.setLanguage(Locale.CHINA);if(result != TextToSpeech.LANG_COUNTRY_AVAILABLE && result != TextToSpeech.LANG_AVAILABLE){Toast.makeText(MainActivity.this,"不支持中文",Toast.LENGTH_SHORT).show();}}}});tts.setSpeechRate(SpeedRate); //设置语速tts.setPitch(Pitch); //设置语调//监听 不用可删掉tts.setOnUtteranceProgressListener(new UtteranceProgressListener(){@Overridepublic void onStart(String s) {}@Overridepublic void onDone(String s) {}@Overridepublic void onError(String s) {}});}private void initview() {// textView = findViewById(R.id.tv_item);editText = findViewById(R.id.ed_text);btText = findViewById(R.id.bt_text);lvitem = findViewById(R.id.lv_item);btsetTts = findViewById(R.id.btsettts);sbSpeedRate = findViewById(R.id.sb_SpeedRate);sbPitch = findViewById(R.id.sb_Pitch);//滑动条监听事件sbPitch.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {@Overridepublic void onProgressChanged(SeekBar seekBar, int i, boolean b) {//seekbar是idfloat Rate = (float)i/10;//Log.d("i = ", i+"");// Log.d("rate = ", Rate+"");tts.setPitch(Rate); //设置音调}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {}});sbSpeedRate.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {@Overridepublic void onProgressChanged(SeekBar seekBar, int i, boolean b) {//seekbar是idfloat Rate = (float)i/10;//Log.d("i = ", i+"");// Log.d("rate = ", Rate+"");tts.setSpeechRate(Rate); //设置音速}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {}});//语音播报控制按钮btsetTts.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {btsetTts.setText("关闭语音");flag = !flag;if(flag == true){Toast.makeText(MainActivity.this,"语音已打开",Toast.LENGTH_SHORT).show();}elseToast.makeText(MainActivity.this,"语音已关闭",Toast.LENGTH_SHORT).show();}});//向API接口发送消息btText.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//tts.speak("哈哈哈哈哈哈哈",TextToSpeech.QUEUE_FLUSH,null);sendMsg();}});}public void sendMsg(){String msg;msg = editText.getText().toString();// textView.setText(msg+"\n");list.add("Alpha: "+msg);adapter.notifyDataSetChanged(); //更新ListViewdoget(msg);}//接受消息并发送public void doget(final String msg){new Thread(new Runnable(){@Overridepublic void run() {String url = URL+msg; //拼接消息 使用get方式发送BufferedReader reader = null;HttpURLConnection connection = null;String result;try {//连接java.net.URL con = new URL(url);connection = (HttpURLConnection) con.openConnection();connection.setRequestMethod("GET");connection.setConnectTimeout(5000);connection.setReadTimeout(5000);//获取返回的数据 接收到的时json字符串InputStream inputStream = connection.getInputStream();reader = new BufferedReader(new InputStreamReader(inputStream));//可变字符串对象,线程不安全,性能略高StringBuilder builder = new StringBuilder();String line = null;while ((line = reader.readLine()) != null) {builder.append(line);}result = builder.toString();//更新UIupdateUI(parseJson(result));Log.d("返回 = ", result);} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (connection != null) {connection.disconnect();if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}}}}}).start();}private void updateUI(final String result) {runOnUiThread(new Runnable(){@Overridepublic void run() {// textView.append(result);list.add("blibli: "+result);adapter.notifyDataSetChanged();//接受到返回数据就刷新界面//handler 将数据传递出去 使用Bundle携带数据Message message = new Message();message.what = 1;Bundle bundle = new Bundle();bundle.putString("msg",result);message.setData(bundle);handler.sendMessage(message);}});}//json数据处理private static String parseJson(String date) {String result = null;try {JSONObject jsonObject = new JSONObject(date);result = jsonObject.getString( "content");Log.d("处理 = ", result);} catch (JSONException ex) {ex.printStackTrace();}return result;}@Overrideprotected void onStop() {super.onStop();tts.stop(); // 不管是否正在朗读TTS都被打断tts.shutdown(); //释放资源}
}
2.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><Buttonandroid:id="@+id/btsettts"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="开启语音"/><TextViewandroid:id="@+id/tv_setting"android:layout_width="wrap_content"android:layout_height="match_parent"android:lines="2"android:maxEms="3"android:gravity="center"android:text="音速:音调:" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><SeekBarandroid:id="@+id/sb_SpeedRate"android:layout_width="match_parent"android:layout_height="wrap_content"android:progress="10"android:max="20"android:layout_weight="1"/><SeekBarandroid:id="@+id/sb_Pitch"android:layout_width="match_parent"android:layout_height="wrap_content"android:progress="10"android:max="20"android:layout_weight="1"/></LinearLayout>></LinearLayout><ListViewandroid:id="@+id/lv_item"android:layout_width="match_parent"android:layout_height="40dp"android:layout_weight="1"></ListView><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><EditTextandroid:id="@+id/ed_text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:hint="输入框"android:layout_weight="1"/><Buttonandroid:id="@+id/bt_text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="发送"/></LinearLayout></LinearLayout>