Cordova plugin Camera Crashing My App in Quasar
Tags: cordova, quasar, vue, camera
Published: 2021-02-06 01:58:27

Photo by <b> <i> [Andrew Neel](https://www.pexels.com/@andrew) </i> </b> from [Pexels](https://www.pexels.com/photo/apple-iphone-desk-laptop-6633920/)

## Table Of Contents
 * [Introduction](#intro)
 * [Counter Measures](#counterMeasures)
 * [Installation of Plugins](#plugins)
 * [Writing The Codes](#code)
 * [Android Foreground Permission](#permission)

### 🎆 Introduction & Explanation <a name="intro"></a>
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 <b>'background app'</b>) to another native app (in this case, the Camera, which becomes the <b>foreground app</b>) 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.

### 🎇 Counter Measures <a name="counterMeasures"></a>
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 <b> foreground app </b>. Well this will need a special android permission, which will be inserted in the Android Manifest.


### 🎞 Installing Plugins <a name="plugins"></a>
I Will simply share the Links to the npm plugins for downloads, and the implementation 
will be done in [Quasar](https://quasar.dev/)

  * [Cordova Plugin Camera](https://www.npmjs.com/package/cordova-plugin-camera)

  * [Cordova Plugin Background-Mode](https://github.com/katzer/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)

## Writing The Codes <a name="code"></a>

#### Below is a code snippet from Quasar doc, on how to use the Camera Plugin
```javascript
<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 🤣.

From the above code, once the <b><i>captureImage</i></b> button is clicked, using the <b>camera plugin</b>, the <b><i>native camera<i/></b> is opened, then when you snap, the <b><i>onSuccess callback function</i></b>, returns the image in a base64; format, then you <b>change the state of the imageSrc</b> to the new converted data:image


#### Below is a snippet From [Katzar](https://github.com/katzer)on how to use the Background-Mode Plugin, with a little adjustment for Quasar.

```javascript
 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>

## Android Foreground Permission <a name="permission"></a>
    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 ](https://stackoverflow.com/questions/52382710/permission-denial-startforeground-requires-android-permission-foreground-servic)

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


# Summary
To be very honest, I just learnt this very life-saving route few hours ago, so I decided to share my newly found knowledge through this article. Hope it will help you some day, reduce your headache or something. 😊

Also, everything done here in Quasar (Vuejs Framework), could be reproduced in normal html css js 'www' folder