출처: https://www.edwith.org/boostcourse-android/lecture/17094/



1. 구현 결과 화면

  



2. AndroidManifest.xml

인터넷 권한을 추가한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tistory.qlyh8.practice">
 
    <uses-permission android:name="android.permission.INTERNET" />
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>
cs



3. activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context="com.tistory.qlyh8.practice.MainActivity">
 
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="이미지 가져오기"/>
 
    <ImageView
        android:id="@+id/image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
 
</LinearLayout>
 
cs



4. ImageLoadTask.java

이미지가 웹서버의 어디에 위치하고 있는지에 대한 정보를 받았다면 그 파일을 다운로드할 수 있다.

객체를 생성할 때, 이미지 Url와 이 이미지를 다운로드 받은 후 화면에 보여줄 때 사용할 ImageVIew를 파라미터로 전달한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.tistory.qlyh8.practice.ch5;
 
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
 
import java.net.URL;
import java.util.HashMap;
 
public class ImageLoadTask extends AsyncTask <Void, Void, Bitmap> {
 
    private String urlStr;
    private ImageView imageView;
    private HashMap<String, Bitmap> hashMap = new HashMap<>();
 
    // 어떤 url 로 요청할 지, 응답을 받은 후 어떤 이미지뷰에 설정할 지 전달받음
    public ImageLoadTask(String urlStr, ImageView imageView){
        this.urlStr = urlStr;
        this.imageView = imageView;
    }
 
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
 
    @Override
    protected Bitmap doInBackground(Void... voids) {
        // 웹서버의 이미지 데이터를 받아 비트맵 객체로 만든다.
        Bitmap bitmap = null;
        try {
            // 메모리에 만들어진 후 해제되지 않으면 메모리에 계속 남아있는다.
            // 여러 이미지를 로딩하게 되면 메모리가 부족해지는 문제가 발생할 수 있으므로
            // 사용하지 않는 비트맵 객체는 recycle() 메소드를 이용해 즉시 해제시킨다.
            if(hashMap.containsKey(urlStr)){  // 요청 주소가 들어있다면 비트맵을 꺼냄
                Bitmap oldBitmap = hashMap.remove(urlStr);
                if(oldBitmap != null){
                    oldBitmap.recycle();    // 들어왔던 비트맵을 메모리에 제거
                    oldBitmap = null;
                }
            }
 
            URL url = new URL(urlStr);
            // 주소로 접속하여 이미지 스트림을 받고, decodeStream 을 통해 비트맵으로 바꿈
            bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
 
            hashMap.put(urlStr, bitmap); // 새 비트맵을 넣음
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
 
    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
 
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        imageView.setImageBitmap(bitmap);   // 비트맵을 이미지뷰에 설정
        imageView.invalidate(); // 이미지를 다시 그림
    }
}
 
cs



5. MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.tistory.qlyh8.practice;
 
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
 
import com.tistory.qlyh8.practice.ch5.ImageLoadTask;
 
public class MainActivity extends AppCompatActivity {
    ImageView imageView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        imageView = findViewById(R.id.image_view);
 
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "https://movie-phinf.pstatic.net/20180620_259/1529458464756gRILM_JPEG/movie_image.jpg?type=m665_443_2";
                ImageLoadTask task = new ImageLoadTask(url, imageView);
                task.execute();
            }
        });
    }
}
cs



6. 참고

- Downloading custom sizes with Glide: https://github.com/bumptech/glide/wiki/Downloading-custom-sizes-with-Glide

- Universal Image Loader: https://github.com/nostra13/Android-Universal-Image-Loader

'Android' 카테고리의 다른 글

SQLiteOpenHelper 사용해보기  (0) 2018.08.19
SQLite database 사용해보기  (0) 2018.08.19
Volley 사용하기 - (2) JSON 요청하기  (1) 2018.07.31
Volley 사용하기 - (1)  (0) 2018.07.31
HTTP - 2. 웹으로 요청하기  (0) 2018.07.30

+ Recent posts