안드로이드

 

 

 

 

class MainActivity
package com.example.choi.ex05_network;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    public void onClick(View v){

        Intent intent=null;
        switch (v.getId()){
            case R.id.button1:
                intent=new Intent(this, HtmlActivity.class);
                break;
        }
        startActivity(intent);
    }



}

 

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/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.ex05_network.MainActivity">

    <Button
        android:text="html 소스 보기"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button1"
        android:onClick="onClick"
        />
</RelativeLayout>

 

class HtmlActivity
package com.example.choi.ex05_network;

import android.content.Intent;
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.EditText;

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

//네트워크 연결 작업시 주의사항
//1.반드시 백그라운드 스레드로 작업
//2.백그라운드 스레드에서는 메인화면 접근 금지
public class HtmlActivity extends AppCompatActivity
    implements  Runnable{
    //1.변수 선언
    Button button1, button2;
    EditText edit1;
    String str;
    final String spring_url ="http://192.168.0.2:2424/";

// Alt + Enter
//android.os.Handler
// 핸들러 : 백그라운드 스레드와 메인스레드의 통신을 담당
    Handler handler=new Handler(){
    //Alter+Insert , Override Methods
// 백그라운드 스레드에서 전달된 메시지를 처리하는 method
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        edit1.setText(str);
      }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.html);
        //2.위젯 생성
        button1=(Button)findViewById(R.id.button1);
        button2=(Button)findViewById(R.id.button2);
        edit1=(EditText)findViewById(R.id.edit1);

        //3. 이벤트 처리

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//메인스레드 외에 백그라운드에서 실행되는 스레드 추가
                Thread th=new Thread(HtmlActivity.this);
                th.start(); //run() 실행 됨

            }
        });


        //웹 뷰로 보기
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(HtmlActivity.this, WebView1.class);
                intent.putExtra("spring_url", spring_url);
                startActivity(intent);
            }
        });

    }


    //Alt+Insert , Implement Methods
    @Override
    public void run() {
       // http://192.168.0.2:2424/
        str=download();
        //에러가 발생함(백그라운드 스레드에서는 메인 UI를 수정할 수 없음/
        //메니페스트 인터넷 권한 설정
        //에러 : Only the original thread that created a view hierarchy can touch its views.
        //edit1.setText(str);
        // 따라서,
        //핸들러에게 메시지 전달
        // sendEmptyMessage( 핸들러에게 전달할 메시지)
        handler.sendEmptyMessage(0);
    }

    String download(){
        StringBuffer sb =new StringBuffer();
        try{
            //웹서버의 주소 (호출할 주소)
            URL url =new URL(spring_url);
            //url 에 접속
            HttpURLConnection conn =(HttpURLConnection)url.openConnection();

            if(conn!=null) {
                conn.setConnectTimeout(5000);//5초 밀리 세컨드 5초가 지나면 연결을 끊겠다.
                conn.setUseCaches(false);// 캐시 사용 x
           // http status code 상태코드, 200 - success
                if(conn.getResponseCode()==200){
            // conn.getInputStream() InputStream을 리턴받음
                    BufferedReader br =new BufferedReader(
                            new InputStreamReader(conn.getInputStream(), "UTF-8"));
                    //for(;;){ //무한 반복
                      while(true){
                        String line=br.readLine(); //한 줄 읽기
                        //더 이상 내용이 없으면 루프 종료
                        if(line==null) break;
                        sb.append(line+"\n");
                    }
                    br.close();//버퍼닫기
                }
                conn.disconnect();// 연결 종료
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sb.toString();
    }



}







 

html
<?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/html"
    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.HtmlActivity">

    <Button
        android:text="다운로드"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/button1" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/button1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/edit1"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:text="웹뷰"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/edit1"
        android:layout_toEndOf="@+id/button1"
        android:layout_marginStart="13dp"
        android:id="@+id/button2" />
</RelativeLayout>

 

 

class WebView1
package com.example.choi.ex05_network;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.webkit.WebView;

public class WebView1 extends AppCompatActivity {

    WebView webView1;


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

        webView1=(WebView)findViewById(R.id.webview1);

        Intent intent=getIntent();
        String spring_url=intent.getExtras().getString("spring_url");

        //자바스크립트 허용
        webView1.getSettings().setJavaScriptEnabled(true);
        //스크롤바 없애기
        webView1.setHorizontalScrollBarEnabled(false);
        webView1.setVerticalScrollBarEnabled(false);

        webView1.loadUrl(spring_url);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView1.canGoBack()) {
            webView1.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }





}

 

web_view1
<?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/web_view1"
    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.WebView1">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:layout_alignParentStart="true"
        android:id="@+id/webview1" />


</RelativeLayout>

 

 

AndroidManifest.xml

 


    <!-- 인터넷 접속 권한 추가 -->
    <uses-permission android:name="android.permission.INTERNET" />

 

app  android Device 에서 DATA 보기 설정 

 

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.choi.ex05_network"
        minSdkVersion 23
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    testCompile 'junit:junit:4.12'
}

 

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

우리가 사는 환경은 우리가 만들어 가는 것이다. 내가 바뀔 때 인생도 바뀐다! -앤드류 매튜스

댓글 ( 4)

댓글 남기기

작성