我需要制作一个带有按钮的简单应用程序,它将调用一些URL。我在Rpi上有一个apache服务器,可通过发送GET URL来控制GPIO
http://192.168.0.105/index.php?pin=2&status=0。
在android studio中,我只做了一个onclick按钮。
问题是我对Java和android不熟悉,所以这是我的问题-使此按钮发送URL的最简单方法是什么?我找到了一些有关从服务器发送或接收数据的教程,但这不是我想要的。
最佳答案
添加清单的权限:<uses-permission android:name="android.permission.INTERNET" />
创建一个类:
class RequestTask extends AsyncTask<String, String, String> {
String response;
ProgressDialog dialog;
@Override
protected String doInBackground(String... params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]); // or HttpPost if you need
ResponseHandler<String> resHandler = new BasicResponseHandler();
response = httpClient.execute(httpGet, resHandler);
} catch (Exception e) {
System.out.println("E: " + e);
}
return null;
}
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
dialog.dismiss();
super.onPostExecute(result);
}
}
致电使用:
new RequestTask().execute("http://192.168.0.105/index.php?pin=2&status=0")