PhoneGap open file in native app. Build via build.phonegap.com - android

At first:
YES, there are many solutions in StackOverflow, but non of them works in my case.
I got application built in SmartGWT.mobile
I attached config files and all needed files to this build to prepare it for PhoneGap
Application is build via build.phonegap.com site.
It works perfectly fine on Android 4.1.1
I want to:
Download file to local filesystem it is an PDF file - It is working fine using:
var fileTransfer = new FileTransfer();
fileTransfer.download(.....
Open PDF in native app (for eg. Adobe Reader) whichever is installed on android for PDFs - it is not working:
I tried:
(1)
cordova.exec("ChildBrowserCommand.showWebPage", encodeURI(theFile.toURL()) );
(2)
window.plugins.childBrowser.showWebPage(encodeURI(theFile.toURL()));
(3)
window.open(encodeURI(theFile.toURL()), '_blank', 'location=yes');
(4)
even HTML5 plugin for open PDFs by firefox
All variations with "file://" without with "./" at front and so on.
childBrowser shows only white screen, each time adds "http://" at front, window.open - the same.
I finally found something interesting like WebIntent, so i did:
window.plugins.webintent.startActivity({
action: window.plugins.webintent.ACTION_VIEW,
type: "application/pdf",
url: encodeURI(theFile.toURL().substring(7))},
function() {},
function() {alert('Failed to open URL via Android Intent')}
);
but its not working due to fact that phonegap-build not attaching class file and It can not find WebIntent Class
I declare this plugin using in config.xml:
<gap:plugin name="com.borismus.webintent.WebIntent" />
Do you know why it is not working, or what I'm doing worng ?
Maybe you know other way to open file just like that in native app, it suppose to be simple
I just want my app to download and show (in native app) the PDF for user.

don's FileOpener version have worked on my app cordova 3.0
phonegap local plugin add https://github.com/don/FileOpener
all the xmls, plugin, etc are then added automatically.
added fileopener.js on index.html
and then
window.plugins.fileOpener.open( path );

$("#page").on('pageshow', function(event, ui) {
if(event.handled !== true)
{
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
event.handled = true;
}
return false;
});
function fail() {
console.log("failed to get filesystem");
}
function gotFS(fileSystem) {
console.log("got filesystem");
// save the file system for later access
console.log(fileSystem.root.fullPath);
window.rootFS = fileSystem.root;
downloadImage(url, fileName);
}
function downloadImage(url, fileName){
var ft = new FileTransfer();
ft.download(
url,
window.rootFS.fullPath + "/" + fileName,
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error" + error.code);
}
);
}

Related

Cordova/Phonegap File Transfer plugin

I'm using Cordova/Phonegap and I want to use a plugin for download a file and put it in Downloads folder. I find the plugin FileTransfer
http://docs.phonegap.com/en/edge/cordova_file_file.md.html#FileTransfer
I'm using this plugin but I don't known the path of folder Download in every device another i want to use the native notification of device...I read that I download the file from remote server but I don't where is and don't show the native console...this is my code in my controller
var fileTransfer = new FileTransfer();
var uri = encodeURI("http://someUrl/tost.pdf");
var fileURL = "/sdcard/Download/tost.pdf";
fileTransfer.download (uri, fileURL, function(entry) {
console.log("download complete: " + entry.toURL());
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
false,
{
headers: {
//"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
Do you know how I can use it with the native notification and the correct path where I must download it?
If you look at the apache/cordova-plugin-file github you can see the locations where you can read from and write to listed in tables for iOS, Android and Blackberry 10.
From the looks of it you are trying to download to a sdcard on Android? The correct url would look like this:
var fileURL = cordova.file.externalRootDirectory+"Download/tost.pdf";
I'm guessing you want to develop you app for iOS and Android, so you should use this url:
var fileURL = cordova.file.dataDirectory+"Download/tost.pdf";
since it's a valid url on both and it's persistent and private.

FileTransfer only partially download files

Tried to download file using Filetransfer Cordova for android but all the files are downloaded partially. It will download just a random number of Bytes (~ 1-1.5 MB) and then fire a success download event.
This is the code:
var uri = encodeURI('http://192.168.1.5:3000/downloads/' + $scope.file.filename);
var trustHost = true;
var options = {};
var fileName = "thisIsAFile.ext";
$ionicPlatform.ready(function () {})
.then(function(){
var fileTransfer = new FileTransfer();
fileTransfer.download(
uri,
"file://mnt/sdcard/Download/" + fileName,
function(entry) {
$ionicPopup.alert({
title: "success".toUpperCase(),
template: JSON.stringify(entry)
})
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
},
trustHost, options);
});
I can easily download files with a browser from the server (either web or mobile version).
The logcat doesn't help or the success object inspection.
All the permissions are set in res/xml/config.xml and everything looks fine in AndroidManifest.xml
I've also tried different file paths and I've tried with cordova.file.* and fileSystem.root
I'm baffled.
I'm using Ionic and ngCordova.
The FileTransfer is file-transfer 0.4.3
I've tried the 0.5 version and it gives me a persistent code 3 error.
Any suggestions?
I've solved this issue by using the res.sendFile() - i'm using node.js - on server-side. I'm not sure why but it seems that the static url - the resource address - need also a response containing the file data.
I hope this could be helpful.

Phonegap 3.5.0 Cordova File API Error: cannot read property 'dataDirectory' of undefined

We have to build an application for iOS and Android using PhoneGap Build and Apache Cordova.
The Phonegap version is 3.5.0. and we want to update the application when an internet connection is available. So we need to download some images files from online server to local file system into the application(iOS and Android).
Here is the example JavaScript code used:
try{
//The directory to store data
var store;
//Used for status updates
var $status;
//URL of our asset
var assetURL = "https://raw.githubusercontent.com/cfjedimaster/Cordova-Examples/master/readme.md";
//File name of our important data file we didn't ship with the app
var fileName = "mydatafile.txt";
//////////////////////
alert("Checking for data file.");
//Check for the file.
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onError);
/////////////////////////////
} catch(e){
alert(e.message);
}
function downloadAsset() {
var fileTransfer = new FileTransfer();
alert("About to start transfer");
fileTransfer.download(assetURL, store + fileName,
function(entry) {
alert("Success!");
appStart();
},
function(err) {
alert("Error!");
console.dir(err);
alert(err);
});
}
//I'm only called when the file exists or has been downloaded.
function appStart() {
// $status.innerHTML = "App ready!";
alert( "App ready!");
}
function onFileSystemSuccess() {
try{
store = cordova.file.dataDirectory;
//Check for the file.
window.resolveLocalFileSystemURL(store + fileName, appStart, downloadAsset);
} catch(e){
alert(e.message);
}
}
function onError(){
alert('error');
}
When launching the application, the result is 2 alerts:
Cannot read property 'dataDirectory' of undefined // alert(e.message);
Error // alert('Error');
Ok, we found the problem!
Inside the app, we have included the cordova js file using the downloaded version of cordova plugin, which included in the js folder of the app.
So instead of the below:
<script type="text/javascript" src="js/cordova.js"></script>
it's recommended to type:
<script type="text/javascript" src="cordova.js"></script>
And Phongap will add the cordova file itself.
It may sound stupid but for all sort of "cannot read property" issues, you may also try
rm -rf plugins
cordova/ionic platform remove xxx
cordova/ionic platform add xxx
It solved my problem which doesn't really make sense at all. Who would expect the plugins themselves are getting wrong?

How to create a protected directory with Phonegap

I am developing a mobile application using Phonegap (Apache Cordova) ver. 3.3.0 for both Android platform and iOS.
This application should be able to create a directory in the mobile device, and access to this to save some files that I have downloaded from external urls.
The application, now, creates correctly the dir, and can access to it to save files.
The problem is that I want to make it a "protected" directory: the directort should be opened only pressing a button in my app, but inaccessible from anywhere else.
How can I realize this?
This is my code, for the creation of the directory.
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
}
function onFileSystemSuccess(fileSystem) {
console.log(fileSystem.name);
console.log(fileSystem.root.name);
var directoryEntry = fileSystem.root;
directoryEntry.getDirectory("myDir", {create: true, exclusive: false}, onDirectorySuccess, onDirectoryFail);
}
function onDirectorySuccess(parent) {
console.log(parent);
//parent.fullPath = path to dir in smartphone
window.localStorage.setItem("directory_path",parent.fullPath);
}
function onDirectoryFail(error) {
alert("Unable to create new directory: " + error.code);
}
function fail(evt) {
console.log(evt.target.error.code);
}
Your idea is impossible in cordova or any other language!
If you wish to accomplish something like that- use sqlite to create folder structure ant save data files there.

Phonegap Android app trigger update programmatically

I am building an Android app that is hosted on a server outside Google Play. I need the app to check for new version and prompt user to update when the app starts.
I built a mechanism to check for new version (the app checks for a file on server and compares version) which is working well. Then I prompt user to update, but if user chooses to proceed with the update, I'm not able to trigger the download and installation of the apk.
I tried simply opening the apk url:
window.open(apkURL);
where the apkURL is the full http link to the .apk file hosted on server.
But it doesn't seem to do anything.
I've been researching but I don't find an answer on how to do this. I found some suggestions using native code, like this post Install Application programmatically on Android but I don't know how to do that from within my Phonegap app.
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("file:///path/to/your.apk"))
.setType("application/vnd.android.package-archive");
startActivity(promptInstall);
Is this the right way to trigger the update? How can something like this be done from within a Phonegap app?
Thanks!
I finally managed to implement this, using the File api and the WebIntent plugin. I will post the solution here in case it helps anyone.
The code downloads the apk from a remote server to the download folder in the sdcard and then triggers the install.
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
fileSystem.root.getFile('download/filename.apk', {
create: true,
exclusive: false
}, function(fileEntry) {
var localPath = fileEntry.fullPath,
fileTransfer = new FileTransfer();
fileTransfer.download(apkURL, localPath, function(entry) {
window.plugins.webintent.startActivity({
action: window.plugins.webintent.ACTION_VIEW,
url: 'file://' + entry.fullPath,
type: 'application/vnd.android.package-archive'
},
function(){},
function(e){
alert('Error launching app update');
}
);
}, function (error) {
alert("Error downloading APK: " + error.code);
});
}, function(evt){
alert("Error downloading apk: " + evt.target.error.code);
});
}, function(evt){
alert("Error preparing to download apk: " + evt.target.error.code);
});
For you guys that use Cordova 3+, a similar solution like that of Vero is possible:
So we're first going to download the .apk file. We need the file-transfer plugin for this.
You can install it with following command:
phonegap local plugin add org.apache.cordova.file-transfer
Secondly, we need another plugin to start a webintent. This webintent prompts the user if there is an update. You can install it with the following command:
phonegap local plugin add https://github.com/Initsogar/cordova-webintent.git
Then, you can use this 2 functions in your code to download the .apk and to prompt the user if
there is an update of the application:
/*
* Uses the filetransfer plugin
*/
function downloadApkAndroid(data) {
var fileURL = "cdvfile://localhost/persistent/CegekaMon.apk";
var fileTransfer = new FileTransfer();
var uri = encodeURI(data.android);
fileTransfer.download(
uri,
fileURL,
function (entry) {
console.log("download complete: " + entry.fullPath);
promptForUpdateAndroid(entry);
},
function (error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
false,
{
}
);
}
/*
* Uses the borismus webintent plugin
*/
function promptForUpdateAndroid(entry) {
window.plugins.webintent.startActivity({
action: window.plugins.webintent.ACTION_VIEW,
url: entry.toURL(),
type: 'application/vnd.android.package-archive'
},
function () {
},
function () {
alert('Failed to open URL via Android Intent.');
console.log("Failed to open URL via Android Intent. URL: " + entry.fullPath);
}
);
}
Sadly you cannot access that kind of native feature within a Phonegap web container without using a plugin, all you can do is link the user to the apk (by opening the native browser for instance) and let him install it.
thank you Vero for answer ... it is help me so much...
there is a problem with your code in cordova file plugin last version.
replace entry.fullPath with entry.toURL() if you use file plugin version 1.0.0 or newer.
if you use entry.fullPath , it throw error 'there is a problem parsing package'.
from file-transfer plugin on github
These paths were previously exposed in the fullPath property of FileEntry and DirectoryEntry objects returned by the File plugin. New versions of the File plugin, however, no longer expose these paths to JavaScript.
If you are upgrading to a new (1.0.0 or newer) version of File, and you have previously been using entry.fullPath as arguments to download() or upload(), then you will need to change your code to use filesystem URLs instead.
FileEntry.toURL() and DirectoryEntry.toURL() return a filesystem URL of the form
cdvfile://localhost/persistent/path/to/file
which can be used in place of the absolute file path in both download() and upload() methods.
Working example in 2018
Based on previous comments I implement this solution
It require:
File plugin
File transfer plugin
Web intent plugin
constructor(public navCtrl: NavController, private transfer: FileTransfer, private file: File, private webIntent: WebIntent) {
const fileTransfer: FileTransferObject = this.transfer.create();
const url = 'urlApkFile';//Modified this
fileTransfer.download(url, this.file.externalDataDirectory + 'file.apk').then((entry) =>
{
webIntent.startActivity({
action: (window).plugins.intentShim.ACTION_INSTALL_PACKAGE,
url: entry.toURL(),
type: 'application/vnd.android.package-archive'
}).then(function () {
//OK
}, function (e) {
alert('Error launching app update' + JSON.stringify(e));
});
}, (error) => {
alert("downdload finish" + JSON.stringify(error));
});
}

Categories

Resources