안드로이드

 

 

 

AndroidManifest.xml


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

 

 

class MainActivity
package com.example.choi.mystudy29_1;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    final static String TAG="MainActivity";
    String urlAddr="";
    Button btnNetCon , btnAsynTask;
    EditText editText;

    ProgressDialog dialog=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnNetCon=(Button)findViewById(R.id.button1);
        editText=(EditText)findViewById(R.id.editText);
        btnAsynTask=(Button)findViewById(R.id.button2);


        btnNetCon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                editText.setText("");
                urlAddr="http://www.sba.seoul.kr";

                //1.첫번째 방법 Thread 를 이용하는 방법
                //다이얼로그 호출
                 dialLogCom();
                MyThread thread=new MyThread();
                thread.start();


            }
        });

        btnAsynTask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                editText.setText("");
                urlAddr="http://www.daum.net";
                //2. 두번째 방법 AsyncTask 를 사용하는 방법
                NetWorkAsyncTask asyncTask =new NetWorkAsyncTask(MainActivity.this, urlAddr, editText);
                asyncTask.execute(100);

            }
        });


    }

    public  void dialLogCom(){
        dialog=new ProgressDialog(MainActivity.this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setTitle("Dialog");
        dialog.setMessage("down......");
        dialog.show();
    }


    class MyThread extends Thread{

        StringBuffer sb;

        public MyThread() {
            sb =new StringBuffer();
        }

        @Override
        public void run() {

            //데이터 불러오기
            contextUrl();

            //데이터 완료후 다이얼로그 닫기
            if(dialog!=null){
                dialog.dismiss();
            }

        }



        public void contextUrl(){


            Log.i(TAG, "contextUrl");


            InputStream is =null;
            InputStreamReader isr =null;
            BufferedReader br=null;


            try {

                URL url=new URL(urlAddr);
                HttpURLConnection connection =(HttpURLConnection)url.openConnection();

                if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){

                    is=connection.getInputStream();
                    isr=new InputStreamReader(is);
                    br=new BufferedReader(isr);

                    String strLine=null;
                    while ((strLine=br.readLine())!=null){

                        sb.append(strLine+"\n");

                        // 다운로드 지연
                        try {
                            //0.001초 지연
                            Thread.sleep(10);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                    Log.i(TAG, "sb :" +sb.toString());

                    // editText 에 데이터를 넣기위해 runOnUiThread 호출
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            editText.append(sb.toString());
                        }
                    });

                }


            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if(br!=null)br.close();
                    if(isr!=null)isr.close();
                    if(is!=null)is.close();

                }catch (Exception e2){
                    e2.printStackTrace();
                }

            }

        }





    }







}











 

 

R.layout.activity_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    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.mystudy29_1.MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:inputType="textMultiLine"
        android:ems="10"
        android:id="@+id/editText"

        android:focusableInTouchMode="false"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/line1" />


    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/line1"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <Button
            android:text="NetWork Connection 1"
            android:layout_width="0dp"

            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:id="@+id/button1"
            android:textAllCaps="false"
            android:textColor="@android:color/background_light"
            android:background="@android:color/holo_orange_dark"
            android:layout_weight="1" />

        <Button
            android:text="NetWork Connection 2"
            android:textAllCaps="false"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/button2"
            android:layout_weight="1"
            android:textColor="@android:color/background_light"
            android:background="@android:color/holo_blue_dark" />

    </LinearLayout>



</RelativeLayout>

 

class NetWorkAsyncTask
package com.example.choi.mystudy29_1;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by choi on 2017-03-17.
 */

public class NetWorkAsyncTask extends AsyncTask<Integer, String, Integer> {


    final static String TAG ="NetWorkAsyncTask";
    Context mContext=null;
    String mAddr;
    ProgressDialog dialog=null;
    EditText editText;

    public NetWorkAsyncTask(Context context, String mAddr, EditText editText) {
          this.mContext=context;
          this.mAddr=mAddr;
          this.editText=editText;

    }


    @Override
    protected void onPreExecute() {
        Log.i(TAG, "onPreExecute()");

        dialog=new ProgressDialog(mContext);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setTitle("Dialog");
        dialog.setMessage("down.....");
        dialog.show();
    }

    @Override
    protected Integer doInBackground(Integer... params) {

        Log.i(TAG, "doInBackground()");
        Log.i(TAG, "params[0] : " +params[0]); //100 출력


        StringBuffer sb =new StringBuffer();
        InputStream is =null;
        InputStreamReader isr =null;
        BufferedReader br=null;

        try {
            URL url =new URL(mAddr);
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(10000);

            if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                is=connection.getInputStream();
                isr=new InputStreamReader(is);
                br=new BufferedReader(isr);

                while (true){
                    String strLine=br.readLine();
                    if(strLine==null)break;
                    sb.append(strLine +"\n");
                }
                Log.i(TAG, "sb:"+sb.toString());

                //onProgressUpdate() 호출
                publishProgress(sb.toString());
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(br!=null)br.close();
                if(isr!=null)isr.close();
                if(is!=null)is.close();

            }catch (Exception e2){
                e2.printStackTrace();
            }
        }

        return null;
    }


    //UI 처리 부분
    @Override
    protected void onProgressUpdate(String... values) {
        Log.i(TAG, "onProgressUpdate()");

        editText.setText(values[0]);
    }



    @Override
    protected void onPostExecute(Integer integer) {
        Log.i(TAG, "onPostExecute()");
        //AsyncTask 종료시 다이얼로그 종료
        dialog.dismiss();
    }


    @Override
    protected void onCancelled() {
        Log.i(TAG, "onCancelled()");
        super.onCancelled();
    }


}

 

 

 

 

 

android

 

about author

PHRASE

Level 60  머나먼나라

경상(卿相, 재상)의 목숨을 고치는 약은 없고, 돈이 있어도 자손의 현명함은 사기 어렵다. -명심보감

댓글 ( 6)

댓글 남기기

작성