admin

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

PhoneGap(cordova) API를 이용하여 하드웨어에 접근하는 방법에 대하여 설명하겠습니다.

우선 하드웨어에 접근하려면 plugin을 설치 해야 합니다.

설치 방법은 2가지 방법이 있는데 

첫쨰 cordova를 이용하여 설치하는 방법

둘쨰 node.js설치 후 plugman을 이용하여 설치 하는 방법이있습니다.


여기서는 cordova을 이용하여 plugin을 설치 하겠습니다.

1. 만들 프로젝트 폴더로 이동합니다.

  cordova create MyFunkyApp

cd MyFunkyApp

cordova platform add ios

cordova emulate ios

이렇게 App을 만들었다면 MyFunkyApp 폴더로 이동합니다

$ cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-camera.git 을 실행하여 plugin을 설치 합니다.

[Error: Error fetching plugin: Error: "git" command line tool is not installed: make sure it is accessible on your PATH.]

이렇게 메세지가 나온다면 git가 설치가 되지 않아서 보여지는 에러니 

https://help.github.com/articles/set-up-git에서 다운받아 설치 합니다.



이제 

cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-camera.git

다시 실행합니다.

정상적으로 실행 되었다면 ios>config.xml파일을 열어

    <feature name="Camera">

        <param name="ios-package" value="CDVCamera" />

    </feature>

카메라 관련 설정이 추가되어있는지 확인합니다.

마찬가지로 안드로이드도 프로젝트>/res/xml/config.xml에 

    <feature name="Camera">

        <param name="android-package" value="org.apache.cordova.camera.CameraLauncher" />

    </feature>

가 추가 되어있는것을 확인 할 수 있습니다.

API plugin URL

cordova-plugin-battery-status   https://git-wip-us.apache.org/repos/asf/cordova-plugin-battery-status.git

cordova-plugin-camera   https://git-wip-us.apache.org/repos/asf/cordova-plugin-camera.git

cordova-plugin-console   https://git-wip-us.apache.org/repos/asf/cordova-plugin-console.git

cordova-plugin-contacts   https://git-wip-us.apache.org/repos/asf/cordova-plugin-contacts.git

cordova-plugin-device   https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git

cordova-plugin-device-motion (accelerometer)   https://git-wip-us.apache.org/repos/asf/cordova-plugin-device-motion.git

cordova-plugin-device-orientation (compass)   https://git-wip-us.apache.org/repos/asf/cordova-plugin-device-orientation.git

cordova-plugin-dialogs   https://git-wip-us.apache.org/repos/asf/cordova-plugin-dialogs.git

cordova-plugin-file   https://git-wip-us.apache.org/repos/asf/cordova-plugin-file.git

cordova-plugin-file-transfer   https://git-wip-us.apache.org/repos/asf/cordova-plugin-file-transfer.git

cordova-plugin-geolocation   https://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation.git

cordova-plugin-globalization   https://git-wip-us.apache.org/repos/asf/cordova-plugin-globalization.git

cordova-plugin-inappbrowser   https://git-wip-us.apache.org/repos/asf/cordova-plugin-inappbrowser.git

cordova-plugin-media   https://git-wip-us.apache.org/repos/asf/cordova-plugin-media.git

cordova-plugin-media-capture   https://git-wip-us.apache.org/repos/asf/cordova-plugin-media-capture.git

cordova-plugin-network-information   https://git-wip-us.apache.org/repos/asf/cordova-plugin-network-information.git

cordova-plugin-splashscreen   https://git-wip-us.apache.org/repos/asf/cordova-plugin-splashscreen.git

cordova-plugin-vibration   https://git-wip-us.apache.org/repos/asf/cordova-plugin-vibration.git


이제 추가 했으니 카메라 API sample을 작성해봅시다.

<!DOCTYPE html>
<html>
  <head>
    <title>Capture Photo</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    var pictureSource;   // picture source
    var destinationType; // sets the format of returned value

    // Wait for device API libraries to load
    //
    document.addEventListener("deviceready",onDeviceReady,false);

    // device APIs are available
    //
    function onDeviceReady() {
        pictureSource=navigator.camera.PictureSourceType;
        destinationType=navigator.camera.DestinationType;
    }

    // Called when a photo is successfully retrieved
    //
    function onPhotoDataSuccess(imageData) {
      // Uncomment to view the base64-encoded image data
      // console.log(imageData);

      // Get image handle
      //
      var smallImage = document.getElementById('smallImage');

      // Unhide image elements
      //
      smallImage.style.display = 'block';

      // Show the captured photo
      // The inline CSS rules are used to resize the image
      //
      smallImage.src = "https://t1.daumcdn.net/cfile/tistory/233A9D3A56EB11EE2E" + imageData;
    }

    // Called when a photo is successfully retrieved
    //
    function onPhotoURISuccess(imageURI) {
      // Uncomment to view the image file URI
      // console.log(imageURI);

      // Get image handle
      //
      var largeImage = document.getElementById('largeImage');

      // Unhide image elements
      //
      largeImage.style.display = 'block';

      // Show the captured photo
      // The inline CSS rules are used to resize the image
      //
      largeImage.src = imageURI;
    }

    // A button will call this function
    //
    function capturePhoto() {
      // Take picture using device camera and retrieve image as base64-encoded string
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
        destinationType: destinationType.DATA_URL });
    }

    // A button will call this function
    //
    function capturePhotoEdit() {
      // Take picture using device camera, allow edit, and retrieve image as base64-encoded string
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
        destinationType: destinationType.DATA_URL });
    }

    // A button will call this function
    //
    function getPhoto(source) {
      // Retrieve image file location from specified source
      navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
        destinationType: destinationType.FILE_URI,
        sourceType: source });
    }

    // Called if something bad happens.
    //
    function onFail(message) {
      alert('Failed because: ' + message);
    }

    </script>
  </head>
  <body>
    <button onclick="capturePhoto();">Capture Photo</button> <br>
    <button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
    <button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
    <button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
    <img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
    <img style="display:none;" id="largeImage" src="" />
  </body>
</html>

안드로이드 프로젝트에서 카메라 기능을 on시키고 확인하면 잘 동작 하는것을 확인 할 수 있습니다.

참고  URL

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Eclipse JSDT jQuery(jQuery Code Assist) 설정하기

Menu bar > Help > Eclipse Marketplace.. 를 선택 실행합니다.

검색어를 JSDT로 입력하고 검색 버튼을 클릭하고 JSDT jQuery를 선택 후 install 버튼을 클릭하여 설치 합니다.


설치가 완료되면 Project Explore에서 프로젝트를 선택하고 오른쪽마우스(Mac은 control + 마우스크)하여 Properties를 클릭합니다.

javaScript >  include Path를 선택합니다.

Libraries 탭에서 Add JavaScript Library를 선택하고 아래 그림과 같이 jQuery Library를 선택 후 Next버튼을 클릭합니다.

jQuery Version을 선택하고 Finish 버튼을 클릭합니다.


그럼 새문서를 만들어서 테스트를 해봅시다.


336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

첫 하이브리드 앱(Ajax JSONP을 이용한 비동기 서버 호출)


Mac 환경설정 > Mac cordova설치 및 Eclipse 연동에서 작성한 helloworld  Project를 이용하여 로그인 페이지를 작성하겠습니다.

흐름은 아래 그림과 같으며 서버는 로컬에서 Eclipse로 구동하여 테스트 했습니다.

소스코드는 cordova3.0.5을 이용하여 생성했습니다.

Project Folder

Xcode


안드로이드(Eclipse)



1.login.html페이지 작성.

  화면

소스코드

<!doctype html>

<html>

    <head>

        <meta charset="UTF-8">

            <title>Untitled Document</title>

            <link rel="stylesheet" href="./css/jquery.mobile-1.3.2.min.css" />

            <script src="./js/jquery-1.9.1.js"></script>

            <script src="./js/jquery.mobile-1.3.2.js"></script>

            <script src="./js/common.js"></script>

            <script type="text/javascript">

                $(document).on( 'click', '#checkLogin', function(){

                               checkLogin($('#name').val(),$('#password').val());

                               });

                function checkLogin(id,pass) {

                    var params = {ID:id

                        ,PASS:pass

                        ,AUTOLOGIN:'N'

                    };

                    $.ajax({

                           type: 'GET',

                           url: "http://172.16.1.50:8080/myweb/cb.jsp",

                           data : params,

                           contentType: "Content-Type: application/javascript",

                           dataType: "jsonp",

                           jsonp : "callback",

                           jsonpCallback: "jsonpCallback",


                           error: function (xhr, ajaxOptions, thrownError) {

                           alert("Error: " + xhr.status + "\n" +

                                 "Message: " + xhr.statusText + "\n" +

                                 "Response: " + xhr.responseText + "\n" + thrownError);

                           }

                           });

                }

                function jsonpCallback(data){

                   // alert('jsonpCallback1:___'+JSON.stringify(data));

                    if(data.RESULT=='2'){

                        $.mobile.changePage('./main.html');

                    }else{

                        alert('not user... please retry..');

                    }

                }

                </script>

    </head>

    <body>

        <div id="test-page" data-role="page">

            <div data-role="header">

                <h1><a data-ajax="false" href="/">Login</a></h1>

            </div>

            <div data-role="content">

                <div data-role="fieldcontain">

                    <label for="name">Name:</label>

                    <input id="name" type="email" name="name" />

                </div>

                <div data-role="fieldcontain">

                    <label for="password">Password:</label>

                    <input id="password" type="password" name="password" />

                </div>

            </div>

            <button type="button" id="checkLogin" name="checkLogin" >LOGIN</button>

        </div>

    </body>

</html>



2.main.html 페이지 작성.

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

Main page....

</body>

</html>


3.Server Module 작성 

Menu Bar > File > New > Dynamic Web Project 을 선택하여 새로운 web프로젝트를 생성합니다.

그리고 WebContent하위에 cb.jsp파일을 생성하고 아래와 같이코딩을 합니다.

 <%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>

<%

String cb = request.getParameter("callback");

String id = request.getParameter("ID");

String pass = request.getParameter("PASS");

String auto = request.getParameter("AUTOLOGIN");


/*

login check..

   if login OK return '2' 

   else '1'

*/


String result = "2";


%>

<%=cb %>({'RESULT':'<%=result %>'})



마지막으로config.xml의 access 설정을 변경합니다.

 프로젝트의 config.xml을 열어서 <access origin="172.0.0.1*" />이부분을 

<access origin="*" />로 변경하여 모든 접속을 허용하도록 합니다.

위치는 Xcode는 프로젝트/config.xml(프로젝트/www/config.xml이 아님)

 android Eclipse는 프로젝트/res/xml/config.xml 찾아서

을 변경합니다.


이제 Xcode에서 프로젝트 실행을 클릭하고 로그인하여 정상적으로 되는지 확인하자


 



이렇게 메인 페이지까지 나오면 정상적으로 된것이다 .. 

이제 안드로이드도 확인을 해봅시다.

프로젝트 > Debug As > Android Application을 선택 합니다.

테스용디바이스를 선택 합니다.

이미 구동중인 device가 있으면 아래와 같이 화면에 보이고 아니면 아래의 "Launch a new Android Virtual Device"에서 선택하여 실행합니다.





안드로이드도 정상적으로 로그인되는것을 확인 합니다.