Http与后台任务
发布日期:2021-04-30 21:02:45 浏览次数:91 分类:精选文章

本文共 1594 字,大约阅读时间需要 5 分钟。

网络基本连接代码

要从指定URL获取原始数据并返回一个字节流数组,可以使用以下代码实现:

public byte[] getUrlBytes(String urlSpec) throws IOException {    URL url = new URL(urlSpec);    HttpURLConnection connection = (HttpURLConnection) url.openConnection();    try {        ByteArrayOutputStream out = new ByteArrayOutputStream();        InputStream in = connection.getInputStream();        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {            return null;        }        byte[] buffer = new byte[1024];        int bytesRead = 0;        while ((bytesRead = in.read(buffer)) > 0) {            out.write(buffer, 0, bytesRead);        }        out.close();        return out.toByteArray();    } finally {        connection.disconnect();    }}

需要在Android应用中添加网络使用权限:

后台任务

在Android应用中,可以使用AsyncTask来执行后台任务。以下是一个示例:

private class FetchItemsTask extends AsyncTask
> { @Override protected ArrayList
doInBackground(Void... params) { return new FlickrFetchr().fetchItems(); }}

要在主线程启动后台任务,可以使用以下代码:

new FetchItemsTask().execute();

请注意,Android系统会监控主线程的响应情况。如果主线程无法响应重要事件(如按下返回键),应用可能会无响应。

创建正确转义的参数化URL

要创建一个参数化的URL,可以使用Uri类来实现。以下是一个示例:

String url = Uri.parse(ENDPOINT)    .buildUpon()    .appendQueryParameter("method", METHOD_GET_RECENT)    .appendQueryParameter("api_key", API_KEY)    .appendQueryParameter(PARAM_EXTRAS, EXTRA_SMALL_URL)    .build()    .toString();

从后台回到主线程

onPostExecute方法用于在后台任务完成后返回结果,并在主线程上更新UI。以下是一个示例:

protected void onPostExecute(ArrayList
galleryItems) { mItems = galleryItems; setupAdapter();}

这个方法在doInBackground()执行完毕后才会运行,且是在主线程上执行。

上一篇:价值2000元的学习资源泄露,详细的Android学习指南
下一篇:Spring中的Bean

发表评论

最新留言

表示我来过!
[***.240.166.169]2026年05月31日 05时03分48秒