Android 智能聊天机器人demo(类似小爱同学)

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  使用原生 TextToSpeech
    private 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);
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //控件初始化
        initview();

        //listview的适配器 可以自定义 这里使用原生ArrayAdapetr
        adapter = 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() {
            @Override
            public 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(){

            @Override
            public void onStart(String s) {

            }

            @Override
            public void onDone(String s) {

            }

            @Override
            public 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() {
             @Override
             public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                 //seekbar是id
                 float Rate = (float)i/10;
                 //Log.d("i = ", i+"");
                 // Log.d("rate = ", Rate+"");
                 tts.setPitch(Rate);   //设置音调
             }

             @Override
             public void onStartTrackingTouch(SeekBar seekBar) {

             }

             @Override
             public void onStopTrackingTouch(SeekBar seekBar) {

             }
         });
        sbSpeedRate.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //seekbar是id
                float Rate = (float)i/10;
                //Log.d("i = ", i+"");
               // Log.d("rate = ", Rate+"");
                tts.setSpeechRate(Rate);   //设置音速
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //语音播报控制按钮
        btsetTts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btsetTts.setText("关闭语音");
                flag = !flag;
                if(flag == true){
                    Toast.makeText(MainActivity.this,"语音已打开",Toast.LENGTH_SHORT).show();
                }else
                    Toast.makeText(MainActivity.this,"语音已关闭",Toast.LENGTH_SHORT).show();
            }
        });
        //向API接口发送消息
        btText.setOnClickListener(new View.OnClickListener() {
            @Override
            public 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();   //更新ListView
        doget(msg);
    }
    //接受消息并发送
    public  void doget(final String msg){
        new Thread(new Runnable(){
            @Override
            public 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();
                    //更新UI
                    updateUI(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(){
            @Override
            public 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;
    }

    @Override
    protected 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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <Button
            android:id="@+id/btsettts"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="开启语音"
            />
        <TextView
            android: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="音速:音调:" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <SeekBar
                android:id="@+id/sb_SpeedRate"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:progress="10"
                android:max="20"
                android:layout_weight="1"
                />
            <SeekBar
                android: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>


    <ListView
        android:id="@+id/lv_item"
        android:layout_width="match_parent"
        android:layout_height="40dp"

        android:layout_weight="1">

    </ListView>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/ed_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="输入框"
            android:layout_weight="1"
            />
        <Button
            android:id="@+id/bt_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="发送"
            />
    </LinearLayout>


</LinearLayout>
发布了23 篇原创文章 · 获赞 2 · 访问量 1197

猜你喜欢

转载自blog.csdn.net/qq_42733641/article/details/103490181