最近,我正在 Android Studio 上开发一个测验应用程序。假设我正在处理一个问题,我点击了一个按钮,该按钮将发出一个 URL ( http://192.168.43.214/clicker/select?id=1&choice=a )。然后 URL 将作为响应捕获到数据库表中。
我试过类似的东西
findViewById(R.id.buttonA).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Uri uri = Uri.parse("http://192.168.43.214/clicker/select id=1&choice=a");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
这接近于我的解决方案(我的数据库能够捕获记录)但是用浏览器打开它不是故意的。相反,我希望它表现得像一个隐藏的后台进程,只发布一个 URL,除此之外什么都不做。
最佳答案
考虑使用 Volley。
Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster.
阅读,
首先添加依赖到你的build.gradle
文件
dependencies {
...
implementation 'com.android.volley:volley:1.1.1'
}
然后发送请求
String url ="http://192.168.43.214/clicker/select?id=1&choice=a";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// handle response here
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
关于java - 单击按钮时发出一个 url,它作为后台进程运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55668567/