본문 바로가기
안드로이드 웹앱 콘테츠 개발자 양성(국비지원)/HybridApp

HybridApp - 0세대 WepApp (갤러이앱 열고, 웹-앱 문자열 전달)

by 차누감 2020. 1. 15.
반응형

<최종 화면> 버튼을 통해 휴대폰 갤러이앱을 열고, 웹과 안드로이드 앱 데이터 전달


빈 액티비티를 만들자.

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
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
<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp">
 
        <WebView
            android:id="@+id/wv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
        <TextView
            android:id="@+id/tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="message"
            android:padding="8dp"
            android:layout_marginTop="8dp"
            android:textStyle="bold"/>
 
        <View
            android:layout_width="match_parent"
            android:layout_height="3dp"
            android:background="#888888"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="16dp"/>
 
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="웹뷰에 메세지 보내기"
            android:textStyle="bold"/>
 
        <EditText
            android:id="@+id/et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:hint="input message"
            android:padding="8dp"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="send"
            android:layout_gravity="right"
            android:onClick="clickSend"/>
    </LinearLayout>
 
</RelativeLayout>
 
 

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
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
package com.example.hybridapptest2;
 
 
 
public class MainActivity extends AppCompatActivity {
 
    WebView wv;
    TextView tv;
    EditText et;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        wv=findViewById(R.id.wv);
        tv=findViewById(R.id.tv);
        et=findViewById(R.id.et);
 
//        웹뷰설절들
        wv.setWebViewClient(new WebViewClient());
        wv.setWebChromeClient(new WebChromeClient());
 
        WebSettings settings =wv.getSettings();
        settings.setJavaScriptEnabled(true);
 
//        ajax기술은 원래 서버에서만 사용가능했었음.
//        안드로이드 안에서 허용하도록 설정할 수 있음.
//        즉, 경로가 http:// 가 아니라 file://이어도 ajax가 동작함
          settings.setAllowUniversalAccessFromFileURLs(true);
 
//          웹뷰와 연결하는 연결자 객체 생성 및 설정
//          2번째 파라미너 : JS에서 이 연결자 객체를 부르는 이름(별명) 지정
            wv.addJavascriptInterface(new WebViewConnector(),"Droid");
 
//          웹뷰가 보여줄 웹문서 로드하기
            wv.loadUrl("file:///android_asset/index.html");
    }
 
    public void clickSend(View view) {       
 
    }
 
}
 
 

웹뷰가 보여줄 웹문서를 만들기 위해 우선 assets 폴더를 만들자.

assets 폴더 안에 index.html 파일을 만들자.

스타일은 간편라게 bootstrap.css 을 이용하겠다.

bootstrap.css
0.19MB

해당 파일을 assets 폴더에 넣자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
 
<!--        부트스트랩 스타일 라이브러리 적용-->
        <link rel="stylesheet" href="bootstrap.css">
    </head>
    <body>
        <div class="container mt-3">
            <h5>Native Java로 보낼 메세지</h5>
            <input type="text" class="form-control mt-3" id="in1" placeholder="input message">
            <button class="btn btn-primary btn-block mt-3">send message to Native Android</button>
 
            <h5 class="mt-5">Native Java로부터 받은 메세지</h5>
            <h6 id="msg" class="mt-3">WAIT......</h6>
 
        </div>
    </body>
 
</html>
 

<실행 화면>

이제 앱에서 입력한 문자열을 웹에서 보여주자.

이제 웹에서 입력한 문자열을 앱에서 보여주자.

이제 갤러이 앱을 여는 버튼을 만들자.


<복붙용 코드>

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
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
<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp">
 
        <WebView
            android:id="@+id/wv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
        <TextView
            android:id="@+id/tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="message"
            android:padding="8dp"
            android:layout_marginTop="8dp"
            android:textStyle="bold"/>
 
        <View
            android:layout_width="match_parent"
            android:layout_height="3dp"
            android:background="#888888"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="16dp"/>
 
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="웹뷰에 메세지 보내기"
            android:textStyle="bold"/>
 
        <EditText
            android:id="@+id/et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:hint="input message"
            android:padding="8dp"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="send"
            android:layout_gravity="right"
            android:onClick="clickSend"/>
    </LinearLayout>
 
</RelativeLayout>
 
 

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
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
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.example.hybridapptest2;
 
 
 
public class MainActivity extends AppCompatActivity {
 
    WebView wv;
    TextView tv;
    EditText et;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        wv=findViewById(R.id.wv);
        tv=findViewById(R.id.tv);
        et=findViewById(R.id.et);
 
//        웹뷰설절들
        wv.setWebViewClient(new WebViewClient());
        wv.setWebChromeClient(new WebChromeClient());
 
        WebSettings settings =wv.getSettings();
        settings.setJavaScriptEnabled(true);
 
//        ajax기술은 원래 서버에서만 사용가능했었음.
//        안드로이드 안에서 허용하도록 설정할 수 있음.
//        즉, 경로가 http:// 가 아니라 file://이어도 ajax가 동작함
          settings.setAllowUniversalAccessFromFileURLs(true);
 
//          웹뷰와 연결하는 연결자 객체 생성 및 설정
//          2번째 파라미너 : JS에서 이 연결자 객체를 부르는 이름(별명) 지정
            wv.addJavascriptInterface(new WebViewConnector(),"Droid");
 
//          웹뷰가 보여줄 웹문서 로드하기
            wv.loadUrl("file:///android_asset/index.html");
    }
 
    public void clickSend(View view) {
//        웹뷰에서 보여주는 index.html안에 있는 특정함수
//        (프로그래머가 만든 함수 : setReceivedMessage() )를 호출해서 값을 전달
//        Native Java에서 hrml의 dom요소를 직접 제어할 수 없음
//        웹뷰에 보낼 글씨
        String msg=et.getText().toString();
        wv.loadUrl("javascript:setReceivedMessage('"+msg+"')");
        et.setText("");
 
    }
 
    //웹뷰의 Javascript와 통신을 담당할 중계자(위임자, 연결자) 클래스 정의
    class WebViewConnector{
//        javascript에서 호출할 메소드
//        이 메소드를 javascript에서 호출할 수 있게 하려면 특별한 어노테이션을 지정해야함
 
        @JavascriptInterface
        public void setTextView(String msg){
            tv.setText(msg);
        }
        @JavascriptInterface
        public void openGallery(){
            Intent intent=new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivity(intent);
        }
 
    }
}
 
 

index.html

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
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
 
<!--        부트스트랩 스타일 라이브러리 적용-->
        <link rel="stylesheet" href="bootstrap.css">
 
<!--        스크릡트 코드-->
        <script>
        //Native Java에서 호출할 함수 - 파라미터로 값 전달받음
        function setReceivedMessage(msg){
            document.getElementById('msg').innerHTML=msg;
        }
 
        //Native Java에게 메세지 보내는 함수
         function sendMessageToNative(){
            //input요소에 써 있는 보낼 메세지 얻어오기
            var msg= document.getElementById('in1').value;
 
            //안드로이드와 연결하기!
            //Java에서 연결자로 만든 객체의 별명('Droid')를 통해 원하는 기능 수행
            window.Droid.setTextView(msg);
         }
          //Native Java에게 갤러리 앱 실행 요청
            function openGallery(){
                Droid.openGallery();
            }
        </script>
 
    </head>
    <body>
        <div class="container mt-3">
            <h5>Native Java로 보낼 메세지</h5>
            <input type="text" class="form-control mt-3" id="in1" placeholder="input message">
            <button class="btn btn-primary btn-block mt-3" onclick="sendMessageToNative()">send message to Native Android</button>
 
            <h5 class="mt-5">Native Java로부터 받은 메세지</h5>
            <h6 id="msg" class="mt-3">WAIT......</h6>
 
            <button class="btn btn-success btn-block mt-5" onclick="openGallery()">open Gallery</button>
 
        </div>
    </body>
 
</html>
 

 

반응형

댓글