본문 바로가기

Study/Programming

안드로이드 네트워크 웹페이지 읽기 예제 - 꼬로미

홧팅2홧팅2


안녕하세요 꼬로미입니다


안드로이드 프로그래밍 네트워크 웹페이지 읽기 예제 포스팅입니다



웹페이지 읽기

                                                                                                  



애플리케이션에서 인터넷에서 텍스트나 이미지 같은 자원들을 다운로드할 필요가 있으며

웹서버가 사용하는 프로토콜은 HTTP이며 가장 기본적인 클래스로 java.net 패키지의 HttpURLConnection을 사용




소스

public class MainActivity extends Activity {


@Override

public void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Button btnDownload =(Button) findViewById(R.id.download);

OnClickListener downloadListener = new OnClickListener() {

public void onClick(View v) {

if(isNetworkAvailable()) {

EditText url = (EditText) findViewById(R.id.url);

DownloadTask downloadTask = new DownloadTask();

downloadTask.execute(url.getText().toString());

} else {

Toast.makeText(getBaseContext(), "Network is not Available", Toast.LENGTH_SHORT).show();

}

}

};

btnDownload.setOnClickListener(downloadListener);

}


private boolean isNetworkAvailable() {

boolean available = false;

ConnectivityManager connMgr =
                           (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

if (networkInfo != null && networkInfo.isAvailable())

available = true;

return available;

}


private String downloadUrl(String strUrl) throws IOException {

String s = null;

byte[] buffer = new byte[1000];

InputStream iStream = null;

try {

URL url = new URL(strUrl);

HttpURLConnection urlConnection = (HttpURLConnection) url

.openConnection();

urlConnection.connect();

iStream = urlConnection.getInputStream();

iStream.read(buffer);

s = new String(buffer);

} catch (Exception e) {

Log.d("Exception while downloading url", e.toString());

} finally {

iStream.close();

}

return s;

}


private class DownloadTask extends AsyncTask<String, Integer, String> {

String s = null;


protected String doInBackground(String... url) {

try {

s = downloadUrl(url[0]);

} catch (Exception e) {

Log.d("Background Task", e.toString());

}

return s;

}


protected void onPostExecute(String result) {

TextView tView = (TextView) findViewById(R.id.text);

tView.setText(result);

Toast.makeText(getBaseContext(),

"Web page downloaded successfully", Toast.LENGTH_SHORT)

.show();

}

}

}



ConncetivityMager 클래스 : 네트워크 연결 상태 감시
    getSystemService() : 다양한 매개변수를 사용가능 하며 여러가지 객체를 얻어올 수 있음
                                    매개변수 표 포스트 : http://promobile.tistory.com/169

AsyncTask<> 클래스를 이용해 스레드를 나눠서 작업

doInBackground(Strung... url) :  새로운 스레드로 배경에서 실행됨

onPostExecute(String result) : 다운로드가 끝나면 실행되며 다운로드된 문자열로 텍스트뷰를 채움



XML 레이아웃

<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" >


    <EditText

        android:id="@+id/url"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:ems="10"

        android:inputType="textUri" >

    </EditText>


    <Button

        android:id="@+id/download"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="DOWN" />


    <TextView

        android:id="@+id/text"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="TextView" />

 

</LinearLayout>



매니페스트 파일 퍼미션 설정

   <uses-permission android:name="android.permission.INTERNET" />

   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />




실행화면


EditText에 정확한 URL을 입력하고 Down 버튼을 클릭시

소스가 다운로드되어 TextView 보여지며 토스트 메시지도 함께 출력



읽어주셔서 감사합니다 오키