android 后台访问网络
时间: 2023-10-16 16:10:57 浏览: 43
在 Android 应用中进行后台网络访问可以使用 Android 提供的 AsyncTask 或者 Volley 框架。
使用 AsyncTask:
1. 创建一个继承 AsyncTask 的子类;
2. 在 doInBackground() 方法中进行网络请求;
3. 在 onPostExecute() 方法中处理请求结果。
示例代码:
```
public class NetworkTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
String result = "";
try {
URL url = new URL("http://www.example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream in = new BufferedInputStream(conn.getInputStream());
result = readStream(in);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result) {
// 处理请求结果
}
private String readStream(InputStream is) throws IOException {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while (i != -1) {
bo.write(i);
i = is.read();
}
return bo.toString();
}
}
```
使用 Volley:
1. 添加 Volley 依赖;
2. 创建一个 RequestQueue 对象;
3. 创建一个 StringRequest 对象,设置请求地址和回调函数;
4. 将请求加入到请求队列中。
示例代码:
```
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.example.com";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// 处理请求结果
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// 处理请求错误
}
});
queue.add(stringRequest);
```