本篇內容主要講解“Android中如何實現一個圖片查看器”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“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);
// };};
@Override
protected 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();}}到此,相信大家對“Android中如何實現一個圖片查看器”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。