本文介紹了Android 簡單的圖片查看器源碼實現,分享給大家,具體如下:
public class MainActivity extends Activity {private EditText et_path;private ImageView iv; //創建handler 對象 // private Handler handler = new Handler(){ // // //處理消息 // public void handleMessage(android.os.Message msg) { // // Bitmap bitmap = (Bitmap) msg.obj;// iv.setImageBitmap(bitmap); // };};@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // [1]找到我們關心的控件 et_path = (EditText) findViewById(R.id.et_path); iv = (ImageView) findViewById(R.id.iv); }// [2]點擊按鈕進行查看 指定路徑的源碼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); //發消息 runOnUiThread(new Runnable() { public void run() { iv.setImageBitmap(cacheBitmap); } }); }else{ //第一次訪問 聯網獲取數據 System.out.println("第一次訪問連接網絡"); //[2.2]創建url對象 URL url = new URL(path); //[2.3]獲取httpurlconnection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //[2.4]設置請求的方式 conn.setRequestMethod("GET"); //[2.5]設置超時時間 conn.setConnectTimeout(5000); //[2.6]獲取服務器返回的狀態碼 int code = conn.getResponseCode(); if (code == 200) { //[2.7]獲取圖片的數據 不管是什么數據(txt文本 圖片數據 )都是以流的形式返回 InputStream in = conn.getInputStream(); //[2.7]緩存圖片 谷歌給我們提供了一個緩存目錄 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 不 管你在什么位置上調用 action都運行在UI線程里 runOnUiThread(new Runnable() { public void run() { //run方法一定執行在UI線程 里 // [2.9]把bitmap顯示到iv上 iv.setImageBitmap(bitmap); } });// Message msg = Message.obtain(); //使用msg的靜態方法 可以減少對象的創建// msg.obj = bitmap;// handler.sendMessage(msg); //發消息 } } } catch (Exception e) { e.printStackTrace(); } };}.start();}}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答