지난번에 만들었던 갤러리 앱의 경우 res/drawable 디렉토리에 사용하는 모든 이미지를 넣어두었는데 이러다보니 앱 자체의 사이즈가 너무 커지는 단점이 있다. 그래서 외부 웹에서 이미지를 가져오도록 수정하였다.

우선 앱에서 인터넷에 접속할 수 있는 권한을 AndroidManifest.xml 에 주어야 한다. 아래와 같이 uses-permission을 사용하여 INTERNET 권한을 주면 된다.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.hellogallery"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">

다음으로는 ImageAdapter class에서 사용했던 mImageIds 대신에 mRemoteImages를 다음과 같이 만든다. 여기엔 web상에 있는 이미지의 주소를 나열해주면 된다.
    private String[] mRemoteImages = {
        "http://www.examples.com/a.jpg",
        "http://www.examples.com/b.jpg",
        "http://www.examples.com/c.jpg",
        "http://www.examples.com/d.jpg",
        "http://www.examples.com/e.jpg"
    };

그 후엔 mImageIds를 사용하던 부분을 mRemoteImages를 사용해 구현하면 된다.
i.setImageResource(mImageIds[position]);
위의 것을 다음과 같이 수정한다.
try {
            URL aURL = new URL(mRemoteImages[position]);
            URLConnection conn = aURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            Bitmap bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
            i.setImageBitmap(bm);
        } catch (IOException e) {
            i.setImageResource(R.drawable.file_not_found);
            Log.e("DEBUGTAG", "Remote Image Exception", e);
        }
R.drawable.file_not_found 는 혹시 웹에서 이미지를 불러오지 못할 경우 화면에 띄워줄 수 있는 이미지를 res/drawable에 넣어주면 되겠다.

여기서 더 추가해볼 만한 것은 웹상의 xml파일을 읽어들여 어플에서 사용할 이미지에 대한 정보 및 이미지를 가져오는 것이다. 이렇게 되면 어플을 수정할 필요없이 웹상의 xml파일을 수정하는 것만으로 앱 내의 이미지 업데이트가 가능해지므로 좀더 유연한 어플이 될 수 있다.

참고한 사이트는 다음과 같다.
http://developer.android.com/guide/topics/security/security.html
http://www.anddev.org/gallery_with_remote_images-t769.html

저작자 표시 비영리 변경 금지

댓글을 달아 주세요