圖片檢視器
阿新 • • 發佈:2019-02-01
UI設計
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height ="match_parent"
tools:context=".MainActivity"
tools:layout_editor_absoluteY="81dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/et_url"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/bt_look"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text ="檢視原始碼" />
<ImageView
android:id="@+id/iv_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
直接載入網頁圖片
package com.example.administrator.logincase;
import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static android.content.pm.PackageManager.PERMISSION_DENIED;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
public class MainActivity extends AppCompatActivity {
static final int m_nError = 0;
static final int m_nLookImage = 1;
/*
* 定義一個handler用於接收執行緒訊息
* */
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case m_nError:
Toast.makeText(MainActivity.this, "http請求錯誤",
Toast.LENGTH_SHORT).show();
return;
case m_nLookImage:
ImageView image=findViewById(R.id.iv_image);
Bitmap bitmap= (Bitmap) msg.obj;
image.setImageBitmap(bitmap);
return;
default:
break;
}
super.handleMessage(msg);
}
};
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 0x11: {
if (grantResults[0] == PERMISSION_GRANTED) {
Toast.makeText(this, "網路許可權請求成功",
Toast.LENGTH_SHORT).show();
return;
} else {
Toast.makeText(this, "網路許可權請求失敗",
Toast.LENGTH_SHORT).show();
return;
}
}
default:
break;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkSelfPermission(Manifest.permission.INTERNET) == PERMISSION_DENIED) {
requestPermissions(new String[]{Manifest.permission.INTERNET}, 0x11);
}
}
public void click(View v) {
/*
* 網路的訪問必須線上程裡面實現
* */
new Thread() {
@Override
public void run() {
EditText editText = findViewById(R.id.et_url);
String strUrl = editText.getText().toString().trim();
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
if (conn.getResponseCode() != 200) {
Message msg = Message.obtain();
msg.what = m_nError;
handler.sendMessage(msg);
return;
}
InputStream in = new BufferedInputStream(conn.getInputStream());
Bitmap bitmap = BitmapFactory.decodeStream(in);
Message msg = Message.obtain();
msg.what = m_nLookImage;
msg.obj = bitmap;
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
利用快取
生成到快取中的檔案可以在安卓應用中點選清除資料清楚
package com.example.administrator.logincase;
import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static android.content.pm.PackageManager.PERMISSION_DENIED;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
public class MainActivity extends AppCompatActivity {
static final int m_nError = 0;
static final int m_nLookImage = 1;
/*
* 定義一個handler用於接收執行緒訊息
* */
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case m_nError:
Toast.makeText(MainActivity.this, "http請求錯誤",
Toast.LENGTH_SHORT).show();
return;
case m_nLookImage:
ImageView image = findViewById(R.id.iv_image);
Bitmap bitmap = (Bitmap) msg.obj;
image.setImageBitmap(bitmap);
return;
default:
break;
}
super.handleMessage(msg);
}
};
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 0x11: {
if (grantResults[0] == PERMISSION_GRANTED) {
Toast.makeText(this, "網路許可權請求成功",
Toast.LENGTH_SHORT).show();
return;
} else {
Toast.makeText(this, "網路許可權請求失敗",
Toast.LENGTH_SHORT).show();
return;
}
}
default:
break;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkSelfPermission(Manifest.permission.INTERNET) == PERMISSION_DENIED) {
requestPermissions(new String[]{Manifest.permission.INTERNET}, 0x11);
}
}
public void click(View v) {
new Thread() {
@Override
public void run() {
EditText editText = findViewById(R.id.et_url);
String strUrl = editText.getText().toString().trim();
try {
/*
* 快取圖片,如果圖片已經存在了就不從網上下載了
* */
File file = new File(getCacheDir(), "test.jpg");
if (file.exists() && file.length() > 0) {
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Message msg = Message.obtain();
msg.what = m_nLookImage;
msg.obj = bitmap;
handler.sendMessage(msg);
return;
}
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
if (conn.getResponseCode() != 200) {
Message msg = Message.obtain();
msg.what = m_nError;
handler.sendMessage(msg);
return;
}
InputStream in = new BufferedInputStream(conn.getInputStream());
FileOutputStream fos = new FileOutputStream(file);
int len = -1;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
in.close();
fos.close();
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Message msg = Message.obtain();
msg.what = m_nLookImage;
msg.obj = bitmap;
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
使用runOnUiThread
package com.example.administrator.logincase;
import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static android.content.pm.PackageManager.PERMISSION_DENIED;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
public class MainActivity extends AppCompatActivity {
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 0x11: {
if (grantResults[0] == PERMISSION_GRANTED) {
Toast.makeText(this, "網路許可權請求成功",
Toast.LENGTH_SHORT).show();
return;
} else {
Toast.makeText(this, "網路許可權請求失敗",
Toast.LENGTH_SHORT).show();
return;
}
}
default:
break;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkSelfPermission(Manifest.permission.INTERNET) == PERMISSION_DENIED) {
requestPermissions(new String[]{Manifest.permission.INTERNET}, 0x11);
}
}
public void click(View v) {
new Thread() {
@Override
public void run() {
EditText editText = findViewById(R.id.et_url);
String strUrl = editText.getText().toString().trim();
try {
/*
* 快取圖片,如果圖片已經存在了就不從網上下載了
* */
File file = new File(getCacheDir(), "test.jpg");
if (file.exists() && file.length() > 0) {
final Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
runOnUiThread(new Runnable() {
@Override
public void run() {
ImageView image = findViewById(R.id.iv_image);
image.setImageBitmap(bitmap);
}
});
return;
}
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
if (conn.getResponseCode() != 200) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "網路許可權請求成功",
Toast.LENGTH_SHORT).show();
}
});
return;
}
InputStream in = new BufferedInputStream(conn.getInputStream());
FileOutputStream fos = new FileOutputStream(file);
int len = -1;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
in.close();
fos.close();
final Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
runOnUiThread(new Runnable() {
@Override
public void run() {
ImageView image = findViewById(R.id.iv_image);
image.setImageBitmap(bitmap);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}