CORDOVA

bluetooth

ZEROWIN.TECH 2021. 7. 13. 00:52
728x90

참조사이트

블루투스 관련 참조 사이트입니다.

https://github.com/evothings/cordova-ble

Create Project

프로젝트를 생성합니다.

cordova create jinseng com.zw.jinseng jinseng

Platform

플랫폼을 추가합니다.

cordova platform add android ios

Plugin

  • Inappbrowser 추가합니다.
cordova plugin add cordova-plugin-inappbrowser 

  • BLE 플러그인을 추가합니다.
cordova plugin add cordova-plugin-ble


https://github.com/evothings/cordova-ble

 

evothings/cordova-ble

Bluetooth Low Energy plugin for Cordova. Contribute to evothings/cordova-ble development by creating an account on GitHub.

github.com

  • 모바일 OS  alert, confirm 메세지창 사용
cordova plugin add cordova-plugin-dialogs  

 

  • 디바이스 정보 조회시 필요한 플러그인
cordova plugin add cordova-plugin-device

 

AndroidManifest.xml

<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" package="com.zw.jinseng" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:hardwareAccelerated="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:usesCleartextTraffic="true" requestLegacyExternalStorage="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode" android:label="@string/activity_name" android:launchMode="singleTask" android:name="MainActivity" android:screenOrientation="portrait" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider android:authorities="${applicationId}.cordova.plugin.camera.provider" android:exported="false" android:grantUriPermissions="true" android:name="org.apache.cordova.camera.FileProvider">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/camera_provider_paths" />
        </provider>
        <amazon:enable-feature android:name="com.amazon.device.messaging" android:required="false" xmlns:amazon="http://schemas.amazon.com/apk/res/android" />
        <service android:exported="false" android:name="com.onesignal.ADMMessageHandler" />
        <receiver android:name="com.onesignal.ADMMessageHandler$Receiver" android:permission="com.amazon.device.messaging.permission.SEND">
            <intent-filter>
                <action android:name="com.amazon.device.messaging.intent.REGISTRATION" />
                <action android:name="com.amazon.device.messaging.intent.RECEIVE" />
                <category android:name="com.yellowin.hello20210710" />
            </intent-filter>
        </receiver>
    </application>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="com.amazon.device.messaging.permission.RECEIVE" />
    <permission android:name="com.yellowin.hello20210710.permission.RECEIVE_ADM_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="com.yellowin.hello20210710.permission.RECEIVE_ADM_MESSAGE" />
</manifest>
    
  • 경로

 

 

Cordova Health Plugin 을 추가합니다.

https://www.npmjs.com/package/cordova-plugin-health

인앱브라우져 파일 수정

1)인앱브라우져 소스코드 수정
 URL로 호출/로딩되는 모바일웹서비스의 컨트롤을 위하여 인앱브라우져 소스코드 수정은 꼭 이루어져야 함.
Android 인앱브라우져 소스코드
- 아래 경로의 네이티브 java 소스코드를 수정. ..\platforms\android\app\src\main\java\org\apache\cordova\inappbrowser\
iOS 인앱브라우져 소스코드
1)url예외처리 수정소스 ..\platforms\ios\앱이름\Plugins\cordova-plugin-inappbrowser\CDVWKInAppBrowser.m

 

config.xml 파일 수정

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.zw.jinseng" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>jinseng</name>
<description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    
    <access origin="*" />
    <allow-intent href="*" />
    <access launch-external="true" origin="*" />
    <allow-navigation href="*" />


    <platform name="android">
        <allow-intent href="market:*" />


        <preference name="AndroidLaunchMode" value="singleTask" />
        <preference name="Orientation" value="portrait" />
        
        <preference name="SplashScreenDelay" value="100000" />
        <preference name="SplashMaintainAspectRatio" value="true" />
        <preference name="SplashShowOnlyFirstTime" value="false" />
        <preference name="FadeSplashScreen" value="false" />
        <preference name="ShowSplashScreenSpinner" value="true" />

        <preference name="AppendUserAgent" value="mobileapp android" />


        <icon density="ldpi" src="res/icon/android/icon-36.png" />
        <icon density="mdpi" src="res/icon/android/icon-48.png" />
        <icon density="hdpi" src="res/icon/android/icon-72.png" />
        <icon density="xhdpi" src="res/icon/android/icon-96.png" />
        <icon density="xxhdpi" src="res/icon/android/icon-144.png" />
        <icon density="xxxhdpi" src="res/icon/android/icon-192.png" />

        <splash density="port-hdpi" src="res/screen/android/1280x1920.png" />
        <splash density="port-ldpi" src="res/screen/android/1280x1920.png" />
        <splash density="port-mdpi" src="res/screen/android/1280x1920.png" />
        <splash density="port-xhdpi" src="res/screen/android/1280x1920.png" />
        <splash density="port-xxhdpi" src="res/screen/android/1280x1920.png" />
        <splash density="port-xxxhdpi" src="res/screen/android/1280x1920.png" />
        <splash density="port-tvdpi" src="res/screen/android/1280x1920.png" />

    </platform>

    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />

        <preference name="Orientation" value="portrait" />

        <preference name="SplashScreenDelay" value="10000" />
        <preference name="SplashMaintainAspectRatio" value="true" />
        <preference name="SplashShowOnlyFirstTime" value="false" />
        <preference name="FadeSplashScreen" value="true" />
        <preference name="ShowSplashScreenSpinner" value="true" />
        <preference name="SplashScreenBackgroundColor" value="white" />
        
        <preference name="DisallowOverscroll" value="true" />
        <preference name="WKWebViewOnly" value="true" />
        <preference name="AppendUserAgent" value="mobileapp iosapp" />


        <icon height="20" src="res/icon/ios/icon-20.png" width="20" />
        <icon height="29" src="res/icon/ios/icon-29.png" width="29" />
        <icon height="40" src="res/icon/ios/icon-40.png" width="40" />
        <icon height="50" src="res/icon/ios/icon-50.png" width="50" />
        <icon height="57" src="res/icon/ios/icon-57.png" width="57" />
        <icon height="58" src="res/icon/ios/icon-58.png" width="58" />
        <icon height="60" src="res/icon/ios/icon-60.png" width="60" />
        <icon height="72" src="res/icon/ios/icon-72.png" width="72" />
        <icon height="76" src="res/icon/ios/icon-76.png" width="76" />
        <icon height="80" src="res/icon/ios/icon-80.png" width="80" />
        <icon height="87" src="res/icon/ios/icon-87.png" width="87" />
        <icon height="100" src="res/icon/ios/icon-100.png" width="100" />
        <icon height="110" src="res/icon/ios/icon-110.png" width="110" />
        <icon height="114" src="res/icon/ios/icon-114.png" width="114" />
        <icon height="120" src="res/icon/ios/icon-120.png" width="120" />
        <icon height="144" src="res/icon/ios/icon-144.png" width="144" />
        <icon height="152" src="res/icon/ios/icon-152.png" width="152" />
        <icon height="167" src="res/icon/ios/icon-167.png" width="167" />
        <icon height="180" src="res/icon/ios/icon-180.png" width="180" />
        <icon height="1024" src="res/icon/ios/icon-1024.png" width="1024" />

        <splash src="res/screen/ios/Default@2x~iphone~anyany.png" />
        <splash src="res/screen/ios/Default@3x~iphone~anyany.png" />

    </platform>
</widget>

인앱브라우져 이벤트 함수


 앱구동시 www/index.html 파일이 로딩되면서 index.js 파일내의 구문들이 실행됨.
- index.js에서 네이티브기능의 동작 구문의 소스등 로직이 들어감.
- 인앱브라우저로 모바일웹 컨텐츠가 로딩되어 서비스가 이루어지며, 아래 이벤트가 사용 됨.
1.loadstart 이벤트
- 인앱브라우져로 로딩된 웹페이지에서 url호출이 발생했을때 실행되는 이벤트
2.loadstop 이벤트
- url호출이 되고 웹서버로부터 이미지등 컨텐츠파일들의 로딩이 완료되었을때 실행 이벤트
3.exit 이벤트
- 인앱브라우져가 종료되었을때 실행 이벤트
4.message 이벤트
- 인앱브라우져에서 앱단으로 메세지를 전달할때 사용되는 이벤트

안드로이드 백버튼

/** 안드로이드 백버튼 처리 */
function onBackKeyDown() {
    //alert('location_url : '+location_url);

    //   //메인페이지인지의 여부 체크하여, 메인페이지라면 앱을 종료할수 있게 한다.
    //https://m.naver.com
    if (location_url.indexOf("naver.com") > 0 && location_url.length <= 20) {
        //alert("exit");
        exitApp();
    } else {
        //메인페이지가 아니라면 뒤로이동처리 (뒤로이동할 수 없다면 종료팝업 메세지띄움)
        try {
            //history.back();
            ref.executeScript({
                code: "history.back()",
            });
        } catch (err) {
            exitApp();
        }
    }
}

메세지 종료팝업

/** 종료메세지 팝업 */
function exitApp() {
    navigator.notification.confirm(
        // 내장객체 navigator brabra
        "앱을 종료하시겠습니까?", // message
        function(index) {
            if (index == 1) {
                //종료버튼을 누르면 ref 인앱브라우져 객체가 닫히고 하단 exit 이벤트가 호출됨.
                ref.close();
            } else if (index == 2) {
                return false;
            }
        },
        "앱 종료", // title
        ["종 료", "취 소"] // buttonLabels
    );
}

 

 

컴파일 에러시

 

구글핏 권한 획득

블루투스 

  • index.js
  • 코드도바에서 블루투스 통신 예제
var ref;
function onDeviceReady() {
    // Cordova is now initialized. Have fun!
    ref = cordova.InAppBrowser.open('main.html', '_blank', 'location=no,toolbar=no');

    ref.addEventListener("message", function(val) {
        // alert(JSON.stringify(val));
        if(val.data.action == "camera") {
            DEVICE_addItem();
        }
    });
}

document.getElementById("ble_start_scan").addEventListener("click", function() {
    evothings.ble.startScan(
        function(device)
        {
            // console.log('startScan found device named: ' + device.name);
            log('startScan found device named: ' + device.name);
        },
        function(errorCode)
        {
            console.log('startScan error: ' + errorCode);
        }
    );    
});

document.getElementById("ble_stop_scan").addEventListener("click", function() {
    evothings.ble.stopScan();
});

function log(msg, level) {

    level = level || "log";

    if (typeof msg === "object") {

        msg = JSON.stringify(msg, null, "  ");
    }

    console.log(msg);

    //if (level === "status" || level === "error") 
    {

        var msgDiv = document.createElement("div");
        msgDiv.textContent = msg;

        if (level === "error") {

            msgDiv.style.color = "red";
        }

        msgDiv.style.padding = "5px 0";
        msgDiv.style.borderBottom = "rgb(192,192,192) solid 1px";
        document.getElementById("output").appendChild(msgDiv);
    }
}

 

'CORDOVA' 카테고리의 다른 글

웹사이트 이동시 이벤트 수신  (0) 2021.07.10