标签:
1.新建一个Activity,布局文件如下
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="获取图片"/> </LinearLayout>
Activity的java代码如下:
一个显示图片的ImageView,一个用户触发操作的Button,urlString是网络图片的地址
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private ImageView mImageView; private Button mButton; private String urlString = "http://image.tianjimedia.com/uploadImages/2012/231/59/W19D0E6GL776.jpg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mImageView = (ImageView)findViewById(R.id.imageView); mButton = (Button)findViewById(R.id.button); mButton.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.button: MyAsyncTask myAsyncTask = new MyAsyncTask(mImageView); myAsyncTask.execute(urlString); break; default: break; } } }
2.自定义的异步任务MyAsyncTask
传入的参数为String,也就是网络图片的地址,返回值为一个Bitmap,用来显示在ImageView中,同时MyAsyncTask持有一个主Activity中ImageView的引用
通过网络图片地址构建一个URL,设置超时时间以及请求方法,如果返回值为200,代表成功,然后获取输入流,通过BitmapFactory构建Bitmap
public class MyAsyncTask extends AsyncTask<String,Void,Bitmap> { public static final String TAG = "MyAsyncTask"; private ImageView mImageView; public MyAsyncTask(ImageView imageView){ this.mImageView = imageView; } @Override protected Bitmap doInBackground(String... params) { String urlString = params[0]; try{ URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if(conn.getResponseCode() == 200){ InputStream inputStream = conn.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } }catch (Exception ex){ ex.printStackTrace(); } return null; } @Override protected void onPostExecute(Bitmap bitmap) { if(bitmap != null){ mImageView.setImageBitmap(bitmap); } } }
标签:
原文地址:http://www.cnblogs.com/hanqi/p/5680474.html