How to install and call cordova plugins - android

I have installed cordova (version 3.3) and built a sample project using these commands:
$ cordova create hello com.example.hello "HelloWorld"
$ cd hello
$ cordova platform add android
$ cordova build
and imported the project into Eclipse (according to http://cordova.apache.org/docs/en/3.3.0/guide_platforms_android_index.md.html#Android%20Platform%20Guide). I am able to successfully run the app from Eclipse by selecting Run As → Android Application.
Now I want to make use of cordova's notification ablities. I added the plugins (following this guide: http://cordova.apache.org/docs/en/3.3.0/cordova_notification_notification.md.html#Notification) with the commands:
$ cordova plugin add org.apache.cordova.dialogs
$ cordova plugin add org.apache.cordova.vibration
and when I type:
$ cordova plugin ls
it correctly lists the plugins I just added.
I return to Eclipse and paste the following code into assets/www/index.html (overwriting the existing code in index.html):
<!DOCTYPE html>
<html>
<head>
<title>Notification Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
// Empty
}
// Show a custom alert
//
function showAlert() {
navigator.notification.alert(
'You are the winner!', // message
'Game Over', // title
'Done' // buttonName
);
}
// Beep three times
//
function playBeep() {
navigator.notification.beep(3);
}
// Vibrate for 2 seconds
//
function vibrate() {
navigator.notification.vibrate(2000);
}
</script>
</head>
<body>
<p>Show Alert</p>
<p>Play Beep</p>
<p>Vibrate</p>
</body>
</html>
When I deploy it to a device, it displays three links (Show Alert, Play Beep and Vibrate). When I press on these I expect the corresponding native notification to occur, but it doesn't. Instead I get the following error messages (displayed in LogCat):
Show alert: Uncaught ReferenceError: showAlert is not defined:45
Play Beep: Uncaught ReferenceError: playBeep is not defined:46
Vibrate: Uncaught ReferenceError: vibrate is not defined:47
How am I supposed to fix these errors?
Thanks in advance!

Have you tried to update the files and run everything from the www folder instead?

In your question you didn't mention updating the config.xml and AndroidManifest.xml files as noted in the API documentation. I'll copy them here for reference.
(in app/res/xml/config.xml)
<feature name="Notification">
<param name="android-package" value="org.apache.cordova.dialogs.Notification" />
</feature>
<feature name="Vibration">
<param name="android-package" value="org.apache.cordova.vibration.Vibration" />
</feature>
(in app/AndroidManifest.xml)
<uses-permission android:name="android.permission.VIBRATE" />
For further clarification see the answer to this question.
Should a phonegap plugin be declared in the config.xml file?

Related

cordova-plugin-file to play video file from extSD

I am needing to have my cordova wrapped html show a picture and run a video file located off the root of the external SD. There did not seem to be a place to ask these questions on the git hub for the cordova-plugin-file.
A) I am not sure I understand what path to use in 2 B&C below in order to accomplish this if the files are in those two sub directories off the root?
B) Are ALL those values in 3 B necessary if all I need is access to the ext SD?
Here is what I know from the documentation so far ... but obviously I don't have it all correct because I get the error (see below)
1) Set up environment from CMD line
cordova create MyApp
cd /MyApp
cordova platform add android#latest
cordova plugin add cordova-plugin-whitelist
cordova plugin add cordova-plugin-file
corddova build android (after step 3 below)
2) Add these to index.html
A) cdvfile: scheme to Content-Security-Policy meta tag of the index page, e.g.:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap:cdvfile:https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src
B) <img src="cdvfile:///img/logo.png" />
C) <p>Play video</p>
3) Add these to config.xml
A) <access origin="cdvfile://*" />
B) <preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,assets,root" />
The error I get on the Android when clicking on the video link is ...
net::ERR_UNKNOWN_URL_SCHEME (cdvfile:video/0001_a1.mp4)
===========
EDIT #1
Now trying recommendation by #DaveAlden ... using plugin called [cordova.plugins.diagnostic][2] with this configuration to locate root path on ExtSD to play video BUT get the error (see below) ...
config.xml
<preference name="android-minSdkVersion" value="14" />
<preference name="android-targetSdkVersion" value="14" />
<preference name="android-maxSdkVersion" value="25" />
<plugin name="cordova-plugin-whitelist" spec="1" />
<plugin name="cordova.plugins.diagnostic" />
Index.html
<body>
<!-- Set up path to ExtSD on Android -->
<script>
function getSdRefAndEmbed(){
cordova.plugins.diagnostic.getExternalSdCardDetails(function(details){
details.forEach(function(detail){
if(detail.type === "root"){
cordova.file.externalSdCardRoot = detail.filePath;
embedMedia();
}
});
}, function(error){
console.error(error);
});
}
function embedMedia(){
$('.extSdVideo').each(function(){
$(this).attr('href', cordova.file.externalSdCardRoot + $(this).attr('href'));
});
}
$(document).on('deviceready', getSdRefAndEmbed);
$(document).on('pageinit', embedMedia);
</script>
<!-- Play video file -->
<a class="extSdVideo" href="video/0001_a1.mp4" id="0001_a1"> a1 </a>
</body>
Application Error
net::ERR_FILE_NOT_FOUND (file:///android_assest/www/HHR/hhr-cm_cameroon-cm1-fra-spa/‌​‌​hhr/hhr-cm_cameroo‌​n-‌​cm1-fra-spa/vide‌​o/00‌​01_a1.mp4
Tried placing the 0001_a1.mp4 in either of these two directories...
extSDRoot/video/0001_a1.mp4
and/or
extSDRoot/www/HHR/hhr-cm_cameroon-cm1-fra-spa/‌​‌​hhr/hhr-cm_cameroo‌​n-‌​cm1-fra-spa/vide‌​o/00‌​01_a1.mp4
=================== EDIT #2
#DaveAlden Suggested trying these three things...
1) Put console.dir(details) inside of getExternalSdCardDetails() to see what native paths the plugin is finding.
RESULT: it gives the same path in the error message
Application Error
net::ERR_FILE_NOT_FOUND
(file:///android_asset/www/hhr/cm_cameroon-cm1-fra-spa/0001_a1.mp4)
2) Try the example project (https://github.com/dpa99c/cordova-diagnostic-plugin-example) on the same device to see if the ext SD example works.
RESULT 1: The build for the example project failed...
BUILD FAILED Total time: 47.426 secs Error: cmd: Command failed with exit code 1 Error output: F:\DIAGNOSTIC_WORKING\cordova-diagnostic-plugin-example\plat‌​forms\android\build\ intermediates\res\merged\debug\values-v24\values-v24.xml:3: AAPT: Error retrievi ng parent for item: No resource found that matches the given name 'android:TextA ppearance.Material.Widget.Button.Borderless.Colored'.
#DaveAlden response to the Build Fail...
You have missing/outdated Android SDK components in your build
environment and/or are using an outdated version of cordova-android
platform. See documentation
(https://github.com/dpa99c/cordova-diagnostic-plugin#building-for-android)
and this issue
(https://github.com/dpa99c/cordova-diagnostic-plugin/issues/161).
My Actions:
I checked the Android SDK Manager to see that all API levels were on the same level for the required products by running this command
C:> Android -v
Android SDK Tool 25.2.5
SDK platform 25
Android Support Repository 46
Google Play services 39
Google Repository 45
I ran this command...
cordova platform check android
Got this result...
F:\DIAGNOSTIC_WORKING\cordova-diagnostic-plugin-example>cordova platform check android
Subproject Path: CordovaLib
android # 6.1.2; current did not install, and thus its version cannot be determined
Why do I get this "current did not install"? Could this be the issue why the diagnostic plugin is not finding the correct path for the extSD?
I ran this command...
cordova platform rm android && cordova platform add android#latest && cordova build android
Now the Build Succeeded for Example Project!
See screen shot of the example diagnostic app showing path to the extSD. This path looks very different from the path I am getting when I run the diagnostic plugin in my app.
Note the button "Write External SD File" did not write anything when pressed. I checked with my file manager.
The path given for the Example Project is very different for the path that the diagnostic plugin gives for my app (see mine below). These results were from the same Galaxy S7.
net::ERR_FILE_NOT_FOUND (file:///android_assest/www/HHR/hhr-cm_cameroon-cm1-fra-spa/‌​‌​hhr/hhr-cm_cameroo‌​n-‌​cm1-fra-spa/vide‌​o/00‌​01_a1.mp4
I ran this command for my app but no change ...
cordova platform rm android && cordova platform add android#latest && cordova build android
3) #DaveAlden suggested running a debug using Chrome... I'll do that next.
Found this...
============= EDIT 3 SUCCESSFULLY played video from extSD using cordova-diagnostic-plugin
Here's how...
The final hurdle was that because I have an Android 6+ phone I had to also add a function to check for run time permission to read the extSD. The code kept bombing with the error show in Edit #2 (see above) like it was trying to see an internal path. Once I added the function to check for run time permission it finally gave the correct external path. Hint ... it is not enough to just provide the permission in the manifest. You can read about it here. Thanks #DaveAlden for your example project!
https://github.com/dpa99c/cordova-diagnostic-plugin-android-runtime-example
Android runtime permissions
Android 6 / API 23 introduces the concept of runtime permissions. Similar to >iOS, certain "dangerous" permissions must be requested at runtime in addition >to being listed in the Android manifest.
Runtime permissions only apply if the device/emulator the app is running on has >Android 6.0 or above AND the app is built using API 23 or higher. For Cordova, >this means using the Cordova Android platform version 5.0.0 or above. If the >app is built with version 4.x or below (API 22 or below), runtime permissions >do not apply - all permissions are granted at installation time.
Add to Config.xml
<access origin="*" />
<plugin name="cordova-plugin-whitelist" version="*" />
<plugin name="cordova.plugins.diagnostic" version="*" />
<plugin name="cordova-plugin-file" version="*" />
<preference name="android-minSdkVersion" value="21" />
<preference name="android-targetSdkVersion" value="23" />
<config-file target="AndroidManifest.xml" parent="/*">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Thanks to #DaveAlden for this code... I only added the function to check the run time read permission. Dave you should just add this code for reading media files from the extSD to your project example so you don't have to help the next person as much as you did me. :)
Add to Index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src * gap://ready file:; style-src 'self' 'unsafe-inline'; img-src * 'self' data:; script-src * 'unsafe-inline' 'unsafe-eval'">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<h3>Play video and img file</h3>
<img class="extSdImg" src="img/image1.png"/>
<img class="extSdImg" src="img/image2.png"/>
<p>
<a class="extSdVideo" href="video/video1.mp4">Play video</a>
</p>
<p>
<a class="extSdVideo" href="video/video2.mp4">Play video</a>
</p>
</body>
</html>
Add to Index.js
function authorizerequestExtSD() {
cordova.plugins.diagnostic.requestExternalStorageAuthorization(function(status){
console.log("Successfully requested external storage authorization: authorization was " + status);
checkState();
getSdRefAndEmbed();
}, function(error){
console.error(error);
});
}
function getSdRefAndEmbed(){
cordova.plugins.diagnostic.getExternalSdCardDetails(function(details){
details.forEach(function(detail){
if(detail.type === "root"){
cordova.file.externalSdCardRoot = detail.filePath;
embedMedia();
}
});
}, function(error){
console.error(error);
});
}
function embedMedia(){
$('.extSdImg').each(function(){
$(this).attr('src', cordova.file.externalSdCardRoot + $(this).attr('src'));
});
$('.extSdVideo').each(function(){
$(this).attr('href', cordova.file.externalSdCardRoot + $(this).attr('href'));
});
}
$(document).on('deviceready', authorizerequestExtSD);
$(document).on('pageinit', embedMedia);
Add local file copy of jQuery (found one in this project https://github.com/dpa99c/cordova-diagnostic-plugin-example):
jquery-2.1.3.min.js
Your approach is not going to work: cdvfile:// is an internal pseudo-protocol defined by cordova where the first part of the path defines an internal reference point (cdvfile://localhost/persistent|temporary|another-fs-root*/path/to/file) whereas 2B and 2C are defining paths as if relative to the root of the external SD card root.
Note that cordova-plugin-media will not help you, since it's only for playing audio and does not itself resolve file locations.
If your media files are on an external removable SD card (e.g. in Samsung Galaxy devices), cordova-plugin-file does not provide a reference to access this location. The "external" references used by cordova-plugin-file (e.g. cordova.file.externalRootDirectory) actually point to an internal memory location - /scard/. This is because not all devices have removable external SD cards (e.g. Google Nexus) so /sdcard is an "emulated" storage location which is guaranteed to exist on all Android devices.
If you wish to read files from the external removable SD card, you can do so using cordova-diagnostic-plugin to obtain a valid filepath reference to the external SD card root. Note that this will need to by done dynamically in JS as opposed to hardcoding static paths in HTML:
index.html
<body>
<img class="extSdImg" src="img/image1.png"/>
<img class="extSdImg" src="img/image2.png"/>
<p><a class="extSdVideo" href="video/video1.mp4">Play video</a></p>
<p><a class="extSdVideo" href="video/video2.mp4">Play video</a></p>
</body>
index.js
function getSdRefAndEmbed(){
cordova.plugins.diagnostic.getExternalSdCardDetails(function(details){
details.forEach(function(detail){
if(detail.type === "root"){
cordova.file.externalSdCardRoot = detail.filePath;
embedMedia();
}
});
}, function(error){
console.error(error);
});
}
function embedMedia(){
$('.extSdImg').each(function(){
$(this).attr('src', cordova.file.externalSdCardRoot + $(this).attr('src'));
});
$('.extSdVideo').each(function(){
$(this).attr('href', cordova.file.externalSdCardRoot + $(this).attr('href'));
});
}
$(document).on('deviceready', getSdRefAndEmbed);
$(document).on('pageinit', embedMedia);

console.log not working when running an Android app in Cordova

I have a basic Cordova application with a simple console.log() function at the end.
My index.html file looks as follows:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("Device is ready!");
}
</script>
</body>
</html>
As you can see it's basically the same as the automatically generated file with some console.log script at the bottom.
Unfortunately when I run the app on Android using cordova emulate android, I cannot seem to find the output from console.log(..) anywhere. However, it works fine on browsers.
console.log(..)only works on browser console, not on command line.
To get log that appears on your app use alert(...);.
Anyway if you wanted to see your logs by consol.log() you should use an IDE like Android Studio or use ddms located where your adb is installed. (run ddms.bat)
Use
cordova plugin add cordova-plugin-console
This plugin will enable console logging.
It has various methods for console printing
console.log
console.error
console.exception
console.warn
console.info
console.debug
console.assert
console.dir
console.dirxml
console.time
console.timeEnd
console.table
By default plugin is not installed so you will have to add it manually.
Reference.
Regards.

jQuery Mobile Phonegap Cordova Events not working and Firing

We have to build a mobile application using HTML5, to be worked on Android and IOS.
We started by using jQuery Mobile Framework to manage the pages and actions.Every thing is fine. The problem is when we use the Apache Cordova API, to get some info from the device like the uuid, and manage an Exit Application Button, nothing working!...
We use the Cordova Script which get from this Google Link.
We put the line below into the config.xml file before building the app pn phonegap:
<plugin name="Notification" value="org.apache.cordova.notification.Notification" />
We use the official documentation presented From Cordova Phonegap Site , which is below:
<!DOCTYPE html>
<html>
<head>
<title>Notification Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
// Empty
}
// alert dialog dismissed
function alertDismissed() {
// do something
}
// Show a custom alertDismissed
//
function showAlert() {
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
}
</script>
</head>
<body>
<p>Show Alert</p>
</body>
</html>
But any thing not happened after building the sources to the Android Platform. No Events fired or anything related to phonegap!
We have searching many results and suggestions to resolve that but without any results!
The applications has been tested on Android 4.3.
Thank you for your suggestions.
You are using a very old version of cordova (2.5), the latest version is 3.5 and here is the proper location for documentation and download: http://cordova.apache.org/
Try putting a console.log or alert inside onDeviceReady function to make sure cordova is initialised properly, but I think your problem is with the cordova project setup. Try creating a fresh project using 3.5 with command line as explained in documentation first.
Try adding the device plugin from the command line:
phonegap plugin add org.apache.cordova.device
This has worked for me in the past. The command is the same for Windows, Linux and Mac. Then put something into your deviceready event to ensure that it's being fired.
Using cordova 2.9.0 and upper cans resolve this issues.
theses lines are needed to put in the config.xml file:
<feature name="Device">
<param name="android-package" value="org.apache.cordova.device.Device" /> // android
<param name="ios-package" value="CDVDevice" /> IOS
</feature>
<!-- -->
<plugins>
<plugin name="App" value="org.apache.cordova.App" />
<plugin name="Device" value="org.apache.cordova.Device" />
<plugin name="Device" value="CDVDevice" />
</plugins>
<!-- phonegap plugins -->
<gap:plugin name="org.apache.cordova.console" />
<gap:plugin name="org.apache.cordova.device" version="0.2.8" />
<gap:plugin name="org.apache.cordova.dialogs" />

Phonegap Android Splash Screen not working

I am building and Application using Phonegap. Following is my problem:
I did cordova create hello, then I did cordova platform add android , followed by cordova plugin add org.apache.cordova.splashscreen and then finally cordova build android.
My top level config.xml contains:
<preference name="SplashScreen" value="screen" ></preference>
<feature name="SplashScreen">
<param name="android-package" value="org.apache.cordova.splashscreen.SplashScreen" />
</feature>
My index.html from www folder contains
<script src="cordova.js"></script>
<script src="cordova_plugins.js"></script>
<script src="js/main.js"></script>
My main.js somewhere contains:
navigator.splashscreen.hide();
I imported
<project root directory>/platforms/android into eclipse ADT.
I guess navigator.splashscreen.hide() is not working because splashscreen gets hide on 3000 ms only, which is by default and I am getting this on my ADT Logcat:
06-10 12:33:39.641: W/System.err(7663): java.lang.ClassNotFoundException: org.apache.cordova.splashscreen.SplashScreen
and a large dump regarding the same and then
06-10 12:33:39.651: D/PluginManager(7663): exec() call to unknown plugin: SplashScreen

Android PhoneGap HTML5video

I am looking for an HTML 5 video plugin for PhoneGap.
I found a plugin at GitHub but there maybe something wrong as I have the following issues:
I don't know where to place the plugin.xml
I don't know how to to link with it <video> tag
and it's not working with PhoneGap
this javascript function now
function start(){
window.plugins.html5video.initialize({"video1" : "movie.mp4"});
window.plugins.html5video.play("video1");
}
04-24 09:52:59.305: E/Web Console(740): Uncaught TypeError: Cannot call method 'initialize' of undefined at file:///android_asset/www/index.html:44
After several attempts I solved this way:
I have installed Git
I have installed the plugin HTML5Video for Cordoba with command cordova plugin add https://github.com/jaeger25/Html5Video.git (with this command, the project has run automatically configured to use the plugin)
I created the folder platforms\androis\res\raw\ where I copied the video splash.mp4
In the html file (in my case \www\splash.html) I insert this code in HEAD:
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="Html5Video.js"></script>
<script>
// Wait for device API libraries to load
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// device APIs are available
//
function onDeviceReady() {
window.plugins.html5Video.initialize({
"splashvideo" : "splash.mp4"
})
window.plugins.html5Video.play("splashvideo");
}
</script>
and this is the BODY code
<body onload="onLoad()">
<video id="splashvideo" autobuffer controls="false"></video>
</body>
It's work for me ;)

Categories

Resources