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

HybridApp - 1세대 cordova (카메라, 갤러리앱)

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

<최종화면> hml,js,css로 화면을 구성하고 버튼을 만들 수 있지만, 그것을 Android Studio와 연동하여 휴대폰 기능을 사용할 수 있다. 카메라와 갤러리앱을 실행해보자.


새로 폴더와 패키지, 앱이름을 만들자.

<실행화면>처음 실행 화면은 저렇게 나온다.

기본적으로 코드가 써져 있다. 이제 이것을 지우고 새로 코딩해보자.

index.html에 쓸때 없는 내용은 지우고 새로 만들자.

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
<!DOCTYPE html>
 
<html>
    <head>
        <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
       
        <link rel="stylesheet" href="./jquery.mobile-1.4.5.min.css" />
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <title>Hello World</title>
 
           <!-- JQM library 추가 -->
        <script src="./jquery.min.js"></script>
        <script src="./jquery.mobile-1.4.5.js"></script>
        
        
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
 
    </head>
    <body>
 
        <div data-role="page">
            <div data-role="header" data-position="fixed">
                <h2>Camera Test APP</h2>
            </div>
 
            <div data-role="content">
                <div class="ui-bar ui-bar-b">
                    <h3>Camera use</h3>
                </div>
                <br>
                <img src="" id="img_pic">
            </div>
 
        </div>
 
    </body>
</html>
 
 

index.css와 index.js 안에 적힌 내용은 다 지우자.

<실행 화면>

cmd창에서 일일히 실행하기 전에 웹 브라우저로 확인 가능하다. 웹 브라우저에서 F12눌러서 모바일형으로 확인.

아래에 버튼 두개를 만들어 준다. JQM library로 쉽게 스타일 및 배치 해준다.

나중에 갤러이와 카메라가 보일 사이즈가 가로 화면을 꽉채울 비율로 해놓자.

버튼을 눌렀을 때 기능을 추가하도록 제어할 id를 주자.

이제 휴대폰 기능을 사용하도록 cordova plugin을 설치하자.

우선 작업중인 폴더를 들어가면 plugins 폴더가 있다. 만약 설치가 잘됐다면 아래 경로에 추가가 될 것이다.

https://www.npmjs.com/

 

npm | build amazing things

Build amazing things We're npm, Inc., the company behind Node package manager, the npm Registry, and npm CLI. We offer those to the community for free, but our day job is building and selling useful tools for developers like you. Take your JavaScript devel

www.npmjs.com

 

cmd창에 명령어를 쓰고 다시 아까 폴더를 확인해보자.

폴더가 생긴거와 별개로, 확실히 확인하는 방법이 또 있다.

이제 카메라관련 기능도 사용해보자.

index.js

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
// 문서가 로딩이 되어야 html 요소들을 제어할 수 있으므로
$(document).ready( function(){
 
    //html문서의 로드와는 별개로 디바이스의 준비콜백처리 필요(onResume 같은 역할)
    document.addEventListener('deviceready', onDeviceReady, true);
 
    // 카메라 실행 버튼 click 이벤트
    $('#btn_takePic').click(function(){
        takePic();
    });
 
    // 갤러리앱 실행 버튼 click 이벤트
    $('#btn_getPic').click(function(){
        getPic();
    });
 
});
 
// 디바이스가 준비되면 자동으로 실행되는 콜백함수
function onDeviceReady(){
    // alert(); //웹용 다이얼로그
 
    // 디바이스 고유의 다이얼로그 사용
    // 디바이스 고유의 기능을 사용하고자 한다면 해당 기능 package(library)를 npm에서 다운 받아 plug-in해야함
    navigator.notification.alert('Device Ready',null,'Alert Dialog','ok');
    
}
 
// 사진 or 갤러리 사용 모두 하나의 plugin 사용
// cordova-plugin-camera
 
// 사진찍기
function takePic(){
    navigator.camera.getPicture( 
        function(imgData){ //사진 캡쳐 성공했을 때
            var img=document.getElementById('img_pic');
            img.src=imgData;
 
            $('h3').replaceWith($('<h3>Taken Picktuew</h3>'));
        } ,
        function(message){ //사진 캡쳐 실패했을 때
            alert(message);
        } ,
        {   //옵션
            quality:20,
            destinationType: Camera.DestinationType.FILE_URI,
            saveToPhotoAlbum: true
        } );
}
 
//갤러리앱
function getPic(){
    navigator.camera.getPicture(
        function(imgData){ //사진 캡쳐 성공했을 때
            var img=document.getElementById('img_pic');
            img.src=imgData;
 
            $('h3').replaceWith($('<h3>Taken Picktuew</h3>'));
        } ,
        function(message){ //사진 캡쳐 실패했을 때
            alert(message);
        } ,
        {   //옵션
            quality:20,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType:Camera.PictureSourceType.PHOTOLIBRARY
        } );
}
 
 


<복붙용 코드>

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
48
49
50
51
<!DOCTYPE html>
 
<html>
    <head>
        <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
       
        <link rel="stylesheet" href="./jquery.mobile-1.4.5.min.css" />
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <title>Hello World</title>
 
           <!-- JQM library 추가 -->
        <script src="./jquery.min.js"></script>
        <script src="./jquery.mobile-1.4.5.js"></script>
        
        
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
 
    </head>
    <body>
 
        <div data-role="page">
            <div data-role="header" data-position="fixed">
                <h2>Camera Test APP</h2>
            </div>
 
            <div data-role="content">
                <div class="ui-bar ui-bar-b">
                    <h3>Camera use</h3>
                </div>
                <br>
                <img src="" id="img_pic">
            </div>
 
            <div data-role="footer" data-position="fixed" data-theme="b">
                <div data-role="navbar">
                    <ul>
                        <li><button id="btn_takePic">Take a Picture</button></li>
                        <li><button id="btn_getPic">Get the Picture</button></li>
                    </ul>
                </div>
            </div>
 
        </div>
 
    </body>
</html>
 
 

index.js

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
// 문서가 로딩이 되어야 html 요소들을 제어할 수 있으므로
$(document).ready( function(){
 
    //html문서의 로드와는 별개로 디바이스의 준비콜백처리 필요(onResume 같은 역할)
    document.addEventListener('deviceready', onDeviceReady, true);
 
    // 카메라 실행 버튼 click 이벤트
    $('#btn_takePic').click(function(){
        takePic();
    });
 
    // 갤러리앱 실행 버튼 click 이벤트
    $('#btn_getPic').click(function(){
        getPic();
    });
 
});
 
// 디바이스가 준비되면 자동으로 실행되는 콜백함수
function onDeviceReady(){
    // alert(); //웹용 다이얼로그
 
    // 디바이스 고유의 다이얼로그 사용
    // 디바이스 고유의 기능을 사용하고자 한다면 해당 기능 package(library)를 npm에서 다운 받아 plug-in해야함
    navigator.notification.alert('Device Ready',null,'Alert Dialog','ok');
    
}
 
// 사진 or 갤러리 사용 모두 하나의 plugin 사용
// cordova-plugin-camera
 
// 사진찍기
function takePic(){
    navigator.camera.getPicture( 
        function(imgData){ //사진 캡쳐 성공했을 때
            var img=document.getElementById('img_pic');
            img.src=imgData;
 
            $('h3').replaceWith($('<h3>Taken Picktuew</h3>'));
        } ,
        function(message){ //사진 캡쳐 실패했을 때
            alert(message);
        } ,
        {   //옵션
            quality:20,
            destinationType: Camera.DestinationType.FILE_URI,
            saveToPhotoAlbum: true
        } );
}
 
//갤러리앱
function getPic(){
    navigator.camera.getPicture(
        function(imgData){ //사진 캡쳐 성공했을 때
            var img=document.getElementById('img_pic');
            img.src=imgData;
 
            $('h3').replaceWith($('<h3>Taken Picktuew</h3>'));
        } ,
        function(message){ //사진 캡쳐 실패했을 때
            alert(message);
        } ,
        {   //옵션
            quality:20,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType:Camera.PictureSourceType.PHOTOLIBRARY
        } );
}
 
 

index.css

1
#img_pic { display: block; width: 100%;}

 

반응형

댓글