setTimer() & timeInterval() in sencha don't work in Android & iPhone device - android

I am working on a sencha touch application where I need to send request to server after every 1 min. I am using setInterval() & setTimeOut() both works in chrome on desktop but when it comes to iPhone or Android it don't work (they don't get called)
Has anyone used these functions before (successfully) or any other functions to use.
Code used
setInterval(function(){
//server calling method
},10000);
setTimeout(function name,10000);
Function name is function which has code to send request to server.
Thank YOu

Why don't you Sencha's DelayedTask class for the purpose? It will be something like this:
//create the delayed task instance with our callback
var task = Ext.create('Ext.util.DelayedTask', function() {
//server calling method
// The task will be called after each 10000 ms
task.delay(10000);
}, this);
//The function will start after 0 milliseconds - so we want to start instantly at first
task.delay(0);
//to stop the task, just call the cancel method
//task.cancel();
And, I worked with this code with Phonegap and it worked fine.

In iPhone generally NSTimer is used.
NSTimer *timer_main = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:#selector(yourfunction) userInfo:nil repeats:YES];
This will work in iPhone..

Related

Cordova - How to change page from android code?

My question looks stupid at first glance and all my searches pointed out window.location and other JS stuff or the externalWebPage plugin. That's not what I'm looking for.
From the JAVA code, when I catch one specific exception during execution of a custom plugin, I want to force the page to move to "logout.html". I don't want to execute callback.error() or to deal with the error inside code in my webpage in any ways. I only want my transaction to be cancel and a web resource to be loaded in the current web UI.
Is there any way to do that?
Thanks in advance.
The CordovaWebView offers a showWebPage function to load any url from the native code.
From the plugin you should be able to do
this.webView.showWebPage("logout.html", false, true, null);
Also offers loadUrl
this.webView.loadUrl("file:///android_asset/www/logout.html");
And you can also use loadUrl to execute javascript so you can run the window.location from there without a callback.
this.webView.loadUrl("javascript:window.location.href='logout.html'");
You will either need to add it to your main.js interface so that you can callup page changed () and handle it in your angular code.
This can be a simple onPageNeedsChanged Handler call where you retain the context on page change context and just call it whenever you need.
Or you can call the onError callback from the caller, if it is a consistent error callback context to move you there, but sounds like you don't want to do this route.
So the easiest answer then is to just launch your own Activity with a preloaded web url and a web view. You already have access to the activity, so just make your own native activity with a full web view in it, hard coded url and then launch your activity on error.
i.e. I do it for sending an email, but it could be your own activity
cordova.getActivity().startActivity(Intent.createChooser(emailIntent, "Send mail..."));
You may even be able to get a reference to the Cordova web view, but not positive on that, but I assume you could through the tree of objects.
Does that work for you needs?
If not can you elaborate on your hesitation to handle in the onerror callback. It's fairly straight forward. Maybe I can help you there as an alternative? Retaining the callingContext and just using callingContext.error(withkey or instructions or object) is not too bad.
A35ble.writeValueToPodCharacteristic(this.device.macAddress, true, this.bytesToSend,
function (response) {
console.log("Success: " + response);
callbackContext.device.notificationReceivedFromPod(callbackContext.device.arrayBufferToString(response));
},
function (response) {
console.log("ERROR: " + response);
alert("Error Sending NSM Message: " + response);
}
);
For example I made a cordova plugin called A35ble that manages my bluetooth stuff and in this response I just show alert.

Background service on react-native android

Is there any way to create a background service with react-native on android?
I would like some sort of timer that wakes up every hour or so, and launches a simple javascript task.
Yes, It can be done.
React native operates on top of the native (java/Objc) to JS bridge with a concept of "native" and JS modules (modules can have methods that you may call from the "other" side of the bridge). All the UI stuff is built on top of the bridge (the main "native" module that handles generating views is called "UIManager"). It is possible to use bridge directly the only restriction is that the communication has to be asynchronous.
You can call the javascript function from the JAVA code. Check this link for the documentation.
Absolutely. In fact it's quite easy now to achieve this entirely in JS (no need to write native code) cross platform with react native queue and react native background task.
There are some limitations. The background task will only be fired roughly every 15 minutes at smallest intervals (and the timing isn't guaranteed to be perfect if it even fires at all - the iOS/Android scheduler is sort of a black box that looks at battery life, current cpu load, etc, when determining when to fire a scheduled task). Also the task is limited to 30 seconds of execution.
I've written a tutorial on how to set all this up here.
Let me know if you have any difficulty getting it up and running.
Release v0.36 support headless-js, only Android, for now.
https://facebook.github.io/react-native/docs/headless-js-android.html
It's Working in my case user the react-native-background-job library for running a background service. It's working after the kill the app.
https://github.com/vikeri/react-native-background-job
import BackgroundJob from "react-native-background-job";
const regularJobKey = "regularJobKey";
BackgroundJob.register({
jobKey: regularJobKey,
job: () => {
console.log('Background Service Call!');
}
});
<TouchableHighlight
onPress={() => {
BackgroundJob.schedule({
jobKey: regularJobKey,
period: 2000
});
}}
>
<Text>Schedule regular job</Text>
</TouchableHighlight>
Example Here : https://github.com/vikeri/react-native-background-job/blob/master/example/index.android.js
Try to use react-native-background-actions, it's very great service even for iOS and they are providing the ProgressBar feature as well.
yarn add react-native-background-actions
or npm:
npm install --save react-native-background-actions
A short code snippet of how to use it.
import BackgroundService from 'react-native-background-actions';
// You can do anything in your task such as network requests, timers and so on,
// as long as it doesn't touch UI. Once your task completes (i.e. the promise is resolved),
// React Native will go into "paused" mode (unless there are other tasks running,
// or there is a foreground app).
const veryIntensiveTask = async (taskDataArguments) => {
// Example of an infinite loop task
const { delay } = taskDataArguments;
await new Promise((resolve) => {
for (let i = 0; BackgroundService.isRunning(); i++) {
console.log(i);
await sleep(delay);
}
});
};
const options = {
taskName: 'Example',
taskTitle: 'ExampleTask title',
taskDesc: 'ExampleTask description',
taskIcon: {
name: 'ic_launcher',
type: 'mipmap',
},
color: '#ff00ff',
linkingURI: 'yourSchemeHere://chat/jane', // See Deep Linking for more info
parameters: {
delay: 1000,
},
};
await BackgroundService.start(veryIntensiveTask, options);
await BackgroundService.updateNotification({taskDesc: 'New ExampleTask description'}); // Only Android, iOS will ignore this call
// iOS will also run everything here in the background until .stop() is called
await BackgroundService.stop();

Corona Sdk - Removing one instance of objects with the same name

I'm making a space game using Corona Sdk and one of the functions in my code is used to fire laser beams. These beams are supposed to disappear when they finish their transition, but I have one problem: when I fire more than one at the same time (using a button widget(one per click)) only the last one fired disappears, right after the first one finishes its transition.
This is my code right now:
local function removeLaser(event)
--[[
this doesn't work -> display.remove(laser)
this returns an error (main.lua:34: attempt to call method 'removeSelf' (a
nil value)) -> laser.removeSelf()
--]]
end
local function fire(event)
laser=display.newImageRect("laser.png",75,25)
laser.x=spaceship.contentWidth+spaceship.x/2+3
laser.y=spaceship.y
transition.to(laser,{time=1000,x=display.contentWidth, onComplete=removeLaser})
end
local function createButton()
buttonFire=widget.newButton
{
defaultFile="buttonUNP.png",
overFile="buttonP.png",
width=130,
height=130,
emboss=true,
onPress=fire,
id="buttonFire"
}
buttonFire.x=display.contentWidth-buttonFire.contentWidth/2-10
buttonFire.y=display.contentHeight-buttonFire.contentHeight/2-10
end
What should I do about the function removeLaser(event)?
Just put the removeLaser into fire function:
local function fire(event)
local laser=display.newImageRect("laser.png",75,25) -- always declare objects as locals
laser.x=spaceship.contentWidth+spaceship.x/2+3
laser.y=spaceship.y
local function removeLaser(target) -- `onComplete` sends object as a parameter
target:removeSelf()
target = nil
end
transition.to(laser,{time=1000,x=display.contentWidth, onComplete = removeLaser})
end

How to create async call with jquery with android using phonegap?

I have seen background service in phonegap and integrated successfully but, I need to make an ajax call to get the data from server.This call need to be happen in background process without disturbing the UI. I am unable to do this using this plugin.
And my code look like,
$.ajax({
type: "POST",
url: "http://example.com/xxx",
dataType: "xml",
async:true,
success: function (data) {
var serializer = new XMLSerializer();
var xmlString = serializer.serializeToString(data);
var finalxml= xmlString.replace(/</g, '<').replace(/>/g, '>').replace('<br/>','\n');
window.localStorage.setItem("xml_Questions",finalxml);
}
});
This ajax call has to be done with async(background) call while user doing something..
But user is not able to do anything until get the response.So I have followed Background service plugin for phonegap, but I am not able to implement this method with that plugin.
Can we do this?
Can anybody help me?
Thank you in adv...
Your $.ajax code looks right to me, so it shouldn't block the app behavior.
I don't completely understand your question... user shoudn't be allowed to do anything until the localstorage.setitem is set? If this is right, you could use jquery to enable some kind of "NEXT" button after the setItem instruction, so the user won't be able to move on until the async call is done.

timeout parameter does not make any effect on Titanium.Network.createHTTPClient

I want user to wait for specified time(4seconds) to get connected to server. If it cannot connect within the specified time period, application should get closed.
Here is what I have coded:
var downloadDataReq = Titanium.Network.createHTTPClient({timeout :4000});
downloadDataReq.onload = function() { //some code }
downloadDataReq.onerror = function(event) { //some code }
var urlToDownloadData = 'http://www.google.com';
downloadDataReq.open("POST", urlToDownloadData);
downloadDataReq.send();
The Problem is that app waits for fix time (timeout parameter does not effect at all).
P.S.: making an app for android using Titanium.
Try to use method like this:
downloadDataReq.setTimeout(4000);
For me, timeout on HTTP requests aren't working as it should. I had very weird issues, such as:
If I put 1000ms timeout, it'll be called on 2 or 3 seconds.
If I put 2000ms timeout or above, it'll never be called.
I'm using Android ICS and JB, and on both I get the issues above. Seems that timeout parameter is buggy.
As a workaround, I'm doing checks inside onload (example: if I'm downloading a file, I compare the checksum of local file, with the checksum of the same file on the server), and I'm simulating timeouts with JavaScript's setTimeout. It's working to an extend.
The code below demonstrate how to simulate a request timeout, with JS's setTimeout command:
var downloadDataReq = Titanium.Network.createHTTPClient();
downloadDataReq.onload = function() {
clearTimeout(timeout);
alert('loaded');
}
downloadDataReq.onerror = function(e) {
clearTimeout(timeout);
alert('error: ' + e.error);
}
var urlToDownloadData = 'http://10.1.1.183/maquina_local/arquivos/FirefoxPortable_12.0_PortugueseBR.paf.exe';
downloadDataReq.open("GET", urlToDownloadData);
var timeout = setTimeout(function(){
downloadDataReq.onload = function(){
downloadDataReq.onerror({'error': 'timeout'});
};
downloadDataReq.abort();
}, 4000);
downloadDataReq.send();
On timeout, I'm changing onload event to onerror one, because if you try aborting a running request, it'll trigger 'onload' event, not 'onerror'. If you don't do it, this issue can give you corrupted files (ex: a 20mb file that, when request is aborted, file will be incomplete, with a size smaller than 20mb).
I'm still testing this solution, but at least for now, it solved a few bugs for me.
Try this.
Ti.App.timeOut = 99000; //declare in app.js
then use anyWhere in your project.But make Sure every time when you create a httpClient.
dont recreate or redefine in Code or through out the page.
this works fine for me.
//HAVE A LOOK OVER THE USE OF THIS
var xhr = Titanium.Network.createHTTPClient({timeout:Ti.App.timeOut});

Categories

Resources