十年網(wǎng)站開發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
本篇內(nèi)容主要講解“Android中如何實(shí)現(xiàn)一個(gè)圖片查看器”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Android中如何實(shí)現(xiàn)一個(gè)圖片查看器”吧!

具體代碼如下:
public class MainActivity extends Activity {
private EditText et_path;
private ImageView iv;
//創(chuàng)建handler 對象
// private Handler handler = new Handler(){
//
// //處理消息
// public void handleMessage(android.os.Message msg) {
//
// Bitmap bitmap = (Bitmap) msg.obj;
// iv.setImageBitmap(bitmap);
// };};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// [1]找到我們關(guān)心的控件
et_path = (EditText) findViewById(R.id.et_path);
iv = (ImageView) findViewById(R.id.iv);
}
// [2]點(diǎn)擊按鈕進(jìn)行查看 指定路徑的源碼
public void click(View v) {
new Thread(){public void run() {
try {
//[2.1]獲取訪問圖片的路徑
String path = et_path.getText().toString().trim();
File file = new File(getCacheDir(),Base64.encodeToString(path.getBytes(), Base64.DEFAULT));
if (file.exists()&& file.length()>0) {
//使用緩存 的圖片
System.out.println("使用緩存圖片 ");
final Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//把cacheBitmap 顯示到iv上
// Message msg = Message.obtain();
// msg.obj = cacheBitmap;
// handler.sendMessage(msg); //發(fā)消息
runOnUiThread(new Runnable() {
public void run() {
iv.setImageBitmap(cacheBitmap);
}
});
}else{
//第一次訪問 聯(lián)網(wǎng)獲取數(shù)據(jù)
System.out.println("第一次訪問連接網(wǎng)絡(luò)");
//[2.2]創(chuàng)建url對象
URL url = new URL(path);
//[2.3]獲取httpurlconnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//[2.4]設(shè)置請求的方式
conn.setRequestMethod("GET");
//[2.5]設(shè)置超時(shí)時(shí)間
conn.setConnectTimeout(5000);
//[2.6]獲取服務(wù)器返回的狀態(tài)碼
int code = conn.getResponseCode();
if (code == 200) {
//[2.7]獲取圖片的數(shù)據(jù) 不管是什么數(shù)據(jù)(txt文本 圖片數(shù)據(jù) )都是以流的形式返回
InputStream in = conn.getInputStream();
//[2.7]緩存圖片 谷歌給我們提供了一個(gè)緩存目錄
FileOutputStream fos = new FileOutputStream(file);
int len = -1;
byte[] buffer = new byte[1024];//1kb
while((len=in.read(buffer))!=-1){
fos.write(buffer, 0, len);
}
fos.close();
in.close();
//[2.8]通過位圖工廠 獲取bitmap(bitmap)
final Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//這句api 不 管你在什么位置上調(diào)用 action都運(yùn)行在UI線程里
runOnUiThread(new Runnable() {
public void run() {
//run方法一定執(zhí)行在UI線程 里
// [2.9]把bitmap顯示到iv上
iv.setImageBitmap(bitmap);
}
});
// Message msg = Message.obtain(); //使用msg的靜態(tài)方法 可以減少對象的創(chuàng)建
// msg.obj = bitmap;
// handler.sendMessage(msg); //發(fā)消息
}
}
} catch (Exception e) {
e.printStackTrace();
}
};}.start();}}到此,相信大家對“Android中如何實(shí)現(xiàn)一個(gè)圖片查看器”有了更深的了解,不妨來實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)建站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!