Android/Information
Android ↔ Typescript 함수 공유 방법 (2)
y0ngha
2021. 10. 27. 01:33
이 전 글에서 Android Native는 모두 작성하였으니, 이제 TypeScript를 작성하면 작업이 마무리된다.
NativeService.ts 라는 Class를 생성해주도록 하자.
NativeService.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
declare global {
interface Window {
native: Native;
}
}
declare global {
interface Native {
getPref: (key: string, defaultData: string) => Promise<void>;
setPref: (key: string, data: string) => Promise<void>;
}
}
export class NativeService implements Native {
async getPref(key: string, defaultData: string): Promise<void> {
window[key] = await window.native.getPref(key, defaultData);
}
async setPref(key: string, data: string): Promise<void> {
await window.native.setPref(key, data);
}
}
|
cs |
[Line 1~5] global 영역 안에 있는 window에 대해 native라는 object를 추가해준 것 이다.
[Line 7~12] global 영역에 Native라는 Interface를 추가해준 것이다.
Line 1~5를 거치면서 window.native의 Type은 Line 7~12에서 생성한 Native라는 Interface라는 것을 정의해준 것 이다.
(사실 소스가 겹치지 않았나 싶다.)
그 후 NativeService Class는 Native Interface를 참조하게끔 작성하였다.
window.native.(함수명) 을 호출하게 되었을 때 이 전글에서 기술한 @JavascriptInterface Annotation이 달려있는 함수중에 이름이 맞는 함수로 호출하게 된다.
여기서 값을 받아오는 방식으로는 window[key] 형식을 채택하였는데, 사실 Android는 Native에서 바로 리턴해줘도 상관이 없다.
그럼에도 window[key] 형식을 채택한 이유는 iOS와 통일성을 가져가기 위해서 채택한 부분이었다.
Hybrid App을 개발하면서 위 방법은 자주 쓰고 있다.