304
No
class ImageActivity
package com.example.choi.ex05_network;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageActivity extends AppCompatActivity implements Runnable{
//1. 변수 선언
Button button1;
ImageView img1;
Bitmap bitmap; //비트맵 객체
final String img_url ="http://192.168.0.2:2424/mainbanner/78ef8348-fbd4-486c-8b95-71a246bad6b3_1.jpg";
//메인 스레드와 백그라운드 스레드 간의 통신
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//이미지뷰에 비트맵 리소스 연결
img1.setImageBitmap(bitmap);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image);
//2. 위젯 연결
button1=(Button)findViewById(R.id.button1);
img1=(ImageView)findViewById(R.id.img1);
//3. 버튼 클릭 이벤트
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//백그라운드 스레드 생성
Thread th=new Thread(ImageActivity.this);
th.start(); //run() 이 실행됨.
}
});
}
//Alt + Insert Implement methods
@Override
public void run() {
//http://192.168.0.2:2424/mainbanner/78ef8348-fbd4-486c-8b95-71a246bad6b3_1.jpg
URL url=null;
try{
//스트링 주소를 url 형식으로 변환
url=new URL(img_url);
//url 에 접속 시도
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.connect();
//스트림 생성
InputStream is=connection.getInputStream();
//스트림에서 받은 데이터를 비트맵 변환
bitmap= BitmapFactory.decodeStream(is);
// 핸들러에게 화면 갱시 요청
handler.sendEmptyMessage(0);
//연결 종료
connection.disconnect();
}catch (Exception e){
e.printStackTrace();
}
}
}
image
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.choi.ex05_network.ImageActivity">
<Button
android:text="다운로드"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="@+id/button1" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="@mipmap/ic_launcher"
android:layout_below="@+id/button1"
android:layout_marginTop="18dp"
android:id="@+id/img1"
android:layout_alignParentEnd="true" />
</RelativeLayout>
댓글 ( 4)
댓글 남기기