看到QQ群裡有個朋友說加載圖片內存溢出的問題,所以就按照自己的想法試試的。但是按照他的方法,不知道為何沒有發生內存溢出,不知道什麼情況。
寫這篇文章主要有三個目的:
1.多線程的學習
2.圖片加載的學習
3.編程練手
好了,上代碼
package org.tonny;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.R;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
public class NetpictActivity extends Activity
{
private Bitmap mBitmap = null;
private ImageView mView = null;
private Handler mHandler = null;
//網上隨便找的一個圖片
private final String mUri = "http://pic5.nipic.com/20100118/3822085_173909557153_2.jpg";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//這邊的用R.id.layout方法出現了問題,所以只好用數值代替了
setContentView(0x7f030000);
mView = (ImageView)this.findViewById(0x7f050000);
mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case 1:
if (mView == null || mBitmap == null)
{
return;
}
mView.setImageBitmap(mBitmap);
break;
}
}
};
}
public void onBtnShowClick(View v)
{
Thread thrad = new Thread()
{
@Override
public void run()
{
try
{
URL url = new URL(mUri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream inputStream = conn.getInputStream();
//mBitmap是一個全局變量,用於存儲圖片的數據
mBitmap = BitmapFactory.decodeStream(inputStream);
Message msg = mHandler.obtainMessage();
//注意這裡只傳輸了類型
msg.what = 1;
mHandler.sendMessage(msg);
inputStream.close();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
};
thrad.start();
}
}
注意在清單文件裡配置訪問網絡的權限
好了,繼續學習