I am new to cordova and plugins..
I have created a webappp, in my app i need to download files from server..
so i have used cordova background download plugin.. and i m using intel xdk.. so i have impoted plugin there..
cordova plugin github
now.. when i download file, on notification bar its showing downloading file.. BUT ITS SHOWING PLUGIN PACKAGE NAME WHILE DOWNLOADING.... but file save as its original name.... here it is my code..
var app = {
fileName: "tera hone.mp3",
uriString: "https://api.soundcloud.com/tracks/133667943/stream?client_id=67739332564a7130c3a05f90f2d02d2e", // 38.3 MB
// Application Constructor
initialize: function() {
this.bindEvents();
},
downloadFile: function(uriString, targetFile) {
var lblProgress = document.getElementById('lblProgress');
var complete = function() {
lblProgress.innerHTML = 'Done';
};
var error = function (err) {
console.log('Error: ' + err);
lblProgress.innerHTML = 'Error: ' + err;
};
var progress = function(progress) {
lblProgress.innerHTML = (100 * progress.bytesReceived / progress.totalBytesToReceive) + '%';
};
try{
var downloader = new BackgroundTransfer.BackgroundDownloader();
// Create a new download operation.
var download = downloader.createDownload(uriString, targetFile);
// Start the download and persist the promise to be able to cancel the download.
app.downloadPromise = download.startAsync().then(complete, error, progress);
} catch(err) {
console.log('Error: ' + err);
}
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
document.getElementById('btnStart').addEventListener('click', this.startDownload);
document.getElementById('btnStop').addEventListener('click', this.stopDownload);
document.getElementById('btnFileInfo').addEventListener('click', this.getFileInfo);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
app.startDownload();
},
startDownload: function () {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile(app.fileName, { create: true }, function (newFile) {
app.downloadFile(app.uriString, newFile);
});
});
},
stopDownload: function () {
app.downloadPromise && app.downloadPromise.cancel();
},
getFileInfo: function () {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
fileSystem.root.getFile(app.fileName, { create: true }, function (fileEntry) {
fileEntry.file(function (meta) {
document.getElementById('lblFileInfo').innerHTML =
"Modified: " + meta.lastModifiedDate + "<br/>" +
"size: " + meta.size;
});
}, function(error) {
document.getElementById('lblFileInfo').innerHTML = "error: " + error;
});
});
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
this is my javascript file invoke from my html file.. from cordova plugin..
also when i stop downloading.. it stops but app suddenly crashed everytime....
sorry for my bad english..
Related
I'm developing an Ionic App using Cordova File Transfer Plugging to download set of images into the device. Currently it downloads images successfully and I need to restrict 1 download job at a time. Following is the code :
$scope.activeDownload = false;
// Download the current magazine
$scope.downloadMagazine = function() {
if($rootScope.user.user_id == undefined) {
$scope.showLoginAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Oops!',
template: "Your must login to download magazines"
});
};
$scope.showLoginAlert();
return;
}
document.addEventListener('deviceready', function () {
var dirName = $rootScope.currentIssue.slug+'_VOL_'+$rootScope.currentIssue.vol+'_ISU_'+$rootScope.currentIssue.issue;
// First create the directory
$cordovaFile.createDir(cordova.file.dataDirectory, dirName, false)
.then(function (success) {
var count = 1;
$scope.loadedCount = 0;
$ionicLoading.show({template : "<progress max=\"100\" value=\"0\" id=\"dw-prog\"></progress><p> Downloading pages...</p><p>Please wait...</p> <button ng-controller=\"magazineIssueCtrl\" ng-click=\"downloadBackground()\" class=\"button button-full button-positive\">Continue in Background</button>"});
angular.forEach($scope.pages, function(value, key) {
function wait() {
if($scope.proceed == false) {
window.setTimeout(wait,50);
}
else {
var imgName = count+".png";
$scope.saveImage(dirName,value.link,imgName); // Then save images one by one to the created directory.
count++;
}
};
wait();
});
}, function (error) {
// Directory already exists means that the magazine is already downloaded.
$scope.showDownloadedAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Why worry!',
template: "Your have already downloaded this magazine. You can view it on downloads"
});
};
$scope.showDownloadedAlert();
});
}, false);
};
// Save a image file in a given directory
$scope.saveImage = function(dir,imgUrl,imageName) {
$scope.proceed = false;
var url = imgUrl;
var targetPath = cordova.file.dataDirectory+ dir+"/" + imageName;
var trustHosts = true;
var options = {};
// Download the image using cordovafiletransfer plugin
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(result) {
$scope.proceed = true;
$scope.loadedCount ++;
document.getElementById("dw-prog").value = ($scope.loadedCount / $scope.pages.length )*100;
if($scope.loadedCount == $scope.pages.length) {
$scope.activeDownload = false;
$ionicLoading.hide();
$scope.showDownloadSuccessAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Success!',
template: "Your magazine successfully downloaded. You can view it on Downloads!"
});
};
$scope.showDownloadSuccessAlert();
}
}, function(err) {
//alert(JSON.stringify(err));
}, function (progress) {
});
};
// Continue download in background
$scope.downloadBackground = function () {
$scope.activeDownload = true;
$ionicLoading.hide();
$scope.showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Sent to Background!',
template: "You can view it on downloads tab"
});
};
$scope.showAlert();
$rootScope.downloadInBackground.dirName = $rootScope.currentIssue.slug+'_VOL_'+$rootScope.currentIssue.vol+'_ISU_'+$rootScope.currentIssue.issue;
};
Here everything happens as expected but I need the $scope.activeDownload variable to be true when a download is sent to background so that I can refer to that variable before starting another download job. But the problem here is that variable seems to be set to false always. Could you please help me to identify the problem here?
I've tried to create a default Phonegap barcode scanner trough plugin basic installation, but it didn't work well. I don't know what's happening. Here is my code:
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
console.log('-');
console.log(cordova);
console.log('-');
console.log(cordova.plugins.barcodeScanner);
console.log('-');
cordova.plugins.barcodeScanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
Cancelled: " + result.cancelled);
},
function (error) {
alert("Scanning failed: " + error);
}
);
}
};
It's basically the default Phonegap plugin panel. The problem is that it doesn't recognize the cordova.plugin.barcodeScanner. I've created the project trough the Phonegap Windows tool and ran the cordova plugin add cordova-plugin-statusbar command inside the folder. Please help me, I can't see any code example of this working. Thanks.
you can call getScanner() function onClick event in javascript Read More Here
function getScanner(){
cordova.plugins.barcodeScanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
function (error) {
alert("Scanning failed: " + error);
}
); }
let me know if its not working..
I'm trying to test a Push Notification app with Phonegap. I registered my project at GCM and added my Project Number at the SenderID var. Here's the code:
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
var pushNotification = window.plugins.pushNotification;
alert("Register called");
pushNotification.register(this.successHandler, this.errorHandler,{"senderID":"543180841340","ecb":"app.onNotificationGCM"});
},
successHandler: function(result) {
alert('Callback Success! Result = '+result)
},
errorHandler:function(error) {
alert(error);
},
onNotificationGCM: function(e) {
switch( e.event )
{
case 'registered':
if ( e.regid.length > 0 )
{
console.log("Regid " + e.regid);
alert('registration id = '+e.regid);
document.getElementById('regId').value = e.regid;
}
break;
case 'message':
alert('message = '+e.message+' msgcnt = '+e.msgcnt);
break;
case 'error':
alert('GCM error = '+e.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
},
onNotificationAPN: function(event) {
var pushNotification = window.plugins.pushNotification;
alert("Running in JS - onNotificationAPN - Received a notification! " + event.alert);
if (event.alert) {
navigator.notification.alert(event.alert);
}
if (event.badge) {
pushNotification.setApplicationIconBadgeNumber(this.successHandler, this.errorHandler, event.badge);
}
if (event.sound) {
var snd = new Media(event.sound);
snd.play();
}
}
};
I get the first alert ("Register called") but not the regID. I'm using the Phonegap Developer app for Android and the "phonegap serve" command to get it live. I tried to download the app too, but still doesn't work.
Firing the ("Register called") Doesn't mean that the push notification registration is instantiated but it means that receivedEvent is called and that is good.
1- Make sure that push notification plugin is included in config.xml and the pushNotification object is not null.
to include the plugin to config.xml: add <gap:plugin name="com.phonegap.plugins.pushplugin" />
2- Make sure that the sender id is OK "no typos".
I made a little phonegap/cordova application, and I need to access an object inside my .js file. Turns out I have no idea on how to change the structure of my code to make this happen.
Here is my index.html code :
<!DOCTYPE html>
<html>
<head>
<title>NFC tag ID reader</title>
<script type="text/javascript" src="js/index.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() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwriteend = function(evt) {
console.log("contents of file now 'some sample text'");
writer.truncate(11);
writer.onwriteend = function(evt) {
console.log("contents of file now 'some sample'");
writer.seek(4);
writer.write(" different text");
writer.onwriteend = function(evt){
console.log("contents of file now 'some different text'");
}
};
};
writer.write("some sample text");
//MAKE THIS OBJECT GLOBAL ?
}
function fail(error) {
console.log(error.code);
}
</script>
</head>
<body>
<div class="app">
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
And here is my index.js code :
var app = {
/* Application constructor */
initialize: function() {
this.bindEvents();
console.log("Starting NFC Reader app");
},
/* bind any events that are required on startup to listeners: */
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
/* this runs when the device is ready for user interaction: */
onDeviceReady: function() {
nfc.addTagDiscoveredListener(
app.onNfc, // tag successfully scanned
function (status) { // listener successfully initialized
app.displayCpt("<b>"+cpt+"</b>" + ' personnes restantes.');
app.displayBjr("\n");
app.displayBjr("Identifiez-vous:");
},
function (error) { // listener fails to initialize
app.display("NFC reader failed to initialize " +
JSON.stringify(error));
}
);
},
/* displays tag ID from #nfcEvent in message div: */
onNfc: function(nfcEvent) {
var tag = nfcEvent.tag;
var nfcUid = nfc.bytesToHexString(tag.id);
var myDb = {
"04c85ccab52880": {
"name": "name",
"firstname": "fname",
"societe": "work"
}
var mapped = Object.keys(myDb).map(function(uid){
return (myDb[uid].uid = uid) && myDb[uid];
});
for(var i = 0; i < mapped.length ; i++){
if(mapped[i]['uid'] != nfcUid){
mapped[i]['uid'] += 1;
} else {
mapped[i]['uid'] = nfcUid;
app.display(mapped[i]['name'] + ' ' + mapped[i]['firstname'] + ', ' + mapped[i]['societe']);
writer.write(mapped[i]['name'] + ' ' + mapped[i]['firstname'] + ', ' + mapped[i]['societe']);
//I WOULD NEED THIS WRITER USABLE IN ORDER TO WRITE MY ARRAY CONTENT INTO A FILE
}
}
},
}; // end of app
I think my writer object needs to be global in order to make the mapped array write into a file, but I can't find a way to do that.. Any ideas ?
Thanks
Have you tried putting var writer outside of everything and removing it from the arguments list of gotFileWriter(writer)? That should make it a global variable. Note that this isn't exactly the best of programming practices, one should avoid global variables where possible.
I am trying to load xml data and everything works good, but I would like reload xml data when device resume.
This is my code, and I don't know where to paste function for load on resume. Thanks for advices ;-)
var TITLE = "Example";
var XMLsoubor = "example.xml";
var entries = [];
var selectedEntry = "";
//listen for detail links
$(".contentLink").live("click", function () {
selectedEntry = $(this).data("entryid");
});
//Listen for main page
$("#mainPage").live("pageinit", function () {
//Set the title
$("h1", this).text(TITLE);
$.ajax({
url: XMLsoubor,
success: function (res, code) {
entries = [];
var xml = $(res);
var items = xml.find("event");
$.each(items, function (i, v) {
entry = {
title: $(v).find("id").text(),
link: $(v).find("begin").text(),
description: $.trim($(v).find("description").text())
};
entries.push(entry);
});
//store entries
localStorage["entries"] = JSON.stringify(entries);
renderEntries(entries);
},
error: function (jqXHR, status, error) {
//try to use cache
if (localStorage["entries"]) {
$("#status").html("Error");
entries = JSON.parse(localStorage["entries"])
renderEntries(entries);
} else {
$("#status").html("Error");
}
}
});
});
$("#mainPage").live("pagebeforeshow", function (event, data) {
if (data.prevPage.length) {
$("h1", data.prevPage).text("");
$("#entryText", data.prevPage).html("");
};
});
//Listen for the content page to load
$("#contentPage").live("pageshow", function (prepage) {
//Set the title
$("h1", this).text(entries[selectedEntry].title);
var contentHTML = "";
contentHTML += entries[selectedEntry].description;
contentHTML += '<p/><br><br><br>text';
$("#entryText", this).html(contentHTML);
});
function renderEntries(entries) {
var s = '';
$.each(entries, function (i, v) {
s += '<li>' + v.title + '<br>text</li>';
});
$("#linksList").html(s);
$("#linksList").listview("refresh");
}
Use the eventlistener for "resume". It should be made as soon as deviceready has fired.
http://docs.phonegap.com/en/2.9.0/cordova_events_events.md.html#resume
The very first thing you should have in your script is an event for deviceready because a lot of Cordova things aren't ready until the deviceready event has been fired, so you need to listen for deviceready, like this:
document.addEventListener("deviceready", onDeviceReady, false);
Then you add the other listeners in the onDeviceReady function and begin the rest of your app start up from there:
function onDeviceReady() {
//The device is ready when this function is called
document.addEventListener("resume", appReturnedFromBackground, false);
}
function appReturnedFromBackground() {
//This function is called when the app has returned from the background
alert("The app has returned from the background");
}