Tampilkan postingan dengan label Cordova Tutorial. Tampilkan semua postingan
Tampilkan postingan dengan label Cordova Tutorial. Tampilkan semua postingan

Jumat, 11 Agustus 2017

Cordova - Best Practices

Cordova is used for creating hybrid mobile apps, so you need to consider this before you choose it for your project. Below are the best practices for Cordova apps development.

Single Page Apps

This is the recommended design for all Cordova apps. SPA is using client-side router and navigation loaded on the single page (usually index.html). The routing is handled via AJAX. If you have followed our tutorials, you probably noticed that almost every Cordova plugin needs to wait until the device is ready before it can be used. SPA design will improve loading speed and overall performance.

Touch Events

Since Cordova is used for mobile world it is natural to use touchstart and touchend events instead of click events. The click events have 300ms delay, so the clicks don’t feel native. On the other hand, touch events aren't supported on every platform. You should take this into consideration before you decide what to use.

Animations

You should always use hardware accelerated CSS Transitions instead of JavaScript animations since they will perform better on mobile devices.

Storage

Use storage caching as much as possible. Mobile network connections are usually bad, so you should minimize network calls inside your app. You should also handle offline status of the app, since there will be times when user's devices are offline.

Scrolling

Most of the time the first slow part inside your app will be scrolling lists. There are couple of ways to improve scrolling performance of the app. Our recommendation is to use native scrolling. When there are lots of items in the list, you should load them partially. Use loaders when necessary.

Images

Images can also slow the mobile app. You should use CSS image sprites whenever possible. Try to fit the images perfectly instead of scaling it.

CSS styles

You should avoid shadows and gradients, since they slow the rendering time of the page.

Simplification

Browser's DOM is slow, so you should try to minimize DOM manipulation and number of DOM elements.

Testing

Ensure that you test your app on as many devices and operating system versions as possible. If app works flawlessly on one device, it doesn't necessary mean that it will work on some other device or platform.

Cordova - Whitelist

This plugin allows us to implement whitelist policy for app's navigation. When we create a new Cordova project, the whitelist plugin is installed and implemented by default. You can open the config.xml file to see allow-intent default settings provided by Cordova.

Navigation Whitelist

In the simple example below we are allowing links to some external URL. This code is placed in config.xml. Navigation to file:// URLs is allowed by default.
<allow-navigation href = "http://example.com/*" />
The asterix sign, *, is used to allow navigation to multiple values. In the above example, we are allowing navigation to all sub-domains of the example.com. The same can be applied to protocol or prefix to the host.
<allow-navigation href = "*://*.example.com/*" />

Intent Whitelist

There is also the allow-intent element which is used to specify which URLs are allowed to open the system. You can see in the config.xml that Cordova already allowed most of the needed links for us.

Network Request Whitelist

When you look inside config.xml file, there is <access origin="*" />element. This element allows all network requests to our app via Cordova hooks. If you want to allow only specific requests, you can delete it from the config.xml and set it yourself.
The same principle is used as in previous examples.
<access origin = "http://example.com" />
This will allow all network requests from http://example.com.

Content Security Policy

You can see the current security policy for your app inside the head element in index.html.
<meta http-equiv = "Content-Security-Policy" content = "default-src 
   'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 
   'self' 'unsafe-inline'; media-src *">
This is default configuration. If you want to allow everything from the same origin and example.com, then you can use −
<meta http-equiv = "Content-Security-Policy" content = "default-src 'self' foo.com">
You can also allow everything, but restrict CSS and JavaScript to the same origin.
<meta http-equiv = "Content-Security-Policy" content = "default-src *; 
   style-src 'self' 'unsafe-inline'; script-src 'self' 
   'unsafe-inline' 'unsafe-eval'">
Since this is a beginners’ tutorial, we are recommending the default Cordova options. Once you get familiar with Cordova, you can try some different values.

Cordova - Vibration

This plugin is used for connecting to device's vibration functionality.

Step 1 - Installing Vibration Plugin

We can install this plugin in command prompt window by running the following code −
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-vibration

Step 2 - Add Buttons

Once the plugin is installed we can add buttons in index.html that will be used later to trigger the vibration.
<button id = "vibration">VIBRATION</button>
<button id = "vibrationPattern">PATTERN</button>

Step 3 - Add Event Listeners

Now we are going to add event listeners inside onDeviceReady in index.js.
document.getElementById("vibration").addEventListener("click", vibration);
document.getElementById("vibrationPattern").addEventListener("click", vibrationPattern);

Step 4 - Create Functions

This plugin is very easy to use. We will create two functions.
function vibration() {
   var time = 3000;
   navigator.vibrate(time);
}

function vibrationPattern() {
   var pattern = [1000, 1000, 1000, 1000];
   navigator.vibrate(pattern);
}
The first function is taking time parameter. This parameter is used for setting the duration of the vibration. Device will vibrate for three seconds once we press VIBRATION button.
The second function is using pattern parameter. This array will ask device to vibrate for one second, then wait for one second, then repeat the process again.

Kamis, 10 Agustus 2017

Cordova - Splash Screen

This plugin is used to display a splash screen on application launch.

Step 1 - Installing Splash Screen Plugin

Splash screen plugin can be installed in command prompt window by running the following code.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-splashscreen

Step 2 - Add Splash Screen

Adding splash screen is different from adding the other Cordova plugins. We need to open config.xml and add the following code snippets inside the widget element.
First snippet is SplashScreen. It has value property which is the name of the images in platform/android/res/drawable- folders. Cordova offers default screen.png images that we are using in this example, but you will probably want to add your own images. Important thing is to add images for portrait and landscape view and also to cover different screen sizes.
<preference name = "SplashScreen" value = "screen" />
Second snippet we need to add is SplashScreenDelay. We are setting valueto 3000 to hide the splash screen after three seconds.
<preference name = "SplashScreenDelay" value = "3000" />
The last preference is optional. If value is set to true, the image will not be stretched to fit screen. If it is set to false, it will be stretched.
<preference name = "SplashMaintainAspectRatio" value = "true" />
Now when we run the app, we will see the splash screen.
Cordova Splash Screen

Cordova - Network Information

This plugin provides information about device's network.

Step 1 - Installing Network Information Plugin

To install this plugin, we will open command prompt and run the following code −
C:\Users\username\Desktop\CordovaProject>cordova plugin 
   add cordova-plugin-network-information

Step 2 - Add Buttons

Let's create one button in index.html that will be used for getting info about network.
<button id = "networkInfo">INFO</button>

Step 3 - Add Event Listeners

We will add three event listeners inside onDeviceReady function in index.js. One will listen for clicks on the button we created before and the other two will listen for changes in connection status.
document.getElementById("networkInfo").addEventListener("click", networkInfo);
document.addEventListener("offline", onOffline, false);
document.addEventListener("online", onOnline, false);

Step 4 - Creating Functions

networkInfo function will return info about current network connection once button is clicked. We are calling type method. The other functions are onOffline and onOnline. These functions are listening to the connection changes and any change will trigger the corresponding alert message.
function networkInfo() {
   var networkState = navigator.connection.type;
   var states = {};
   states[Connection.UNKNOWN]  = 'Unknown connection';
   states[Connection.ETHERNET] = 'Ethernet connection';
   states[Connection.WIFI]     = 'WiFi connection';
   states[Connection.CELL_2G]  = 'Cell 2G connection';
   states[Connection.CELL_3G]  = 'Cell 3G connection';
   states[Connection.CELL_4G]  = 'Cell 4G connection';
   states[Connection.CELL]     = 'Cell generic connection';
   states[Connection.NONE]     = 'No network connection';
   alert('Connection type: ' + states[networkState]);
}

function onOffline() {
   alert('You are now offline!');
}

function onOnline() {
   alert('You are now online!');
}
When we start the app connected to the network, onOnline function will trigger alert.
Cordova Network Online
If we press INFO button the alert will show our network state.
Cordova Network Info
If we disconnect from the network, onOffline function will be called.
Cordova Network Offline

Cordova - Media Capture

This plugin is used for accessing device's capture options.

Step 1 - Installing Media Capture Plugin

To install this plugin, we will open command prompt and run the following code −
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-media-capture

Step 2 - Add Buttons

Since we want to show you how to capture audio, image and video, we will create three buttons in index.html.
<button id = "audioCapture">AUDIO</button>
<button id = "imageCapture">IMAGE</button>
<button id = "videoCapture">VIDEO</button>

Step 3 - Add Event Listeners

The next step is adding event listeners inside onDeviceReady in index.js.
document.getElementById("audioCapture").addEventListener("click", audioCapture);
document.getElementById("imageCapture").addEventListener("click", imageCapture);
document.getElementById("videoCapture").addEventListener("click", videoCapture);

Step 4A - Capture Audio Function

The first callback function in index.js is audioCapture. To start sound recorder, we will use captureAudio method. We are using two options − limit will allow recording only one audio clip per single capture operation and duration is number of seconds of a sound clip.
function audioCapture() {
   var options = {
      limit: 1,
      duration: 10
   };
   navigator.device.capture.captureAudio(onSuccess, onError, options);

   function onSuccess(mediaFiles) {
      var i, path, len;
      for (i = 0, len = mediaFiles.length; i < len; i += 1) {
         path = mediaFiles[i].fullPath;
         console.log(mediaFiles);
      }
   }

   function onError(error) {
      navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
   }
}
When we press AUDIO button, sound recorder will open.
Cordova Capture Audio
Console will show returned array of objects that users captured.
Cordova Capture Audio Log

Step 4B - Capture Image Function

The function for capturing image will be the same as the last one. The only difference is that we are using captureImage method this time.
function imageCapture() {
   var options = {
      limit: 1
   };
   navigator.device.capture.captureImage(onSuccess, onError, options);

   function onSuccess(mediaFiles) {
      var i, path, len;
      for (i = 0, len = mediaFiles.length; i < len; i += 1) {
         path = mediaFiles[i].fullPath;
         console.log(mediaFiles);
      }
   }

   function onError(error) {
      navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
   }
}
Now we can click IMAGE button to start the camera.
Cordova Capture Image
When we take picture, the console will log the array with image object.
Cordova Capture Image Log

Step 4C - Capture Video Function

Let's repeat the same concept for capturing video. We will use videoCapturemethod this time.
function videoCapture() {
   var options = {
      limit: 1,
      duration: 10
   };
   navigator.device.capture.captureVideo(onSuccess, onError, options);

   function onSuccess(mediaFiles) {
      var i, path, len;
      for (i = 0, len = mediaFiles.length; i < len; i += 1) {
         path = mediaFiles[i].fullPath;
         console.log(mediaFiles);
      }
   }

   function onError(error) {
      navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
   }
}
If we press VIDEO button, the camera will open and we can record the video.
Cordova Capture Video
Once the video is saved, the console will return array once more. This time with video object inside.
Cordova Capture Video Log