本文主要是介绍Http与后台任务(AsyncTask),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
布局文件
<GridView xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/gridView"android:layout_width="match_parent"android:layout_height="match_parent"android:columnWidth="120dp"android:numColumns="3"android:stretchMode="columnWidth" />
<!--我们设置列的宽度为120dp,并使用numColumns属性指示GridView创建尽可能多的列,以铺满整个屏幕。如果在列的空间分配上出现少于120dp的剩余空间,则stretchMode属性会要求GridView在全部列间均分这部分剩余空间。
-->
网络连接类
package com.example.photogallery;import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;import android.net.Uri;
import android.util.Log;public class FlickrFetchr {private static final String TAG = "FlickrFetchr";private static final String ENDPOINT = "http://api.flickr.com/services/rest";private static final String API_KEY = "yourApiKeyHere";private static final String METHOD_GET_RECENT = "flickr.photos.getRecent";private static final String PARAM_EXTRAS = "extras";private static final String EXTRA_SMALL_URL = "url_s";private static final String XML_PHOTO = "photo";/*** HttpURLConnection对象虽然提供了一个连接,但只有在调用getInputStream()方法时(如果是POST请求,* 则调用getOutputStream()方法), 它才会真正连接到指定URL地址。在此之前我们无法获得有效的返回代码。*/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;}int bytesRead = 0;byte[] buffer = new byte[1024];while ((bytesRead = in.read(buffer)) > 0) {out.write(buffer, 0, bytesRead);}out.close();return out.toByteArray();} finally {connection.disconnect();}}public String getUrl(String urlSpec) throws IOException {return new String(getUrlBytes(urlSpec));}/*** 这里我们使用Uri.Builder构建完整的Filckr API请求URL。便利类Uri.Builder可创建正确转义的参数化URL。* Uri.Builder.appendQueryParameter(String, String)可自动转义查询字符串。*/public ArrayList<GalleryItem> fetchItems() {ArrayList<GalleryItem> items = new ArrayList<GalleryItem>();try {String url = Uri.parse(ENDPOINT).buildUpon().appendQueryParameter("method", METHOD_GET_RECENT).appendQueryParameter("api_key", API_KEY).appendQueryParameter(PARAM_EXTRAS, EXTRA_SMALL_URL).build().toString();String xmlString = getUrl(url);Log.i(TAG, xmlString);XmlPullParserFactory factory = XmlPullParserFactory.newInstance();XmlPullParser parser = factory.newPullParser();parser.setInput(new StringReader(xmlString));parseItems(items, parser);} catch (Exception e) {e.printStackTrace();}return items;}void parseItems(ArrayList<GalleryItem> items, XmlPullParser parser)throws XmlPullParserException, IOException {int eventType = parser.next();while (eventType != XmlPullParser.END_DOCUMENT) {if (eventType == XmlPullParser.START_TAG&& XML_PHOTO.equals(parser.getName())) {String id = parser.getAttributeValue(null, "id");String caption = parser.getAttributeValue(null, "title");String smallUrl = parser.getAttributeValue(null, EXTRA_SMALL_URL);GalleryItem item = new GalleryItem();item.setId(id);item.setCaption(caption);item.setUrl(smallUrl);}eventType = parser.next();}}
}
在子线程中执行网络请求(调用AsyncTask)
package com.example.photogallery;import java.util.ArrayList;import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;public class PhotoGalleryFragment extends Fragment {private static final String TAG = "PhotoGalleryFragment";private GridView mGridView;private ArrayList<GalleryItem> mItems;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setRetainInstance(true);new FetchItemsTask().execute();}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View view = inflater.inflate(R.layout.fragment_photo_gallery,container, false);mGridView = (GridView) view.findViewById(R.id.gridView);setupAdapter();return view;}/*** 设置adpter之前,应检查getActivity()的返回结果是否为空。这是因为fragment可脱离activity而存在。* 我们正在使用AsyncTask,我们必须自己负责触发相应的事件,而且也不能确定fragment是否与activity相关联。* 因此需检查确认fragment是否与activity相关联。如果fragment脱离了activity,则依赖于activity的操作* (如创建ArrayAdapter)就会失败。*/void setupAdapter() {if (getActivity() == null || mGridView == null)return;if (mItems != null) {mGridView.setAdapter(new ArrayAdapter<GalleryItem>(getActivity(),android.R.layout.simple_gallery_item, mItems));}else {mGridView.setAdapter(null);}}/*** AsyncTask<Params, Progress, Result>* Params可指定输入参数的类型。输入参数传入execute(...)方法(可接受一个或多个参数)。然后,这些变量参数传给doInBackground(...)方法* Progress指定发送进度更新需要的类型。在doInBackground(...)方法调用publishProgress(...)方法,系统会调用onProgressUpdate(...)方法,刷新进度* Result指定doInBackground(...)方法返回的类型以及onPostExecute(...)方法参数接受的类型。* * AsyncTask.cancel(boolean)方法撤销运行中的AsyncTask,分为两种工作模式:粗暴的和温和的。* 如调用温和的cancel(false)方法,该方法会设置isCancelled()状态为true。随后,AsyncTask会检查doInBackground(...)方法* 中的isCancelled()状态,然后选择提前结束运行。* 然而,如调用粗暴的cancel(true)方法,它会终止doInBackground(...)方法当前所在的线程。AsyncTask.cancel(true)方法停止AsyncTask* 的方式简单粗暴,如有可能,应尽量避免此种方式。*/private class FetchItemsTask extends AsyncTask<Void, Void, ArrayList<GalleryItem>> {@Overrideprotected void onPreExecute() {super.onPreExecute();}@Overrideprotected ArrayList<GalleryItem> doInBackground(Void... params) {return new FlickrFetchr().fetchItems();}@Overrideprotected void onProgressUpdate(Void... values) {super.onProgressUpdate(values);}@Overrideprotected void onPostExecute(ArrayList<GalleryItem> result) {mItems = result;setupAdapter();}}
}
代码地址
这篇关于Http与后台任务(AsyncTask)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!