Using $cordovaVibration plugin, we can make a device vibrate. Many applications offer this vibrate feature, for example, messaging apps like Hike, WatsApp, etc. offer vibrate as an option when messages are received. You can ask your app user to enable the same.

Create Ionic project.


ionic start vib blank

Then go to project folder vib.


cd vib

Add vibration plugin using.


cordova plugin add cordova-plugin-vibration

Download ngCordova using

https://github.com/driftyco/ng-cordova/archive/master.zip

Include ngCordova js file in index.html.


<script type="text/javascript" src="js/ng-cordova.min.js" ></script>

Now we are going to do a simple vibrate application when the users click the button.

  1. Create a button in index.html
  2. Write code for button click in app.js
  3. Bind the button with function using ng-click

Add controller


<body ng-app="starter" ng-controller="vibctrl">

Add button to <ion-content>.


<button class="button button-positive" ng-click="vibrate()" >Vibrate</button>

The button is bound to vibrate function using ng-click Add ngCordova in angular module.


angular.module('starter', ['ionic','ngCordova'])

Create vibctrl and add vibrate function.


.controller('vibctrl',function($scope,$ionicPlatform,$cordovaVibration){

$scope.vibrate=function()

{

$cordovaVibration.vibrate(100);

}

})

The app.js file


// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules

// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)

// the 2nd parameter is an array of 'requires'

angular.module('starter', ['ionic','ngCordova'])

.run(function($ionicPlatform) {

$ionicPlatform.ready(function() {

    if(window.cordova && window.cordova.plugins.Keyboard) {

    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard

    // for form inputs)

    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

    // Don't remove this line unless you know what you are doing. It stops the viewport

    // from snapping when text inputs are focused. Ionic handles this internally for

    // a much nicer keyboard experience.

    cordova.plugins.Keyboard.disableScroll(true);

    }

    if(window.StatusBar) {

    StatusBar.styleDefault();

    }

});

})

.controller('vibctrl',function($scope,$ionicPlatform,$cordovaVibration){

$scope.vibrate=function()

{

$cordovaVibration.vibrate(100);

}

})

That's all. Vibration app is ready. Generate apk using.


ionic platform add android

ionic build android

 

Tested Device

Samsung J7 Android Lolipop

Source

APK