How to create Android Service Without interval in Appcelerator/titanium Android? - javascript

I want to create a service in appcelerator android where it starts when i click a download button and stops only if download is interrupted/fails or network is not present.
How can i achieve it? I have referred this article
http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Android.Service
I am following this http://docs.appcelerator.com/platform/latest/#!/guide/File_Uploads_and_Downloads for downloading content (videos)
The other problem i face is ,i can't access the UI or the UI becomes almost non responsive, though i can scroll up and down. when download is in progress on android. This is what the UI looks like and i call a function on click of download button.
NOTE: Each element,light gray rectangle is like an accordian control, which toggles(expands and retracts) on click.
I have written a code like this in a videoDownloader.js file
function downloadVideos(video_download_url){
var xhr = Titanium.Network.createHTTPClient({
onload: function() {
// first, grab a "handle" to the file where you'll store the downloaded data
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'video.mp4');
f.write(this.responseData); // write to the file
timeout: 10000
});
xhr.open('GET',video_download_url);
xhr.send();
}

You might want to look into this module which handles everything for you.

Related

Updating Angular 1.2.10 to latest with a minor bug (Overriding a href - third party)

What I did,
I took this angularjs project and did nothing just updated it using nugget package manager to latest angular libraries,
https://github.com/OfficeDev/Learning-Path-Manager-Code-Sample
Issue
When I click on top right settings button, "Working On It" dialog appears and doesn't goes away.
What I investigated
Looking at url, when I click on "cog" url changes from,
https://omapny-ersda819baad8d.apps.com/sites/Dev1/lpm/app.html#/
to
https://omapny-ersda819baad8d.apps.com/sites/Dev1/lpm/app.html#
and dialog appears, but when I add "/" again, dialog disappears
what could be wrong ? I am totally new to AngualrJS
Edit
Most likely because it has this third party link,
<a id="chromeControl_topheader_apptitlelink" href="#" class="ms-core-suiteLink-a" target="_top"><span id="chromeControl_topheader_apptitle">Learning Path Manager</span></a>
How to get around this ?
I fixed this issue by doing followings,
for app title, I had to modify appStartPage to following,
function init() {
// create chrome control settings
spChromeControlData = {
appStartPage: "app.html#/",
Above change is in spAppChrome.js controller file then in same file i added this within init function,
//fix issues with chrome ctrl
$('body').on('click', '.ms-core-menu-root', function () {
$(this).attr("href", "javascript:;")
});
So this will look something like this,
// create the sharepoint chrome control
var nav = new SP.UI.Controls.Navigation("chrome_ctrl_container", spChromeControlData);
// show chrome control
nav.setVisible(true);
// hide top app chrome (image & app name)
nav.setBottomHeaderVisible(false);
//fix issues with chrome ctrl
$('body').on('click', '.ms-core-menu-root', function () {
$(this).attr("href", "javascript:;")
});
logger.log("spAppChrome loaded", null, controllerId);
common.activateController([], controllerId);
}
Let me know if there's any issue.
Thanks

Twitter Programmatically Add Photo

I made a crop screenshot and upload addon for Firefox. I would like to bring a feature that allows user to tweet the images.
Manually (as human does it) the process is this:
Open twitter.com (if not signed in tell user to sign in)
Click "new tweet" this is done
Attach images by doing "Add photo" and browse to file
This is gif of this process:
Then I focus the tab and focus the tweet input box
So user can type the message, then "whose in the photos" if they want, then click tweet. The great thing is with this method, the images have not bothered twitter servers, as the images are not uploaded until users final write off, when they click the "Tweet" button. So user has chance to decide to click X to remove a screenshot attached before hitting "Tweet". I find this way very friendly to the user and to the twitter servers. (If there is a file size limit that can be attached ill do that check in my addon and let user know it cant go in)
The problem
I am trying to automate steps 1-4. I can do 1, 2, and 4 perfectly.
I am trying to programmatically do step 3. It seems Twitter does not use the input[type=file].files html5 api, they are doing some custom javascript. Does anyone know how I can programtically add in images? I have full privelaged javascirpt code access as this is a Firefox addon.
One big reason I cant tell user to go attach themslves is these image are stored in memory for performance, not in file, so I need to attach them programtically.
Code I tried (HTML5 FileList API)
It uses the mozSetFileArray defined here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement and its brother mozSetFileNameArray here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/mozSetFileNameArray
// Step 1 - Open twitter.com (for testing purposes, twitter.com is open in tab 7 so I dont load it here)
var aContentWindow = gBrowser.tabContainer.childNodes[6].linkedBrowser.contentWindow; // gets window of tab 7
var aContentDocument = aContentWindow.document;
// Step 2 - Open tweet modal
var btnNewTweet = aContentDocument.getElementById('global-new-tweet-button');
console.info('btnNewTweet:', btnNewTweet);
if (!btnNewTweet) {
throw new Error('global tweet button not found, probably not logged in');
}
btnNewTweet.click();
// Step 3 - Attach two File instances for test purposes (in production will attach Blob)
var inputAddPhoto = aContentDocument.getElementById('global-tweet-dialog').querySelector('input[type=file]');
console.info('inputAddPhoto:', inputAddPhoto, inputAddPhoto.mozGetFileNameArray);
if (!inputAddPhoto) {
throw new Error('add photo button not found! i have no idea what could cause this');
}
var newFiles = [];
var myFile1 = new File('C:\\Users\\Vayeate\\Pictures\\Screenshot - Tuesday, August 11, 2015 6-33-58 AM.png'); // using local file for testing
var myFile2 = new File('C:\\Users\\Vayeate\\Pictures\\Screenshot - Tuesday, August 11, 2015 6-38-08 AM.png'); // using local file for testing
newFiles.push(myFile1);
newFiles.push(myFile2);
inputAddPhoto.mozSetFileArray(newFiles);
// Step 4 - Focus message field
// var richInputTweetMsg = aContentDocument.getElementById('tweet-box-global');
// richInputTweetMsg.focus(); // not needed because as when the modal opens twitter puts focus into here anways
// Step 5 - Done, now user can choose to type message, tag "whose in photo", and remove previews. The great thing is with this method, the images have not bothered twitter servers, the images are not uploaded until users final write off, when they click the "Tweet" button
Inspection
I did some debugger inspection, I put a breakpoint on drop, and found that it comes in here, there's some kind of add function.

Auto show print dialog on attachment open

i have a requirement. on click of a link, an attachment should open up in a new window (using window.open() ). The attachment is ideally a pdf file which resides on web server virtual directory(using IIS 7 for testing).
The input to the pdf attachment is generally a url, such as-
http://localhost/attachments/sample.pdf
The pdf open up fine but then the page should automatically show the print dialog to the user. The problem is -
1. the attachments are of different sizes.
2. Attachments loading time is variable depending upon its size.
I have tried the following-
1. 'onload' event for body/iframe.
2. jQuery load function to track the loading of the file.
3. $.get operation by enabling CORS on my requested content.
but none of them worked.
here's what i have tried-
var dom = window.open( '', '', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
dom.document.writeln('<html><title>Attachment</title><head>');
dom.document.writeln('<script type=\'text/javascript\' language=\'javascript\' src=\'http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js\'><\/script>');
dom.document.writeln('<script type=\'text/javascript\' language=\'javascript\'>' );
dom.document.writeln('$(document).ready(function() { /*load/get function goes here */});');
dom.document.writeln('<\/script>')
dom.document.writeln('</head><body><iframe width="100%" height="100%" id="container" type="application\/pdf" src="http://localhost/attachments/sample.pdf"></iframe></body></html>');
dom.document.close();
Is there any way possible to track the loading of the attachment because i am completely out of options now?
If you can modify the PDFs themselves, you can add a print function to the file itself which would work around the issue of tracking when the iframe is loaded.

Ajax to make browser Load

1- OPEN FIREBUG, on the console tab
2- OPEN YOUR GMAIL ACCOUNT,
3- when gmail is loaded, click on one of your label (at the left under the draft box)
4- WITH FIREBUG YOU SEE THAT THE PAGE DOES NOT COMLETLY RELAOD SINCE ALL PREVIOUS ACTION STILL THERE FOR THE CURRENT DOCUMENT, BUT THE BROWSER COMPLETLY ACT LIKE THE PAGE HAVE BEEN RELOADED, stop button browser own loading effect, etc...)
5- !!!!! this is it..!!!!
Does some on have a clue on how site like Gmail can make the browser load on ajax call ( I mean show the loading icon and all, history, etc)
I already know what to check for the history navigation but how in the world they can make the browser to act like this was a simple link that load a complete new page.
from what I see with things like firebug Gmail basically retrieve mail information in JSON and than use some Javascript to render it to the user. But how they make the browser load in the while.
In gmail once it is loaded, obviously they ain't load all the data, from all your folder in background, so when you click on some of your folder and the data is not already loaded they make the browser 'load' like if it were loading a complete new page, while they retrieve the information from their server with some ajax call ( in Firefox you see the browser act like when you click on a normal link, loading icon, stop (x) button activated, and all).
Is it clear?
I came up with some 'ugly' code to achieve my goal that work quite nice in FireFox and IE (sadly it seems to not work in Chrome/WebKit and Opera).
I tell the browser to go to a url that it will not be able to reach before the ajax call end, with window.location=. The browser start to load and than when the ajax call sucess I call window.stop() (window.document.execCommand('Stop') for IE) than innerHTML the ajax data in the document
To me its look ugly and since it not work properly in Chrome/Webkit, this is apparently not the way to go.
There are many ways to utilize AJAX.
Gmail needs to load a lot of files/data before something meaningful can be displayed for the users.
E.g. showing the folder tree first doesn't make sense if it's not clickable or not ready for any interactive use.
Hence, what they do is show something lightweight like a loading graphic/progress bar while asynchronously (behind the scene), pull more data from the server until they can populate the page with a full interface for usage.
I don't know how to explain further. Maybe wiki can help: http://en.wikipedia.org/wiki/Ajax_%28programming%29
http://www.stevesouders.com/blog/2009/04/27/loading-scripts-without-blocking/
Use one of the methods shown as triggering a browser busy state in the table on the page above.
document.getElementById('iframe').src = "http://www.exemple.com/browser_load.html";
They are using iFrame. By changing the source of the iFrame.
Sitepoint has a book "Build Your Own AJAX Applications" and they show some content (all?) in this tutorial:
http://articles.sitepoint.com/article/build-your-own-ajax-web-apps
They will guide you with your AJAX coding.
Think this is your answer:
http://www.obviously.com/tech_tips/slow_load_technique
Looks like gmail and facebook method (browser is showing page as "loading" with loading icons etc. - it is just simulating, because there is a background ajax request) :)
$(function($){
$('a').attr('onclick','return false;').click(function(){
var title = $(this).attr('title');
var href = $(this).attr('href');
$('title').html(title);
$('#content').load(href+' #content', function(){
history.pushState(null, null, href);
}, function(responseText) {
var title = responseText.match(/<title>([^<]*)/)[1];
document.title = title;
});
});
});
window.onpopstate = function( e ) {
var returnLocation = history.location || document.location;
var returnTitle = history.propertyName || document.title;
$('title').html(returnLocation.title)
$('#content').load(returnLocation.href+ ' #content', function(){
history.pushState(null, null, href);
}, function(responseText) {
var title = responseText.match(/<title>([^<]*)/)[1];
document.title = title;
});
}

Communication between firefox extension and page javascript

I am developing a web-based javascript/html application with a sister firefox-extension.
The application's page-javascript performs a few XHR calls immediately after page-load, in order to bring in and display all the content that the page requires.
Is there a way, without polling the DOM, that my extension can know that the page's initialisation procedures are complete?
Interesting question indeed..
I've just found out through this post on MozillaZine's forum an easy way to accomplish this. The technique basically consists in defining a custom DOM element within the web page, filling it with some arbitrary attributes, and then using it as the target of a custom event. The event can than be captured and used to pass values from the webpage to the extension.
Web page (assumes jquery is available)
<script type="text/javascript">
$(document).ready(function(){
$.get("http://mywebsite.net/ajax.php",function(data){
//[...]process data
//define a custom element and append it to the document
var element = document.createElement("MyExtensionDataElement");
element.setAttribute("application_state", "ready");
document.documentElement.appendChild(element);
//create a custom event and dispatch it
// using the custom element as its target
var ev = document.createEvent("Events");
ev.initEvent("MyExtensionEvent", true, false);
element.dispatchEvent(ev);
});
});
</script>
Chrome code:
function myListener(e) {
alert("data:" + e.target.getAttribute("application_state"));
}
function on_specialpage_load(event) {
if (event.originalTarget instanceof HTMLDocument &&
event.originalTarget.location.href == "http://mywebsite.net/myspecialpage.html") {
var doc=event.originalTarget;
doc.addEventListener("MyExtensionEvent", myListener, false, true);
}
}
gBrowser.addEventListener("DOMContentLoaded",on_specialpage_load,false);
Notice that doc.addEventListener has a fourth parameter, indicating that it will accept events coming from untrusted code. However you can add this event listener selectively, so that only trusted pages from your site will be able to pass values to the extension.
You could hook into the XMLHttpRequest object from your extension and monitor the requests, similar to what this GreaseMonkey script does (description). Add a wrapper to onreadystatechange in the same way he's added a wrapper to open which notifies the extension when complete. Probably also want some code which makes sure you're only doing this when visiting your own page.
Firebug does similar stuff for its Net panel, the codebase for that is a bit more intimidating though :) I also had a look at the Firebug Lite watchXHR function, but that code is a bit too cunning for me, if you can work it out let me know.

Categories