Cordova 플러그인 카메라가 Quasar에서 내 앱 충돌

11475 단어 cordovavuecameraquasar
Andrew Neel의 사진Pexels

목차


  • Introduction
  • Counter Measures
  • Installation of Plugins
  • Writing The Codes
  • Android Foreground Permission

  • 🎆 소개 및 설명

    Are you building an App with Cordova support and currently stuck with the cordova plugin camera having to crash and restart your application, or not showing the taken image ? Well this article will shed more light on the issue then outline steps that will help you out, Stay Tuned.

    Having in mind that hybrid (cordova) apps runs on webview, hence having a single main 
    Thread it works with.
    

    Encountering App crashing when using the cordova plugin camera, (or anyother app), occurs when you leave your APP (which now becomes inActive, as it turns a 'background app') to another native app (in this case, the Camera, which becomes the foreground app) with hope of returning to your application (the background app). With an insufficient RAM in Device , the background app (your app), will be terminated to save the OS.

    Android Os has a way of saving the system, from overload, by terminating any process it finds to consume lots of RAM. Checking your device (physical device), you would notice it has a RAM size lower than 3GB (At least mine was 😅), Since efficiency can never be 100%, same goes for this RAM in your device. As other applications are making use of the RAM too, hence when your applications run and encounters a heavy consumption of the RAM (from switching to camera and back), it terminates the background (minimized) apps running so as to save the system from an actual crashing. Oh, this would be at the expense of your own app crashing to save the OS (weird right ? 🙄).

    This time your app restarts from the beginning because it runs on a single Thread.
    

    🎇 대책

    From my little research (references will be posted below), we need to find a way to persist our application whilst in the background.

    i.e: when we leave our app for the camera, it is still active at the background
    
    NB: This would consume user's battery, so endeavor to disable the background activeness 
    when you are done with the whole process that took you outside your app. (We wouldn't want 
    to drain our users device battery right ?😊
    

    After using the native camera, and about to return to your application, it (your app) now becomes a foreground app . Well this will need a special android permission, which will be inserted in the Android Manifest.

    🎞 플러그인 설치

    I Will simply share the Links to the npm plugins for downloads, and the implementation
    will be done in
    Quasar
  • Cordova Plugin Camera
  • Cordova Plugin Background-Mode

  • PS: Please permit me to assume, that you already know how to use cordova plugins (i.e 
    starts working on DeviceReady). This 
    time I will be using it within Quasar (Link to documentation is above, or 
    https://quasar.dev)
    

    코드 작성

    아래는 카메라 플러그인을 사용하는 방법에 대한 Quasar 문서의 코드 스니펫입니다.



    <template>
      <div>
        <q-btn color="primary" label="Get Picture" @click="captureImage" />
    
        <img :src="imageSrc">
      </div>
    </template>
    
    <script>
    export default {
      data () {
        return {
          imageSrc: ''
        }
      },
      methods: {
        captureImage () {
          navigator.camera.getPicture(
            data => { // on success
              this.imageSrc = `data:image/jpeg;base64,${data}`
            },
            () => { // on fail
              this.$q.notify('Could not access device camera.')
            },
            {
              // camera options
            }
          )
        }
      }
    }
    

    NB: Quasar is so rich, that the normal deviceReady function a cordova plugin needs to 
    work, is prebuilt into the runtime, hence, once the app is created, the device is already 
    ready (Oops!!, I did it again, word repetition 😋).
    
    Also, readup on the documentation of each cordova plugin, as accessing them might differ, 
    but a hack I found, is to use window.plugin to access the plugins in my 
    vue/quasar files, 
    else Uncle ESLint will keep scolding you with errors 🤣.
    

    위의 코드에서 카메라 플러그인을 사용하여 captureImage 버튼을 클릭하면 기본 카메라가 열리고 스냅하면 onSuccess 콜백 함수가 이미지를 base64로 반환합니다. 형식을 지정한 다음 imageSrc의 상태를 새로 변환된 data:image로 변경합니다.

    아래는 Quasar에 대한 약간의 조정과 함께 백그라운드 모드 플러그인을 사용하는 방법에 대한 Katzar의 스니펫입니다.



     mounted () {
        // 1) Request background execution
        window.plugin.backgroundMode.enable();
    },
    beforeDestroy () {
        // Disabling the background Mode
        window.plugin.backgroundMode.disable();
    }
    

    * The mounted is a LifeCycleHook in vue, meaning that once the companent/page this code 
      appears on is mounted, the app background mode is automaticaly enabled. Then once you're 
      done, you choose to have another function call, say beforeDestroy; which is 
      another 
      vue LifeCycleHook, to disable the backgroundMode
    
    * Please note how I used window.plugin and not cordova.plugins as 
      seen from the actual github repo, well, Cordova.plugins returned "undefine"</b>
    

    안드로이드 포그라운드 권한

    PS: I'm a JavaScript Dev, don't know much about Java, so I will simply Copy and Paste, I 
    pray WE BOTH understand what we pasted 😋😉
    
    SOURCE: permission Denial Startforeground Requires Android Permission Foreground Servic

    // Simply add the uses permission to your AndroidManifest.xml file
    <manifest ...>
         ...
         <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
         ...
         <application ...>
         ...
    </manifest>
    


    요약



    솔직히 말해서, 나는 이 생명을 구하는 방법을 몇 시간 전에 배웠으므로 이 기사를 통해 새로 발견한 지식을 공유하기로 결정했습니다. 그것이 언젠가 도움이 되기를 바랍니다. 두통이나 그 밖의 것을 줄이십시오. 😊

    또한 여기 Quasar(Vuejs Framework)에서 수행된 모든 작업은 일반 html css js 'www' 폴더에서 재생산될 수 있습니다.

    좋은 웹페이지 즐겨찾기