利用茉莉机器人接口开发一个简单的安卓机器人app
程序员文章站
2022-06-04 09:58:35
...
一、前言
茉莉机器人与其他机器人相比,主要的优势就是免费,不足之处就是不够智能,很多问题都回答不出来。不过呢,茉莉机器人允许用户自定义问题和问题对应的回答,对个人而言还是挺有用的,你可以利用这一点,记录自己容易忘记的一些事情。当然,不建议你把重要的信息,例如账户密码放上去。下图是注册登录账号之后的个人中心,你也可以去官网自己注册一个。
二、APP界面
应用比较简单,只有一个界面,如下图。
可以看到,你想让它怎么回答就怎么回答。大家自行去官网注册,把Api Key和Api Secret换成你们自己的即可。
三、代码
程序的所有接口、类如下图所示。
HttpCallbackListener和HttpUtil是用来进行网络请求操作的。
MainActivity是主界面对应的活动。
Msg是消息的实体类。
MsgAdapter是RecyclerView的适配器。
- HttpCallbackListener
public interface HttpCallbackListener
{
void onFinish(String response);
void onError(Exception e);
}
- HttpUtil
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtil
{
public static void sendHttpRequest(final String address, final HttpCallbackListener listener)
{
new Thread(new Runnable()
{
@Override
public void run()
{
HttpURLConnection connection = null;
try
{
URL url = new URL(address);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
{
response.append(line);
}
if (listener != null)
{
// 回调 onFinish()方法
listener.onFinish(response.toString());
}
} catch (Exception e)
{
if (listener != null)
{
// 回调 onError()方法
listener.onError(e);
}
} finally
{
if (connection != null)
{
connection.disconnect();
}
}
}
}).start();
}
}
- MainActivity
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
public class MainActivity extends AppCompatActivity
{
private EditText et;
private Button btn;
private RecyclerView rv;
private List<Msg> msgList = new ArrayList<>();
private MsgAdapter adapter;
private String [] arr={"近来可好,我亲爱的主人!",
"欢迎主人的归来!",
"很高兴又见到了我的主人!",
"主人您好,请问有什么可以帮您的吗?",
"我是一个能跟用户智能交互的“人”,可以帮用户查询一些实用的资料,比如天气预报、LoL战绩、IP地址等,还拥有一些娱乐系统,比如笑话和抽签等。"
};
private long curTime=0,oldTime=0;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=findViewById(R.id.et);
btn=findViewById(R.id.btn);
rv=findViewById(R.id.rv);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(layoutManager);
adapter = new MsgAdapter(msgList);
rv.setAdapter(adapter);
initMsgs();
btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String content = et.getText().toString();
if(!content.equals(""))
{
Msg msg = new Msg();
msg.setContent(content);
msg.setType(Msg.TYPE_SEND);
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = simpleDateFormat.format(new Date());
msg.setTime(format);
msgList.add(msg);
adapter.notifyItemInserted(msgList.size() - 1); // 当有新消息时,刷新 RecyclerView 中的显示
rv.scrollToPosition(msgList.size()-1);//// 将RecyclerView 定位到最后一行
et.setText("");
InputMethodManager imm =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
HttpUtil.sendHttpRequest("http://i.itpk.cn/api.php?api_key=fe6ed258c8faf18e6400bd7a9d401f16&api_secret=jwxa3c845wxb&question=" + content, new HttpCallbackListener()
{
@Override
public void onFinish(String response)
{
Msg msg = new Msg();
msg.setContent(response);
msg.setType(Msg.TYPE_RECEIVE);
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = simpleDateFormat.format(new Date());
msg.setTime(format);
msgList.add(msg);
adapter.notifyItemInserted(msgList.size() - 1); // 当有新消息时,刷新 RecyclerView 中的显示
rv.scrollToPosition(msgList.size()-1);//// 将RecyclerView 定位到最后一行
}
@Override
public void onError(Exception e)
{
}
});
}
}
});
}
private void initMsgs()
{
Random random=new Random();
int i = random.nextInt(arr.length);
Msg msg1 = new Msg();
msg1.setType(Msg.TYPE_RECEIVE);
msg1.setContent(arr[i]);
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = simpleDateFormat.format(new Date());
msg1.setTime(format);
msgList.add(msg1);
}
}
- Msg
public class Msg
{
public static final int TYPE_RECEIVE=0;
public static final int TYPE_SEND=1;
private String content;
private int type;
private String time;
public String getContent()
{
return content;
}
public void setContent(String content)
{
this.content = content;
}
public int getType()
{
return type;
}
public void setType(int type)
{
this.type = type;
}
public String getTime()
{
return time;
}
public void setTime(String time)
{
this.time = time;
}
}
- MsgAdapter
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder>
{
private static long curTime=0,oldTime=0;
private List<Msg> mMsgList;
static class ViewHolder extends RecyclerView.ViewHolder
{
LinearLayout leftLayout;
LinearLayout rightLayout;
TextView leftMsg;
TextView rightMsg;
TextView timeTv1;
TextView timeTv2;
public ViewHolder(View view)
{
super(view);
leftLayout = (LinearLayout) view.findViewById(R.id.left_layout);
rightLayout = (LinearLayout) view.findViewById(R.id.right_layout);
leftMsg = (TextView) view.findViewById(R.id.left_msg);
rightMsg = (TextView) view.findViewById(R.id.right_msg);
timeTv1=(TextView)view.findViewById(R.id.timeTv1);
timeTv2=(TextView)view.findViewById(R.id.timeTv2);
}
}
public MsgAdapter(List<Msg> msgList)
{
mMsgList = msgList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
Msg msg = mMsgList.get(position);
if (msg.getType() == Msg.TYPE_RECEIVE)
{
// 如果是收到的消息,则显示左边的消息布局,将右边的消息布局隐藏
holder.leftLayout.setVisibility(View.VISIBLE);
holder.rightLayout.setVisibility(View.GONE);
holder.leftMsg.setText(msg.getContent());
holder.timeTv1.setText(msg.getTime());
} else if(msg.getType() == Msg.TYPE_SEND)
{
// 如果是发出的消息,则显示右边的消息布局,将左边的消息布局隐藏
holder.rightLayout.setVisibility(View.VISIBLE);
holder.leftLayout.setVisibility(View.GONE);
holder.rightMsg.setText(msg.getContent());
holder.timeTv2.setText(msg.getTime());
}
}
@Override
public int getItemCount()
{
return mMsgList.size();
}
}