您的位置:首页 > 理论基础 > 计算机网络

Android http 下载图片

2015-08-06 10:41 591 查看
本文主要是介绍Android http下载图片操作,具体先看代码。

1.MainActivity.java

public class MainActivity extends Activity implements OnClickListener {
	private String TAG="MainActivity";
	private Bitmap mDownloadImage = null;
	private ImageView image = null;
	private downloadImageTask task;
	private boolean _isExe = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initWidgets();
		task = new downloadImageTask();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (_isExe) {
			task.cancel(true); // 取消操作
		}
	}

	private void initWidgets() {
		image = (ImageView) findViewById(R.id.img);
		Button btn = (Button) findViewById(R.id.download_btn);
		btn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.download_btn:
			if (!_isExe) {
				Toast.makeText(getApplicationContext(), "正在下载请稍后...", Toast.LENGTH_SHORT).show();
				task.execute("http://f.hiphotos.baidu.com/image/w%3D2048/sign=3b06d28fc91349547e1eef6462769358/d000baa1cd11728b22c9e62ccafcc3cec2fd2cd3.jpg"); // 执行异步操作
				_isExe = true;	
			}
			break;

		default:
			break;
		}
	}

	class downloadImageTask extends AsyncTask<String, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			Log.d(TAG,"[downloadImageTask->]doInBackground "+ params[0]);		
			mDownloadImage = HttpUtils.getNetWorkBitmap(params[0]);
			return true;
		}

		// 下载完成回调
		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			image.setImageBitmap(mDownloadImage);
			Log.d(TAG,"result = " + result);
			super.onPostExecute(result);
		}

		// 更新进度回调
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
	}
}


2.HttpUtils.java

/**
 * http工具类 http可以使用HttpURLConnection或HttpClient
 * 
 */
public class HttpUtils {
	private static String TAG="HttpUtils";
	/**
	 * 获取网络图片
	 * 
	 * @param urlString
	 *            如:http://f.hiphotos.baidu.com/image/w%3D2048/sign=3
	 *            b06d28fc91349547e1eef6462769358
	 *            /d000baa1cd11728b22c9e62ccafcc3cec2fd2cd3.jpg
	 * @return
	 */
	public static Bitmap getNetWorkBitmap(String urlString) {
		URL imgUrl = null;
		Bitmap bitmap = null;
		try {
			imgUrl = new URL(urlString);
			// 使用HttpURLConnection打开连接
			HttpURLConnection urlConn = (HttpURLConnection) imgUrl
					.openConnection();
			urlConn.setDoInput(true);
			urlConn.connect();
			// 将得到的数据转化成InputStream
			InputStream is = urlConn.getInputStream();
			// 将InputStream转换成Bitmap
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			Log.d(TAG,"[getNetWorkBitmap->]MalformedURLException");
			e.printStackTrace();
		} catch (IOException e) {
			Log.d(TAG,"[getNetWorkBitmap->]IOException");
			e.printStackTrace();
		}
		return bitmap;
	}
}


3.布局文件activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
   >
   
	<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="24dip"
        android:layout_gravity="center"
        android:text="http下载图片测试 "/>
	
    <Button
		 android:id="@+id/download_btn"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="下载"
		/>

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
      />

</LinearLayout>


4.修改配置文件AndroidManifest.xml,添加相应权限

<uses-permission android:name="android.permission.INTERNET" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: