AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="shortcut.song.com.myapplication.UrlTestActivity">
<ImageView
android:id="@+id/url_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
package shortcut.song.com.myapplication;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlTestActivity extends AppCompatActivity {
ImageView imageView;
Bitmap bitmap;
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0x1234) {
imageView.setImageBitmap(bitmap);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_url_test);
imageView = (ImageView)findViewById(R.id.url_show);
new Thread(){
@Override
public void run() {
super.run();
try {
URL url = new URL("http://192.168.8.27/files/JPG/9.jpg");
InputStream is = url.openStream();
bitmap = BitmapFactory.decodeStream(is);
handler.sendEmptyMessage(0x1234);
is.close();
is = url.openStream();
OutputStream os = openFileOutput("9.jpg", MODE_PRIVATE);
byte[] buff = new byte[1024];
int hasRead = 0;
while ((hasRead = is.read(buff)) > 0){
os.write(buff, 0, hasRead);
}
is.close();
os.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
运行效果(通过URL加载的图片):