根据url下载一张大小为1M左右的图片,然后用个ImageView显示出来。不爆内存的哦!!!

public class NewsletterInfoManager  extends TabManager {

	private static final NewsletterInfoManager INSTANCE = new NewsletterInfoManager();

	private ImageFileCache imageFileCache = new ImageFileCache();
	private Handler mHandler;
	private String newsLetterUrl;
    private Bitmap bitmap = null;

	protected NewsletterInfoManager() {
		mHandler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				if(bitmap!=null && !bitmap.isRecycled()){
					bitmap.recycle();
				}
				bitmap = imageFileCache.getBigImage(newsLetterUrl);
				getDC().loadImage(bitmap);
				getDC().getNewsletterProgressBar().setVisibility(View.INVISIBLE);
			}

		};
	}

	public static NewsletterInfoManager getInstance() {
		return INSTANCE;
	}


	@Override
	protected BaseDC createDC() {
		return new NewsletterDC(context, R.layout.newsletter_info2, this);
	}

	public NewsletterDC getDC() {
		return (NewsletterDC) super.getDC();
	}

	public void setData(Object obj) {
		Map<String,Object> map = (Map<String,Object>)obj;
		newsLetterUrl = (String)map.get("url");
		getDC().getImageView().setImageBitmap(null);

		if(bitmap!=null && !bitmap.isRecycled()){
			bitmap.recycle();
		}
		bitmap = imageFileCache.getBigImage(newsLetterUrl);
		if(bitmap==null){
			//远程加载图片,并保存到sdcard中
			if(Constant.netIsOK){
				getDC().getNewsletterProgressBar().setVisibility(View.VISIBLE);
			}

			startLoadImage();
		}else{

			getDC().loadImage(bitmap);

		}

	}

	private void startLoadImage(){
		new Thread(){
			public void run(){
				byte[] data;
				try {
					data = getImage(newsLetterUrl);
					if(data!=null){
						BitmapFactory.Options opt = new BitmapFactory.Options();
						opt.inPreferredConfig = Bitmap.Config.RGB_565;
						opt.inPurgeable = true;
						opt.inInputShareable = true;
		                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,opt);// bitmap
		                imageFileCache.saveBmpToSd(bitmap, newsLetterUrl);
		                if(bitmap!=null && !bitmap.isRecycled()){
		                		bitmap.recycle();
		                }
		                mHandler.sendEmptyMessage(0);
		            }
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}.start();
	}
	public void onClicked(int id) {
		super.onClicked(id);
	}

	/**
     * Get image from newwork
     * @param path The path of image
     * @return byte[]
     * @throws Exception
     */
    public byte[] getImage(String path) throws Exception{
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(10 * 1000);
        conn.setRequestMethod("GET");
        InputStream inStream = conn.getInputStream();
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
            return readStream(inStream);
        }else{
        		getDC().getNewsletterProgressBar().setVisibility(View.INVISIBLE);
        		Toast.makeText(context, "网络超时,获取图片失败",Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    /**
     * Get data from stream
     * @param inStream
     * @return byte[]
     * @throws Exception
     */
    public static byte[] readStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1){
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

保存图片到sdcard中的方法如下:
	public void saveBmpToSd(Bitmap bm, String url) {
		if (bm == null) {
			//需要保存的是一个空值
			return;
		}
		//判断sdcard上的空间
		if (FREE_SD_SPACE_NEEDED_TO_CACHE >freeSpaceOnSd()) {
			//SD空间不足
			return;
		}
    		String filename =convertUrlToFileName(url);
    		String dir = getDirectory();

    		checkDir(dir);

    		File file = new File(dir +"/" + filename);
    		try {
    		    file.createNewFile();
    			OutputStream outStream = new FileOutputStream(file);
    			if(filename.indexOf("png")>-1){
    				bm.compress(Bitmap.CompressFormat.PNG, 50, outStream);
    			}
    			if(filename.indexOf("jpeg")>-1 || filename.indexOf("jpg")>-1){
    				bm.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
    			}

    			outStream.flush();
    			outStream.close();

    		} catch (FileNotFoundException e) {
    			Log.w("ImageFileCache","FileNotFoundException");
    		} catch (IOException e) {
    			Log.w("ImageFileCache","IOException");
    		}
    }

上面的50代表逼真度,越大,保存后的文件就越大。



从sdcard获取图片的方法:"
public Bitmap getBigImage(final String url) {
		final String path = getDirectory() + "/" + convertUrlToFileName(url);
		File file = new File(path);
		if (file.exists()) {
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inPreferredConfig = Bitmap.Config.RGB_565;
			opts.inPurgeable = true;
			opts.inInputShareable = true;
			Bitmap bmp=BitmapFactory.decodeFile(path,opts);
			if(bmp==null)
			{
				file.delete();
			}else
			{
				updateFileTime(path);
				return bmp;
			}
		}
		return null;
	}




好的,这是一个使用Handler和Kotlin语言编写的网络下载图片的项目,包含一个进度条、一个按钮和一个ImageView。 首先,我们需要在XML布局文件中添加一个ProgressBar、一个Button和一个ImageView: ```xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ProgressBar android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:visibility="gone" /> <Button android:id="@+id/btnDownload" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Download" android:layout_below="@id/progressBar" android:layout_centerHorizontal="true" /> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/btnDownload" android:scaleType="fitCenter" /> </RelativeLayout> ``` 然后,在Kotlin代码中,我们需要定义一个Handler对象,用于更新UI界面。我们还需要使用AsyncTask类执行后台下载任务,并使用URLConnection和InputStream读取网络数据流。最后,我们需要将下载图片设置到ImageView中。 ```kotlin import android.graphics.BitmapFactory import android.os.AsyncTask import android.os.Bundle import android.os.Handler import android.os.Message import android.view.View import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.URL class MainActivity : AppCompatActivity() { private val handler: Handler = object : Handler() { override fun handleMessage(msg: Message) { super.handleMessage(msg) if (msg.what == 1) { val bitmap = msg.obj as android.graphics.Bitmap imageView.setImageBitmap(bitmap) progressBar.visibility = View.GONE } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnDownload.setOnClickListener { DownloadImageTask().execute("https://www.example.com/image.jpg") } } private inner class DownloadImageTask : AsyncTask<String, Void, android.graphics.Bitmap>() { override fun onPreExecute() { super.onPreExecute() progressBar.visibility = View.VISIBLE } override fun doInBackground(vararg urls: String): android.graphics.Bitmap? { val urlString = urls[0] var inputStream: InputStream? = null var httpURLConnection: HttpURLConnection? = null try { val url = URL(urlString) httpURLConnection = url.openConnection() as HttpURLConnection httpURLConnection.connect() inputStream = httpURLConnection.inputStream return BitmapFactory.decodeStream(inputStream) } catch (e: IOException) { e.printStackTrace() } finally { httpURLConnection?.disconnect() try { inputStream?.close() } catch (e: IOException) { e.printStackTrace() } } return null } override fun onPostExecute(result: android.graphics.Bitmap?) { super.onPostExecute(result) if (result != null) { val message = Message() message.what = 1 message.obj = result handler.sendMessage(message) } } } } ``` 以上就是一个使用Handler和Kotlin语言编写的网络下载图片的项目。当用户点击Download按钮时,会执行AsyncTask类中的doInBackground()方法,下载图片并返回Bitmap对象。然后,使用Handler对象将Bitmap对象发送到主线程,并在ImageView显示图片。同时,进度条在图片下载完成后消失。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值