2015년 6월 24일 수요일

Android Webview, Gear 상에서의 GPS 개발 관련 정리

[Geolocation API 사용을 위한 Android Webview 설정]


Android Webview 내에서 Geolocation API를 사용하려면 아래와 같은 설정이 필요하다.

참고
http://stackoverflow.com/questions/5329662/android-webview-geolocation


1. Android app에서 location 관련 permission 명시

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


2. Geolocation API 사용을 위한 Webview 설정

: JavaScript enable, Geolocation enable, Geolocation caching을 위한 DB path 설정
http://developer.android.com/reference/android/webkit/WebSettings.html

webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setGeolocationEnabled(true);
webView.getSettings().setGeolocationDatabasePath(Context.getFilesDir().getPath());


아래 HTML5 관련 설정들은 실제 Geolocation API에 영향을 주는지 확인은 안했지만
사용하는 webview에서 사용하고 있었던 것이라 혹시나 안된다면 아래 것도 추가를..

webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAppCacheEnabled(true);


3. 위치 정보 접근 허용을 위한 알림 및 허용 처리

: 위치정보 접근 허용을 위한 WebChromeClient.onGeolocationPermissionsShowPrompt() 구현
http://developer.android.com/reference/android/webkit/WebChromeClient.html#onGeolocationPermissionsShowPrompt(java.lang.String, android.webkit.GeolocationPermissions.Callback)

아래 예제에서는 그냥 사용자에게 prompt를 보여주지 않고 자동으로 위치정보를 접근하게 한예제이니 사용자에게 알릴 필요가 있다면 여기서 알려야함.

webView.setWebChromeClient(new WebChromeClient() {
 public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
    callback.invoke(origin, true, false);
 }
});


위 방법들을 사용하면 Android webview 내에서 Geolocation API를 사용할 수 있다.


[Geolocation APIs - getCurrentPosition, watchPosition]

: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation

getCurrentPosition, watchPosition에 대한 설명이다.

둘다 위치 정보를 얻기 위해 hardware를 사용하므로 비동기적(asynchronous)으로 callback을 통해 결과를 전달하는 것은 동일하지만 getCurrentPosition은 일회적으로 현재 위치를 제공하는 것이고 watchPosition은 위치의 변화가 있을 경우 변경된 좌표를 제공한다는 것이 다른 점이다.
또한 아래 설명의 굵은 글씨들을 참고하면 watchPosition이 이전 좌표를 기반하여 별도의 기술을 사용하여 좀 더 정확한 좌표를 제공하려 하는 것 같다. 아마도 Android webview에서 database path를 설정하는 것도 이런 연유에서일 것으로 추측..
하지만 watchPosition은 위치 변화 뿐만아니라 좀 더 정확한 위치가 설정 되어도 알려줘서 모르겠지만 수신 받은 위치를 좀 걸러내야 할 필요성이 있는 것 같다. 특히 GPS + 네트워크 둘다 사용할 경우 종종 부정확한 위치가 전달 된다.

(발췌, MDN Using Geolocation )

Getting the current position

To obtain the user's current location, you can call the getCurrentPosition() method. This initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position.


Watching the current position

If the position data changes (either by device movement or if more accurate geo information arrives), you can set up a callback function that is called with that updated position information. This is done using the watchPosition() function, which has the same input parameters as getCurrentPosition(). The callback function is called multiple times, allowing the browser to either update your location as you move, or provide a more accurate location as different techniques are used to geolocate you. The error callback function, which is optional just as it is for getCurrentPosition(), can be called repeatedly.


이와 비슷한 내용의 Answer와 예제 샘플은 다음과 같다.

watchPosition API 사용 샘플
watchPosition을 계속 실행하면 아무래도 GPS 관련 hardware를 계속 사용하게 되므로 일정시간 watchPosition을 사용하되 몇초 단위로 끊어서 사용하고 있음.
: http://stackoverflow.com/questions/8552186/how-to-get-html5-position-in-webview-updated-at-a-regular-interval-with-fine-ac


Platform, OS 별 Geolocation 사용 예제
: http://docs.phonegap.com/en/edge/cordova_geolocation_geolocation.md.html

HTML5 Geolocation API 표준 문서
: http://www.w3.org/TR/geolocation-API/#geolocation_interface

이것도 참고하시라...
: http://www.andygup.net/how-accurate-is-html5-geolocation-really-part-2-mobile-web/


[Gear에서의 GPS 사용]



- GPS feature를 제공하는 제품들은 Gear2 neo, GearS가 있는 것으로 알고 있지만
   Gear 2에서는 Geolocation API를 사용할 수 없다. (Tizen 2.3 기준)

 . 그래서 GPS 센서가 없는 모델들은 SAP(Samsung Accessory Protocol)을 사용해서 mobile의 GPS 좌표를 사용하더라..
 (http://www.codeproject.com/Articles/830305/Speedometer-for-Galaxy-Gear-Tizen-Based)


- GearS는 GPS 센서가 있지만 GPS 센서, 네트워크 위치를 사용해서 위치를 파악한다.
 . GPS 센서만 사용하고자 한다면 설정 > 연결 > GPS만 사용 에 체크

 . FakeGPS를 사용하여 GearS GPS app디버깅 방법
  : SIM 카드가 없는 상태에서 설정 > 연결 > GPS만 사용 체크 해제
    GearS와 연결된 mobile의 GPS 끄고 fake GPS로 GPS 좌표 설정
    다만 Gear GPS센서가 동작이 안되는 상태에서 가능하므로 실내에서 가능하다..


[T map OpenAPIs]



https://developers.skplanetx.com/apidoc/kor/tmap/

타 통신사에서는 그림의 떡같은 T map인 관계로 별로 좋아하지 않았지만
이번에 Geolocation 관련 API을 찾다 보니 감사하게도 Open API들을 제공하고 있었다.
제공되는 API들도 꽤나 다양해서 GPS app 개발 시 상당히 유용할 것으로 보인다.

REST API를 사용해서 몇개를 사용해 봤는데 아래 사항은 지켜야 정상 응답을 하더라.

- url에서 callback, gizAppId는 값이 없어도 파라미터로 존재해야 한다.

예를 들어 경로 안내 API를 사용하려면
: https://developers.skplanetx.com/apidoc/kor/t-map/course-guide/geojson/

https://apis.skplanetx.com/tmap/routes?version=1&bizAppId={bizAppId}&callback={callback}

위와 같은 URL을 사용해야 하는데 bizAppId와 callback은 optional 항목이다.
하지만 bizAppid와 callback을 생략하고 ?version=1 만 적으면 정상 응답이 오지 않더라.
?bizAppId=&callback=&version=1 이렇게 적어 호출하니 정상응답.


- content type 설정

REST API 호출(HTTP request시) content type을 "Content-Type: application/x-www-form-urlencoded"로 설정해야 해서 jquery의 $.ajax()를 사용 시 header param으로 명시해야 한다.

2015년 6월 22일 월요일

[Links] GPS 관련 정보들 모음. 위도, 경도 등등

GPS 관련 앱 개발로 관련 내용 좀 찾아봄.

[Geographic coordinate system]

: http://en.wikipedia.org/wiki/Geographic_coordinate_system

  . Latitude(위도), Longitude(경도)
  . 완전한 구형이 아닌 지구의 형태로 인해 여러가지 좌표계에 대한 설명을 확인 필요.



중고등학교에서 배운 내용이지만
위도는 적도(0)를 기준으로 위아래를 각 90도로 나눈 것이고 대체적으로 간격이 비슷하지만 경도는 Greenwich를 기준으로 지구를 각 360도 방향으로 세로로 나눈것이라 위도에 따라서 간격이 다르다.
그래서 경위도 기준으로 거리를 거리를 계산할 경우 경도와 위도의 특징을 생각해서 계산해야 하므로 다소 수식을 써서 계산이 필요하다.


경위도 좌표 표시의 다양한 방법 by 이마운틴
: http://www.emountain.co.kr/atl/view.asp?a_id=4054


경도와 위도로 거리와 위치를 알아보는 방법
상세한 수치는 좀 다르지만 대략적으로 쉽게 설명한 글
: http://m.blog.daum.net/esikhong/17163754


T map API 가이트 by SK 플래닛
https://developers.skplanetx.com/apidoc/kor/tmap/reference/

(T map API 가이드에서 발췌)
지도상에 위치를 표현 하기 위해 좌표를 사용 합니다.
우리가 많이 들어본 “동경132 북위 37”은 경위도 좌표계이며 용도에 따라 수 많은 좌표계가 존재 합니다.
T map Open API에서 제공하는 주요 좌표계는 다음과 같습니다.
① EPSG:3857 : Google Mercator 좌표계. EPSG:900913으로 사용되기도 합니다. 900913은 알파벳 GOOGLE과 비슷한 숫자의 조합으로 특별한 뜻을 가지고 있지는 않습니다.
② EPSG:4326 : WGS84 좌표계. 구글 Earth가 사용하고 있는 좌표입니다.
③ KATECH : 국내에서 자동차 내비게이션 시스템 용으로 개발된 좌표계로 KATEC 또는 KATECH 으로 표기하고 있습니다. 과거 국내 포탈 지도 서비스에서 대부분 이 좌표계를 사용했으며 현재의 지도 서비스는 EPSG:3857또는 EPSG:4326을 기본으로 하는 추세 입니다.
서울 광장의 위치를 각각의 좌표계로 나타내면 다음과 같습니다.
- EPSG3857 : Lat: "4518258.6620310" , Lon: "14135199.7637174"
- WGS84 : Lat: "37.5657321", Lon: "126.9786599"
- KATECH : Lat: "551988.4373341", Lon: "309969.0505621"


[GPS]


GPS 개요 by 국토지리정보원
http://sd.ngii.go.kr/sub/gps/gps_outl.jsp?serv_cd=5&mmenu=1&smenu=1

Global Positioning System

간단히 보면 24개의 위성들을 통해서 측위와 시간 정보를 얻기 위한 시스템이며 군사목적으로 개발되었으나 대한항공 007편 격추사건을 통해서 민간에 개방되었음. GPS는 미국에서 운용되는 시스템이고 그외 러시아, 유럽에서 운용되는 시스템이 있다고 함.


대한항공 007편 격추 사건 (보면 볼수록 안타깝다.)
https://ko.wikipedia.org/wiki/%EB%8C%80%ED%95%9C%ED%95%AD%EA%B3%B5_007%ED%8E%B8_%EA%B2%A9%EC%B6%94_%EC%82%AC%EA%B1%B4
https://www.youtube.com/watch?v=10O3fKZBxz0

After Korean Air Lines Flight 007, a Boeing 747 carrying 269 people, was shot down in 1983 after straying into the USSR's prohibited airspace,[22] in the vicinity of Sakhalin and Moneron Islands, President Ronald Reagan issued a directive making GPS freely available for civilian use, once it was sufficiently developed, as a common good.[23]

그외 러시아, 유럽 시스템 소개
This article is about the American system. For the Russian equivalent, see GLONASS. For the European equivalent, see GALILEO. For other similar systems, see GNSS.


[좌표 기반 계산 방법들]


좌표 주변 반경을 계산 하는 방법에 대한 설명
보통 GPS 좌표를 기반해서 두 위치간 거리 측정, 좌표 주위 m 반경 내 있는 좌표들 확인등을 많이 하게 되는데 이를 위한 계산 방법 및 소스코드를 제공한다.
특히나 경도의 특성에 따라 제대로된 계산식을 구성하는 설명이 아주 잘 되어 있어 필독!
: http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates

3.3 Computing the Minimum and Maximum Longitude – the Correct Way

Figure 1: Tangent meridians to the query circle [1]
Moving along a circle of latitude in order to find the minimum and maximum longitude does not work at all as you can see in figure 1: The points on the query circle having the minimum/maximum longitude, T1 and T2, are not on the same circle of latitude as M but closer to the pole. The formulae for the coordinates of these points can be found in a good math handbook like [1]. They are:
latT = arcsin(sin(lat)/cos(r)) = 1.4942(5)
lonmin = lonT1 = lon - Δlon = -1.8184(6)
lonmax = lonT2 = lon + Δlon = 0.4221(7)
where
Δlon = arccos( ( cos(r) - sin(latT) · sin(lat) ) / ( cos(latT) · cos(lat) ) )
      = arcsin(sin(r)/cos(lat)) = 1.1202(8)
Note that special care must be taken if the 180th meridian is within the query circle. See section 3.4 for details.


좌표 기반 계산 방법들을 설명하고 구현한 JavaScript 기반 코드
용도에 따라 참고해서 사용하면 될 듯 함.
: http://www.movable-type.co.uk/scripts/latlong.html

GPS좌표 <-> 도분초 변환방법
: http://en.wikipedia.org/wiki/Geographic_coordinate_conversion

(Wikipedia 발췌)
Informally, specifying a geographic location usually means giving the location's latitude and longitude. The numerical values for latitude and longitude can occur in a number of different formats:[2]
  • degrees minutes seconds: 40° 26′ 46″ N 79° 58′ 56″ W
  • degrees decimal minutes: 40° 26.767′ N 79° 58.933′ W
  • decimal degrees: 40.446° N 79.982° W
There are 60 minutes in a degree and 60 seconds in a minute. Then to convert from a degrees minutes seconds format to a decimal degrees format, one may use the formula
 \rm{decimal\  degrees} = \rm{degrees} + \rm{minutes}/60 + \rm{seconds}/3600.
To convert back from decimal degree format to degrees minutes seconds format,
 \begin{align}
  \rm{degrees} & = \lfloor\rm{decimal\  degrees}\rfloor \\
  \rm{minutes} & = \lfloor 60*(\rm{decimal\  degrees} - \rm{degrees})\rfloor  \\
  \rm{seconds} & = \lfloor 3600*(\rm{decimal\  degrees} - \rm{degrees} - \rm{minutes}/60)\rfloor \\
  \end{align}
where the notation \lfloor x \rfloor means take the integer part of x and is called a floor function.

2015년 5월 13일 수요일

Tizen WebView 사용 방법 정리, 설정, page 관련 signal, navigation policy 관리

Tizen Native app 개발 중 WebView를 사용하다 답답해서 정리함.

Tizen에서 제공하는 webview는 ewebkit2 기반이라고 한다.
자세한 내용과 간단한 사용 방법은 아래 링크 참고

Hello ewebkit?
: http://bunhere.tistory.com/m/post/417

Tizen WebView tutorial
https://developer.tizen.org/documentation/tutorials/native-application/web

Tizen WebView API reference
https://developer.tizen.org/dev-guide/2.3.0/org.tizen.native.mobile.apireference/group__WEBVIEW.html


Tizen document를 봐도 간단히 page만 loading하는 수준으로만 설명 되어 있고
그리고 몇가지 생각 나는 것은

- Tizen 2.2 platform API 대비 API 수준이 퇴화 한 것 같다.
 : 하나의 예로 WebView -> Native Interface가 없어졌음.

- WebView 내 page의 디버깅할 방법이 없다.
 : console log를 확인할 방법이 없고 안드로이드 처럼 크롬 개발자 도구 연동도 못한다.

- Documentation이 부실하다.
 : 예로 API reference상의evas_object_smart_callback_add()를 사용해서 처리하는 signal에 대해서는  signal definition과 argument type만 나오고 어떻게 사용하는지는 알 수 없다.


암튼... 삽질 하면서 몇가지 알게 된 것과
일반적인 Tizen Webview 사용 방법을 정리함.


[User agent 설정, Javascritp enable, cookie 사용 설정]

이부분은 API reference에 나와 있어서 쉽게 사용할 수 있는 부분임.

// user agent 설정
ewk_view_user_agent_set(ewk_view, "사용하고 싶은 USER AGENT");
Ewk_Settings* settings = ewk_view_settings_get(ewk_view);
// javascritp 사용 설정
ewk_settings_javascript_enabled_set(settings, true);

// 모든 cookie 사용 설정
  if(NULL != ewk_view_context_get(ewk_view) &&
NULL != ewk_context_cookie_manager_get(ewk_view_context_get(ewk_view)))
{
ewk_cookie_manager_accept_policy_set(ewk_context_cookie_manager_get(ewk_view_context_get(ewk_view)), EWK_COOKIE_ACCEPT_POLICY_ALWAYS);
}

근데.. webview 내에서 cookie를 설정할 때
webview 내의 web page에서 javascript로 cookie를 설정할 경우는 생성이 되지만
native에서 webview로 javascript execute로 cookie를 설정할 경우는 잘 안된다.

그리고 안드로이드는 platform 차원에서 cookie를 관리하는 cookie manager가 있지만
Tizen은 그런 것 없다. 만약 일반 브라우저에서 로그인 후 생성된 cookie를 동기화 해야할 경우가 있다면.... 방법을 모르겠다.


[JavaScript 실행]

Native에서 WebView 내 API를 호출할 수 있고 이는 Native에서 WebView로 전달할 것이 있을 때 유용함.

ewk_view_script_execute(ewk_view,"자바스크립트 코드", 
            "결과 전달 callback", "callback으로 전달할 user_data");

typedef void(*Ewk_View_Script_Execute_Cb )(Evas_Object *o, const char *result_value, void *user_data)

근데 재미 있는 것은 callback의 result_value가 항상 null로 넘어온다. 언젠가 수정 될듯.
(다른분께서 알려주신건데 result_value가 script에서 마지막의 변수나 return값을 가지는 함수의 결과값이 전달된다고 하니 참고..)


[Page 관련 signal]

page loading 관련, URL 변경 관련 처리를 할 수 있는 signal들을 아래와 같이 등록 가능 함.

evas_object_smart_callback_add(ewk_view, "url,changed", __on_url_changed, user_data);
evas_object_smart_callback_add(ewk_view, "load,started", __on_load_started, user_data);
evas_object_smart_callback_add(ewk_view, "load,finished", __on_load_finished, user_data);
evas_object_smart_callback_add(ewk_view, "load,error", __on_load_error, user_data);

아래와 같이 page 시작 시 signal을 등록하여 처리할 수 있음.
다만 WebView engine에서 loading은 이미 시작된 후 efl port에서 IPC를 전달 받아
callback이 실행되므로 시점 차이가 있을 수 있다.

void __on_load_started(void *user_data, Evas_Object *webview, void *event_info)
{
const char* url = ewk_view_url_get(webview);
DLOG("__on_load_started, URL = %s", url);

}

URL 변경 시 변경된 URL에 따라서 처리할 수 있음.
Hash값이 변경 되었을 경우에도 이 callback이 불리어 hash에 따라서
native에서 처리할 수 있다.

void __on_url_changed(void *user_data, Evas_Object *webview, void *event_info)
{
appdata_s *ad = (appdata_s *)user_data;
const char* url = ewk_view_url_get(webview);

DLOG("__on_url_changed, URL = %s", url);

// Do something for the changed URL.
}

이것을 활용하면 JavaScript -> Native 코드 호출이 가능하다.
JavsScript에서 hash 값을 변경하여 url 뒤에 필요한 명령을 붙이고
Native에서 __on_url_changed event callback 내에서 url의 hash값을 보고
native 코드를 처리하면 된다.


[WebView page navigation policy]

특정 domain내의 page만 webview를 통해서 보여주고 싶을 경우
아래와 같이 signal을 등록해서 처리해야 한다.

evas_object_smart_callback_add(ewk_view, "policy,navigation,decide", __on_policy_navigation, ad);

callback 내에서 이동하려는 url을 ewk_policy_decison_url_get()으로 확인한 뒤
허용되는 domain 내의 page이면 ewk_policy_decision_use()로 이동 허용
아니면 ewk_policy_decision_ignore()로 이동 취소를 하면 됨.


void __on_policy_navigation(void *user_data, Evas_Object *webview, void *event_info)
{
Ewk_Policy_Decision* decision = (Ewk_Policy_Decision*)event_info;

string _loading_url((char*)ewk_policy_decision_url_get(decision));
string _current_url(ewk_view_url_get(webview));

// 허용되는 SITE_DOMAIN 인지 확인
if(0  == _loading_url.compare(0, strlen(SITE_DOMAIN), SITE_DOMAIN) )
{
ewk_policy_decision_use(decision);
return;
}

// 허용되지 않는 URL
ewk_policy_decision_ignore(decision);
}


2015년 5월 12일 화요일

Tizen Wearable 기기에 App 설치를 위한 Certificate 등록

Tizen SDK 2.3 Rev2를 설치하고
Wearable 기기에 앱을 설치하기 위해 Certificate을 등록하기 위해 방법을 찾아봤으나
정작 여러 포스팅이나 비디오에서 보이는 Certificate Request 아이콘이 SDK내에서 보이지 않는다.

Tizen SDK에서 Certificate 등록을 위해 SDK 내 아이콘을 선택하는 장면
https://youtu.be/Xy2B-nlnprg?t=2m10s


몇번의 SDK 재설치와 검색으로 찾아낸 정보로는
Certification을 위한 별도의 SDK가 존재해서 이것을 별도로 설치해줘야 한다.

Tizen Extension SDK for Certificate 다운로드
: http://developer.samsung.com/samsung-z#none

Tizen Extension SDK for Certificate 설치 방법
http://developer.samsung.com/technical-doc/view.do?v=T000000198
: http://seoz.egloos.com/4066593


이후 부터는 위 유투브 링크(https://youtu.be/Xy2B-nlnprg?t=2m10s)를 참고하여 설치하면 된다.

2015년 4월 21일 화요일

Firefox App 개념 대충 정리

MDN App Center
https://developer.mozilla.org/en-US/Apps

[Quickstart]
https://developer.mozilla.org/en-US/Apps/Quickstart

[Getting Started, 한글판]
https://developer.mozilla.org/ko/Apps/Getting_Started

[App Manifest]
 : https://developer.mozilla.org/en-US/Apps/Build/Manifest

- manifest.webapp (.webapp extension은 필수)
- root directory 내에 위치
- JSON format, Content-Type은 application/x-web-app-manifest+json 이어야 함.
- manifest 에서 참조되는 internal path들은 same origin내에 존재해야 함.

- Firfox marketplace 등록 시 필수 항목들
 : name, description, launch_path( for Packaged Apps), icons(128x128 필수, 512x512 옵션), developer, default_locale, type
- generic Open Web Apps
 : name, description, icons(128x128 required, 512x512 recommended)

- optional fields
 . activities
  : 타 app에서 사용가능한 기능을 제공하는 Web Activities의 조합이며 어떤 activity를 지원하는지 정의. 하단은 png, gif 이미지를 share' 하는 activity를 지원하며

"activities": {
  "share": {
    "filters": {
      "type": [ "image/png", "image/gif" ]
    },
    "href": "foo.html",
    "disposition": "window",
    "returnValue": true
  }
}
 . installs_allowed_from
  : app이 설치 가능한 하나 이상의 URL, 구입해야 할 필요가 있는 app이라면 유용하게 사용될 수 있을 듯. default 값는 "*".

"installs_allowed_from": [
  "https://marketplace.firefox.com"
]
 . messages
  : 지정된 message들에 대해서 해당 page가 보여지도록 할 때 사용 됨.

 . permissions
  : app에서 사용할 device api들을 명시함.
  : 상세 permission list
   . https://developer.mozilla.org/en-US/Apps/Build/App_permissions
   . 3단계의 permission level이 존재함.
    > Web apps : basic level의 permission만을 사용 가능
    > Privileged apps : web app의 permission이상을 가짐. Hosted app 포함 안됨.
    > Internal (certified) apps : web app과 privileged app의 permission을 모두 가짐.
      : system level app들이나 Mozilla/operators/OEM들에서 만들어짐 앱들.


[Same Origin Policy]
https://developer.mozilla.org/en-US/Apps/Build/Building_apps_for_Firefox_OS/App_manifest_FAQ
http://charlie0301.blogspot.kr/2013/12/jquery-ajax-same-origin-policy-jsonp.html


[App installation]
 . app 설치 여부 확인할 경우 navigator.mozApps.getSelf() 를 사용
  : 특정앱의 설치 여부를 보려면 navigator.mozApps.checkInstalled()로 확인

var request = navigator.mozApps.getSelf();
request.onsuccess = function() {
  if (request.result) {
    // we're installed
  } else {
    // not installed
  }
};
request.onerror = function() {
  alert('Error checking installation status: ' + this.error.message);
};
 . app 설치를 위해서는 navigator.mozApps.install() 사용.

var request = navigator.mozApps.install("http://path.to/my/example.webapp");
request.onsuccess = function() {
  // great - display a message, or redirect to a launch page
};
request.onerror = function() {
  // whoops - this.error.name has details
};

[Device APIs]
https://developer.mozilla.org/en-US/Apps/Reference/Firefox_OS_device_APIs


[Simple Push]
 : https://developer.mozilla.org/en-US/docs/Web/API/Simple_Push_API
 : https://github.com/Redth/PushSharp/wiki/How-to-Configure-&-Send-FirefoxOS-Push-Notifications-using-PushSharp

Mozilla Push Notifications Flow
이미지  : https://camo.githubusercontent.com/2320ecab764e5493c5f3c1d28ef8e11430629de6/687474703a2f2f61726374757275732e6769746875622e696f2f6c6f6e646f6e5f6d65657475705f66697265666f786f732f696d672f706e735f6578616d706c652e706e67

 . Firefox OS에서만 지원.
 . App은 Simple Push를 사용하기 위해 unique한 endpoint를 Mozilla push 서버로 요청 함. 이후 전달받은 endpoint를 App은 자신의 server에 저장한 뒤 app을 wake 시키기 위해 사용함.
 . push시 endpoint와 version number도 함께 전달할 수 있어 이를 app에서 사용 가능함.
 . push를 unregister 하기 위해서는 PushManager.unregister()을 호출.
 . 사용하기 위해서는
  > manifest 파일 내 message로 "push", "push-register"로 event를 받을 page 등록.
  > manifest 파일 내 permissions에 "push" 등록.
  > PushManager.register()를 사용하여 endpoint 요청.
  > 수신 받은 endpoint를 추후 사용하기 위해 자신의 server에 등록하여 저장.

if (navigator.push) {
  // Request the endpoint. This uses PushManager.register().
  var req = navigator.push.register();
  
  req.onsuccess = function(e) {
    var endpoint = req.result;
      console.log("New endpoint: " + endpoint );
      // At this point, you'd use some call to send the endpoint to your server. 
      // For instance:
      /* 
      var post = XMLHTTPRequest();
      post.open("POST", "https://your.server.here/registerEndpoint");
      post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      post.send("endpoint=" + encodeURIComponents( endpoint ) );
      */
      // Obviously, you'll want to add .onload and .onerror handlers, add user id info,
      // and whatever else you might need to associate the endpoint with the user.
    }

   req.onerror = function(e) {
     console.error("Error getting a new endpoint: " + JSON.stringify(e));
   }
} else {
  // push is not available on the DOM, so do something else.
}
  > app에 push notification 수신 시 처리할 handler들을 등록 (window.navigator.mozSetMessageHandler())
    : push message handler는 index.html, main.js 아님 message handler만을 가지는 특정 파일(push-message.html)에 위치해야 한다. app이 종료되고 push message를 받는다면 message handler에서는 background로 처리를 해야할 지 app을 실행시켜야 할지 판단해야 하기 때문.
    : push-register message handler는 push server 변경, 일시 중지 등의 이유로 device의 internal identifier(UAID, User Agent Identifier)가 변경될 경우 이를 알려 app들이 다시금 endpoint를 register하도록 하기 위해 호출 된다.

  > notification 보내기

curl -X PUT -d "version=5" https://updates.push.services.mozilla.com/update/abcdef01234567890abcdefabcdef01234567890abcdef

[Contacts API]
 : https://developer.mozilla.org/en-US/docs/Web/API/Contacts_API
 . Firefox OS와 Firefox mobile(Android)에서 지원
 . system의 address book에 저장된 contact들을 접근하려면 navigator.mozContacts property를 사용해야 한다.
 . 연락처 추가, 검색, 수정, 삭제 지원
 . 연락처 찾기
  : ContactManager.find(), ContactManager.getAll()을 사용함.

[Notification API]
 : https://developer.mozilla.org/ko/docs/Web/API/notification

 . HTML5 feature라 Firefox외 Android browser, Chrome desktop 에서 지원한다.
  : http://caniuse.com/#feat=notifications
 . 구현 방법
  : https://developer.mozilla.org/en-US/docs/Web/API/Notification/Using_Web_Notifications

2015년 4월 16일 목요일

Chrome App 개념 대충 살펴보기

그냥 찾아봄.

[Create Your First App]
https://developer.chrome.com/apps/first_app

1. manifest 생성
 . chrome app에서는 background로 실행되는 script를 정할 수 있음.

2. background script 생성
 . background로 주기적으로 실행되며 event에 따라 app을 관리함.

3. window page 생성
 . 화면에 app을 보여주기 위해.
4. App icon 정하기
5. Chrome상에서 App launching
 . Chrome setting icon > Tools > Extension
   : Developer mode check 되어 있는지 확인
   : Load unpacked extension 버튼 클릭 후 app folder 선택

* 간단하네...


[Chrome App 관련 개념들]
: https://developer.chrome.com/apps/app_architecture

. Chrome App은 browser tab이 아닌 그냥 비어 있는 사각형에 표시되므로 특성에 따라 UI를 구성해야 함.
. Chrome App에서는 오프라인에서의 동작, 보안의 이유로 local상에서 main page를 위치하도록 하고 있음.

how app container model works

[App Life Cycle]

Life 설치 부터 삭제 까지의 주요 상황은 다음과 같음
- Instaillation : app 설치 시 permission을 사용자로부터 획득
- Startup : event page가 load되고 launch() event가 발생되면 app을 실행함.'
- Termination : app이 종료되면 종료 시 상태를 저장한다.
- Update : Chrome App은 언제나 업데이트 될 수 있지만 startup/termination 단계에서는 변경안됨.
- Uninstallation : 사용자가 app을 삭제하면 executing code와 private data는 모두 삭제 됨.

좀 더 자세히 풀어보면
: https://developer.chrome.com/apps/app_lifecycle

how app lifecycle works

아래와 같이 event Script에서 onLaunched 시 window를 표시함을 볼 수 있음.
chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('main.html', {
    id: 'MyWindowID',
    bounds: {
      width: 800,
      height: 600,
      left: 100,
      top: 100
    },
    minWidth: 800,
    minHeight: 600
  });
});
또한 설치, 중지, 재시작 되었을 때 chrome.runtime의 event listener로 처리할 수 있음.
=> https://developer.chrome.com/extensions/runtime#events


[Security Model]

Chrome App들은 CSP(Content Security Policy)를 따라야 한다고 하고 있음.

- Chrome App들은 사용하는 API들에 따른 permission을 명시적으로 알려야 함.
- Chrome App들은 분리된 storage, external content기반으로 분리된 process를 재사용함. 즉 다른 Chrome App들의 data, Chrome Browser의 Web page의 data를 접근할 수 없음. (cookie도 포함)

[Content Security Policy]
: https://developer.chrome.com/apps/contentSecurityPolicy
- 제약 사항들
 . inline scripting 사용 불허
 . video, audio를 제외한 external resources를 접근 불허
 . iframe 내 resource들을 embed 못함.
 . string-to-JavaScritp methods 사용 불가(eval(), new Function())

위 제약사항들에 대해서 대안으로 templating libraries, XMLHttpRequest를 사용한 external resoruce 접근, webview tag 사용을 말하고 있음.



[Chrome App Sample]
https://github.com/GoogleChrome/chrome-app-samples

[Hello World]
: https://github.com/GoogleChrome/chrome-app-samples/tree/master/samples/hello-world

예제의 진리.. hello world 
간단하다 화면에 Chrome icon과 hello world가 찍힌다.

manifest는 아래과 같고 background script는 main.js임.
{
"manifest_version": 2,
"name": "Hello World",
"version": "2.1",
"minimum_chrome_version": "23",
"icons": {
"16": "icon_16.png",
"128": "icon_128.png"
},
"app": {
"background": {
"scripts": ["main.js"]
}
}
}

background script에서는 
chrome app onLaunch event에서 화면에 index.html을 띄워주고 있음.

chrome.app.runtime.onLaunched.addListener(function() {
  // Center window on screen.
  var screenWidth = screen.availWidth;
  var screenHeight = screen.availHeight;
  var width = 500;
  var height = 300;

  chrome.app.window.create('index.html', {
    id: "helloWorldID",
    outerBounds: {
      width: width,
      height: height,
      left: Math.round((screenWidth-width)/2),
      top: Math.round((screenHeight-height)/2)
    }
  });
});
스크린샷은 직접 해서 보시라. :)

2015년 4월 2일 목요일

ReactJS, React Native 참고 resource들 링크 정리

여기저기서 React.js에 대한 얘기들이 나오길래 찾아봄.

https://facebook.github.io/react/index.html


  • 페이스북이 Web User Interface를 만들기 위해 만든 JavaScript Library.
  • Model-View-Control 패턴 중 View를 위한 component를 만드는 방법을 제공 하고 있음.


ReactJS의 특징

  • JSX(JavaScript XML)
    • XML 기반의 JavaScript 확장 문법이며 Virtual DOM을 생성하기 위해 사용된다.
  • Virtual DOM 
    • JavaScript Object Graph를 저장하고 있으며 변환단계를 거처 HTML DOM을 생성 한다고 함.
    • 변환 시 차이점을 파악하여 업데이트하는 방법을 사용하므로 빠른 DOM 조작 성능을 제공한다고 함
  • 단방향 데이터 바인딩(Unidirectional Data Flow)
    • 데이터 바인딩을 props, state를 사용하도록 제한 하여 디버깅을 쉽게 하고 성능을 높인다고 함.


[그것이 알고 싶다 – Spinbox로 React 겉핥기]
http://wit.nts-corp.com/2014/11/19/2584
: 제목과는 다르게 한번 보면 아 이런 거구나 알 수 있는 포스팅.

[REACTJS 둘러보기 – XHP부터 REACT NATIVE까지]
http://taegon.kim/archives/5097
: React가 나오게 된 배경, ReactJS, React Native에 대한 설명

[영문 Resources]


https://code.facebook.com/
conference 비디오 자료들이 있음.

[Learning React.js: Getting Started and Concepts]
: https://scotch.io/tutorials/learning-react-getting-started-and-concepts
: 간략하게 React.js 컨셉에 대해서 쉽게 설명한 영문 문서

> Unidirectional Data Flow 설명
 : https://scotch.io/tutorials/learning-react-getting-started-and-concepts
사실 JavaScript 초짜인 나에게는 좀 이해가 잘 안되는 개념이다. 그냥 바인딩 하는 방법을 제한한 것만 같아서 React.js에서 디버깅말고 성능 개선 이점의 이유를 잘 모르겠음.

[Intro to the React Framework]
: http://code.tutsplus.com/tutorials/intro-to-the-react-framework--net-35660
: 자세하게 React.js의 컨셉을 설명하는 좀 긴 문서, MVC 패턴부터 설명한다.

> What Makes React Different?
 ReactJS의 특징을 좀 더 자세히 설명해 주는 부분

> Component Lifecycle
 Component Life cycle에 대한 설명

http://open.bekk.no/easier-reasoning-with-unidirectional-dataflow-and-immutable-data
이건 좀 나중에 봐야 겠다.

[React Native]



[React Native]
: http://dalinaum.github.io/react/ios/2015/03/27/hello-react-native.html
 React Native 샘플을 만드는 포스팅