반응형

 

1. Apache cordova -  App 개발 기본

2. Apache cordova - plugin 사용( for android )

3. Apache cordova -  plugin 개발( for android ) 

 4. Apache cordova -  Activity를 포함하는 plugin 개발 ( for android ) 

 

개발 환경:

OS: Windows

개발툴: VS Code

support Platform : Androd

 

지난 글에서 단순한 기능을 포함하는 cordova plugin개발에 대해서 알아봤다.

한가지 더 궁금 했던 부분은 cordova plugin내에 Activity나 string, image 등의 리소스를 포함하여 패키징 할 수 있는냐는 것이다.

cordova plugin으로 어떤 기능까지 제공할 수 있느냐 하는 문제와 크게 다르지 않은 의문이라 조금만 더 파보고자 한다.

 

 

이전 글에 이어서 몇가지만 정리 하고 넘어 가자.

 

cordova plugin은 cordova app과 어느 시점에 어떤 방식으로 병합(?)되는 걸까?

plugin을 추가하면 app 프로젝트에 반영되는 주요 변경 사항을 살펴보자.

 

기억을 상기 시키기 위해, 이전 글에서 작성한 소스코드 두벌을 다시 소환한다.

1. cdvplugin.js - 노출 API를 export한 javascript 소스 파일 ( platform 공통 )

2. cdvplugin.java  - 노출된 API를 구현한 Java 소스 파일 ( android platform 종속 )

 

cordova app 프로젝트 관점

1. package.json 파일에 plugin 설정이 추가 된다.

2. plugins 폴더 하위에 plugin source 파일들이 복사된다. cdvplugin.js , cdvplugin.java,, plugin.xml ...

(파일/폴더 구조 및 소스 및 설정 파일까지 통째로 복사됨)

 

Android app 프로젝트

cordova platform add android

커맨드를 통해 생성되는 [platforms/android] 폴더에 생성되는 프로젝트는

Android Studio를 통해 오픈되며 빌드 가능하다. ( gradle 버전이라던가 plugin 버전이라던가  sdk 버전의 missmatch에서 오는 이슈를 해결해야 하는 경우가 많지만 ...)

이 이야기인 즉슨, platforms/android 폴더에는 모든 app 코드와 모듈(플러그인)이 어떤 형태로든 병합(?)되어 빌드가능한 형상으로 존재한다는 뜻이다)

 

Android project의 구조를 살펴보며, cordova app의 구동구조를 살짝만 엿보도록 하자.

1. Webview에서 구동될 webapp 코드( cdvplugin.js등의 plugin코드 포함)들은 asset 폴더에 추가되고

2. MainActivity에 의해 로드된다.

(아래 그림을 보면 cordova plugin 소스 파일인 cdvplugin.java 또한 프로젝트에 포함되어 있는 것을 확인 할 수 있다.

MainActivity.java

asset에 포함된 webapp의 코드를 webview에 로드할 것으로 추측

package com.thirteenrains.cdvapp;

import android.os.Bundle;

import org.apache.cordova.*;

public class MainActivity extends CordovaActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // enable Cordova apps to be started in the background
        Bundle extras = getIntent().getExtras();
        if (extras != null && extras.getBoolean("cdvStartInBackground", false)) {
            moveTaskToBack(true);
        }

        // Set by <content src="index.html" /> in config.xml
        loadUrl(launchUrl);
    }
}

 

자, 여기까지 살펴보면 cordova app과 plugin이 어떻게 android project에 병합(?) 되는지 감이 오지 싶다.

 

다시 처음의 주제로 돌아와서 ....

cordova plugin의 소스를 대상 플랫폼의 빌드 구성안에 우겨 넣는 형태로 연동하는 것으로 보이는데

Custom Activity나 Resource를 plugin에 추가해서 배포하려면 어떻게 해야 할까?

 

하나의 방법을 제시하자면, 

Androdi Library(AAR)에 리소스를 포함하고, 해당 aar을 plugin에서 참조하는 방법으로 구현이 가능하다.

(다른 방법이 추가로 존재할 수도 있지만 굳이 찾지 않는다.)

 

AAR 프로젝트

Simple한 Activity를 하나 포함한 AAR 라이브러리를 작성한다.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.thirteenrains.nativelib">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:supportsRtl="true"
        android:theme="@style/Theme.Nativelib"
        tools:targetApi="31">
        <activity
            android:name=".SimpleActivity"
            android:exported="true">
        </activity>
    </application>

</manifest>

SimpleActivity.ava

package com.thirteenrains.nativelib

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class SimpleActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_simple)
    }
}

activity_simple.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SimpleActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

build..gradle

plugins {
    id 'com.android.library'
    id 'org.jetbrains.kotlin.android'
}

android {
    compileSdk 30

    defaultConfig {
        minSdk 23
        targetSdk 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}

 

cordova plugin 프로젝트

1. cdvplgin/src/android 폴더에

1) nativelib.aar 복사

2) cdvplugin.gradle 파일 생성

repositories{    
  jcenter()
  flatDir {
      dirs 'src/main/libs'
   }
}

dependencies {
  // nativelib.aar dependency추가
  implementation 'com.thirteenrains.nativelib:nativelib@aar'
  // 필요에 따라 추가 dependency를 추가 할 수 있다.
  implementation 'com.google.android.material:material:1.4.0'
}

android {
  packagingOptions {
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
  }
}

2. cdvplugin/plugin.xml

- gradle 레퍼런스, aar 라이브러리 복사 설정

<?xml version='1.0' encoding='utf-8'?>
<plugin id="com.thirteenrains.cdvplugin" 
    version="0.0.1" 
    xmlns="http://apache.org/cordova/ns/plugins/1.0" 
    xmlns:android="http://schemas.android.com/apk/res/android">
    ...
    <platform name="android">
        ...
        <!-- gradle 설정 -->
        <framework src="src/android/cdvplugin.gradle" custom="true" type="gradleReference" />
        <!-- resource(aar파일) 복사 설정 -->
        <!-- src: plugin폴더 내의 경로, tartget: app 프로젝트 내의 경로 -->
        <resource-file src="src/android/nativelib.aar" target="libs/nativelib.aar" />
        ...
    </platform>
</plugin>

 

cordova app 프로젝트

index.html

<div>
        <p>
          <button id="btnShowActivity">show activity</button>
        </p>
      </div>

my.js

document.getElementById("btnShowActivity").addEventListener("click", toast);

function toast() {
  var cdvplugin = cordova.plugins.cdvplugin;
  cdvplugin.showAct("hi! cordova plugin", onSuccess, onError);
}

function onSuccess(status) {
  alert("onSuccess : " + status);
}

function onError(error) {
  alert("onError : " + error);
}

 

실행

cordova run android

 

- 끝 -

반응형
반응형

1. Apache cordova -  App 개발 기본

2. Apache cordova - plugin 사용( for android )

3. Apache cordova -  plugin 개발( for android )

4. Apache cordova - Activity를 포함하는 plugin 개발 ( for android ) 

 

개발 환경:

OS: Windows

개발툴: VS Code

support Platform : Androd ( iOS - windows에서는 빌드 불가 : 나중에 정리 )

 

간단한 cordova plugin 개발을 통해, cordova plugin 구조에 대해 알아보자.

 

Plugman

plugman은

Apache Cordova 프로젝트 와 함께 사용할 플러그인을 설치 및 제거하는 명령줄 도구입니다 .

라고 설명되어 있습니다.

https://github.com/apache/cordova-plugman

plugman을 통해 cordova plugin 프로젝트를 생성 할수 있습니다.

 

Cordova plugin 개발

plugman 설치

npm install -g plugman

 

plugin 프로젝트 생성

plugman create

지정된 경로에 Cordova 플러그인 프로젝트에 대한 템플릿 구조를 생성

명령 구문:

plugman create 
--name <pluginName> 
--plugin_id <pluginID> 
--plugin_version <version> 
[--path <directory>] 
[--variable NAME=VALUE]

인수:

값설명

--name <pluginName> 플러그인 이름
--plugin_id <pluginID> 플로그인 ID
--plugin_version <version>           플러그인 버전기본값 : 파일 의 요소를 HelloCordova

- config.xml의 name element와 매핑됨
- 어플리케이션의 타이틀로 표시되는 이름

 

코도바 플러그인 프로젝트를 생성해 봅니다.

plugman create --name cdvplugin --plugin_id com.thirteenrains.cdvplugin --plugin_version 0.0.1

[src] 폴더

플랫폼별 플러그인 코드가 작성될 폴더 입니다.

- www/cdvplugin.js 파일

cordova plugin에서 노출할 API가 정의될 파일 입니다.

'플로그인 이름'과 함수 명을 인자로 cordova.exec() 를 호출하는

coolMethod를 Export하고 있는 것을 확인 할 수 있습니다.

 

 plugin.xml 파일

플러그인의 설정이 저장될 파일 입니다.

- 프로젝트 생성 커맨드 실행시 입력한 인자와 비교해보면 되겠습니다.

 

음 기본 템플릿은 심플하네요.

 

www / cdvplugin.js가 cordova app쪽에서 호출할 API가 정의 되는 파일 이고,

src / 하위에 각 플랫폼별 동작 코드가 들어가는 구조인것 같습니다.

 

그럼 Android 플랫폼을 지원하도록 추가 해 보겠습니다.

Cordova plugin Platfom 추가

cd cdvplugin
plugman platform add --platform_name android

src / android 폴더 하위에 cdvplugin.java파일이 생성됩니다.

예상한 것처럼 coolMethod의 실행 코드가 포함되어 있습니다.

성공하면 success callback을

실패하면 error callback을 호출 하는 군요.

package com.thirteenrains.cdvplugin;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * This class echoes a string called from JavaScript.
 */
public class cdvplugin extends CordovaPlugin {

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("coolMethod")) {
            String message = args.getString(0);
            this.coolMethod(message, callbackContext);
            return true;
        }
        return false;
    }

    private void coolMethod(String message, CallbackContext callbackContext) {
        if (message != null && message.length() > 0) {
            callbackContext.success(message);
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }
}

 

이전 글의 플러그인 함수 호출 코드를 소환해 보면 호출 흐름이 파악됩니다.

document
  .getElementById("reqCamPermission")
  .addEventListener("click", requestCameraPermission);

function requestCameraPermission() {
  var permissions = cordova.plugins.permissions;
  permissions.requestPermission(permissions.CAMERA, onSuccess, onError);
}

function onSuccess(status) {
  if (status.hasPermission) {
    alert("SUCCESS - get permission");
  } else {
    alert("FAIL - get permission");
  }
}

function onError() {
  alert("error ");
}

 

플러그인 기능 추가

그러면 내가 만든 플러그인에 'toast'를 팝업 시키는 간단한 기능을 추가해 보겠습니다.

www / cdvplugin.js

exports.toast = function (arg0, success, error) {
  exec(success, error, "cdvplugin", "toast", [arg0]);
};

src / android / cdvplugin.java

 public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("toast")) {
            String message = args.getString(0);
            if (message != null && message.length() > 0) {
                android.widget.Toast.makeText(cordova.getActivity().getApplicationContext()
                , message, android.widget.Toast.LENGTH_SHORT).show();
                callbackContext.success(message);
            } else {
                callbackContext.error("message is empty");
            }
            
            return true;
        }
        
        return false;
    }

 

cordova app에 플러그인 사용

이전 글에서 생성한 cdvapp에 cdvplugin을 추가해서 호출해 보겠습니다.

로컬에 존재하는 플러그인도 cordova plugin add 명령어를 통해 추가 할 수 있습니다.

 

다만 package.json파일을 먼저 생성해야 합니다.

plugman createpackagejson ./

 

cordova app프로젝트에 플러그인 추가

cdvapp과 cdvplugin폴더가 동일한 폴더에 있다고 가정하면

아래의 커맨드를 통해 로컬 폴더의 플러그인을 app에 추가 할 수 있습니다.

 

cordova plugin add ../cdvPlugin

--link 옵션을 추가로 주면, plugin 폴더를 sysbolic link로 참조하여 플러그인 변경사항이 바로 적용됩니다.

(플러그인 개발 중에는 --link옵션이 유용할 것 같네요)

* --link 옵션으로 command를 실행시, 아래와 같은 에러가 발생할 수 있는데 이경우 cmd창을 관리자권한으로 실행 한후 명령어를 실행하면 정상 설치 됩니다.

 

플러그인 추가

플러그인 리스트 확인

플러그인 삭제

 

cordova app프로젝트에서 플러그인 사용

www / index.html

- toast 버튼 추가

<button id="btnToast">toast</button>

 

www / js / my.js

- toast plugin 호출 코드 추가

document.getElementById("btnToast").addEventListener("click", toast);

function toast() {
  var cdvplugin = cordova.plugins.cdvplugin;
  cdvplugin.toast("hi! cordova plugin", onSuccess, onError);
}

function onSuccess(status) {
  alert("SUCCESS");
}

function onError(error) {
  alert("ERROR : " + error);
}

 

 

다음 글에서는 Activity ( View ) 혹은 resource를 포함하는 plugin 개발에 대해 좀 더 알아 보겠습니다.

 

4. Apache cordova - Activity를 포함하는 plugin 개발 ( for android ) 

반응형
반응형

1. Apache cordova - App 개발 기본

2. Apache cordova - plugin 사용( for android )

3. Apache cordova - plugin 개발( for android )

4. Apache cordova - Activity를 포함하는 plugin 개발 ( for android ) 

cordova app에 카메라, GPS, PUSH등의 Native 기능을 사용하려면 cordova plugin을 사용해야 한다.

이번 글에서는 cordova plugin을 추가하고 사용하는 기본적인 방법에 대해서 가볍게 살펴본다.

 

개발 환경:

OS: Windows

개발툴: VS Code

support Platform : Androd ( iOS - windows에서는 빌드 불가 : 나중에 정리 )

 

Apache cordova 핵심 플러그인

 

Plugin Search - Apache Cordova

Cordova Plugins What is a Cordova plugin? A plugin is a bit of add-on code that provides JavaScript interface to native components. They allow your app to use native device capabilities beyond what is available to pure web apps. Below is a list of Apache C

cordova.apache.org

 

플러그인 Command

cordova plugin command

프로젝트 플러그인 관리

Command Syntax:

cordova {plugin | plugins} [
    add <plugin-spec> [..] {--searchpath=<directory> | --noregistry | --link | --save | --force} |
    {remove | rm} {<pluginid> | <name>} --save |
    {list | ls}
]

 

명령 옵션 설명
add <plugin-spec> […]                                       지정된 플러그인 추가
  --link       로컬 경로에서 설치하는 경우 파일을 복사하는 대신 심볼릭 링크를 생성. 플러그인 개발에 유용.
remove <pluginid>\|<name> […]                             지정된 ID/이름을 가진 플러그인을 제거합니다.
list   현재 설치된 플러그인 나열

 

플러그인 적용

상대적으로 적용이 간단한 권한처리 플러그인을 적용해 본다.

 

플러그인 추가

android permission plugin(cordova-plugin-android-permissions) 

cordova plugin add cordova-plugin-android-permissions

cordova plugin add 명령어로 plugin을 추가 하면, package.json에 관련 정보가 추가된다.

 

plugin 테스트를 위한 UI추가

- index.html에 버튼을 하나 추가

- 플러그인 사용 코드를 추가할 my.js파일도 include

 

plugin 테스트를 위한 코드 추가

- js/my.js 파일을 생성후, 코드 추가

document
  .getElementById("reqCamPermission")
  .addEventListener("click", requestCameraPermission);

function requestCameraPermission() {
  var permissions = cordova.plugins.permissions;
  permissions.requestPermission(permissions.CAMERA, onSuccess, onError);
}

function onSuccess(status) {
  if (status.hasPermission) {
    alert("SUCCESS - get permission");
  } else {
    alert("FAIL - get permission");
  }
}

function onError() {
  alert("error ");
}

 

실행

App을 실행 해 봅니다.

cordova run android

- 권한 요청 창이 뜨면 성공

 

플러그인 구조 엿보기

cordova plugin을 개발하는 글에서 다시 설명하겠지만,

cordova plugin add  명령을 통해 , 플러그인을 설치하면, 아래 그림과 같은 구조의 폴더와 파일들이 생성된다.

 

 

www폴더 하위의 permissions.js 파일의 아래 부분과

android/plugins 폴더 하위의 Permissions.java 파일을 살펴보면 cordova Plugin의 동작구조를 엿볼 수 있다.

 

3. Apache cordova - plugin 개발( for android )

4. Apache cordova - Activity를 포함하는 plugin 개발 ( for android ) 

 

반응형

+ Recent posts