How to code an app in Huawei GT 2 Pro wear to always keep on the screen active? - wear-os

I investigated and Although I read documentations of Huawei Wear Engine, I couldn't find any things. I knows this I should change power or keep-on setting but I did not find anthing. Even I know implementing a service to will affect system configuration but there is no any document about it. Could you help me about implement always keep on screen huawei GT2 Pro.

Keeping screen on could be achieved via brightness.setKeepScreenOn(OBJECT)
https://developer.harmonyos.com/en/docs/documentation/doc-references/lite-wearable-system-screen-brightness-0000001122145264
Sample code is as follows:
brightness.setKeepScreenOn({
keepScreenOn: true,
success: function () {
console.log('handling set keep screen on success.')
},
fail: function (data, code) {
console.log('handling set keep screen on fail, code:' + code + ', data: ' + data);
},
});

As#Zinna mentioned, You can call brightness.setKeepScreenOn(OBJECT) to always keep on the screen active.
Examples are as follows:
brightness.setKeepScreenOn({
keepScreenOn: true,
success: function () {
console.log('handling set keep screen on success.')
},
fail: function (data, code) {
console.log('handling set keep screen on fail, code:' + code + ', data: ' + data);
},
});
You are advised to invoke it in the onShow() phase to always keep the screen on.
For details, kindly refer to this Docs.

Related

Memory leaks in Appcelerator Android HTTP?

I am running into what looks like a memory leak on Android using Appcelerator. I am making an HTTP GET call repeatedly until all data is loaded. This call happens about 50 times, for a total of roughly 40 MB of JSON. I am seeing the memory usage spike dramatically if this is executed. If I execute these GETs the heap size (as reported by Android Device Monitor, the preferred method to check memory according to the official Appcelerator docs) gets up to ~240 MB and stays there for as long as the app runs. If I do not execute these GETs, it only uses about 50 MB. I don't think this is a false heap reading either, because if I execute the GETs again (from page 1) I run out of memory.
I have looked through the code and cannot find any obvious leaks, such as storing all results in a global variable or something. Are the HTTP responses being cached somewhere?
Here is my code, for reference. syncThings(1, 20) (sanitized name :) ) gets called during startup. It in turn calls a helper function syncDocuments(). Here are the two functions. Don't worry about launchMainWindow() unless you think it could be relevant, but assume it does no cleanup.
function syncThings(page, itemsPerPage) {
var url = "the_url";
console.log("Getting page " + page);
syncDocuments(url,
function(response) {
if (response.totalDocumentsInQuery == itemsPerPage) {
// More pages to get
setTimeout(function() {
syncThings(page + 1, itemsPerPage);
}, 1);
} else {
// This was the last page
launchMainWindow();
}
},
function(e) {
Ti.API.error('Default error callback called for syncThings;', e);
dispatcher.trigger('app:update:stop');
});
}
function syncDocuments(url, successCallback, errorCallback) {
new HTTPRequest({
url: url,
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
timeout: 30000,
success: function (response) {
Ti.API.info('Success callback called for ' + url);
successCallback(response);
},
error: function (error) {
errorCallback(error);
}
}).send();
}
Any ideas? Am I doing something wrong here?
Edit: I am using Titanium SDK 6.0.1.GA. This happens on all Android versions.
Try using the file-property of the HTTPClient: http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Network.HTTPClient-property-file
otherwise the file will be loaded into memory.
There will be a memory leak fix in 6.1.0: https://github.com/appcelerator/titanium_mobile/pull/8818 that might fix something too.

Cordova ajax call fail on real device and works in the emulator

I have a Cordova application with some Ajax calls. Everything works fine but a call where I upload some picture taken through the camera (via base64 encoding).
The problem is that on the Genymotion emulator (Nexus 5) the call works fine, on the other hand on a real Nexus 5 the call fails with error 500 and I really can't figure out why.
Here's the code of the Ajax call:
$('.add-coupon').on('click', function() {
var dt = {
"api_token": localStorage['api_token'],
"title": localStorage['c_title'],
"description": localStorage['c_description'],
"start_price": localStorage['c_price'],
"third_level_category": localStorage['c_third'],
"main_attachments": localStorage['image_0'],
"post_attachments_1": localStorage['image_1'],
"post_attachments_2": localStorage['image_2'],
"post_attachments_3": localStorage['image_3']
};
$.ajax({
url: 'http://www.XXXXXXXXXXXXXXX.com:8000/api/v1/upload',
type: 'POST',
data: JSON.stringify(dt),
cache: true,
async: true,
success: function(data) {
alert('ok');
window.location = 'index-shop.html';
},
error: function(event, jqXHR, ajaxSettings, thrownError) {
alert('[event:' + event + '], [jqXHR:' + jqXHR.responseText + '], [ajaxSettings:' + ajaxSettings + '], [thrownError:' + thrownError + '])');
}
});
});
As you can see nothing special happens during the request, what am I missing?
If I make the call with the same data even with postman (the chrome plugin) everything works fine!
EDIT: If I do NOT take any picture (so main_attachmends and all the post_attachments are empty) the call works. It's only when i take the images that do not work.
I solved the problem by adding this code: Getting error "exceeded available parameter key space"?
Apparently the emulator images were really small and everything worked fine, but with normal images i get the following error:
App 15424 stderr: [ 2015-05-04 13:28:38.2529 15508/0x00000001a22140(Worker 1) utils.rb:84 ]: *** Exception RangeError in Rack application object (exceeded available parameter key space) (process 15508, thread 0x00000001a22140(Worker 1))

How to run a consuming process before sending data with ajax and jquery on the background with the spinner running?

I am trying to send data to server using ajax, but the problem is that I have a consuming process before sending the data.
The process takes about 5 seconds and the spinner has to run in the process.
So in my code the spinner doesnt show until the ajax call starts (probably because the process is blocking everything)
If I move the call "consumingprocess" into "beforesend", then it doesnt work and I am not sure why.
So the question is how to show the spinner, while everything is beeing called (the consumingprocess and the ajax call)
Thanks
This is my code:
$("#btnAccept").bind("click", function(event, ui) {
//start spinner, works fine but only shows after consumingprocess has finished
$.mobile.loading( 'show' );
console.log("btnAccept");
var data = consmuingprocess();
console.log(data);
// data is fine
$.ajax({
type : "POST",
url : url,
dataType : "xml",
contentType : "text/xml;charset=UTF-8",
data : data,
requestHeaders : {
Origin : '*'
},
crossDomain : true,
beforeSend : function(xhr) {
xhr.setRequestHeader("Authorization", "Basic xxxxxxxxxxxxxxx");
console.log("beforeSend");
},
error : errorAJAX,
success : parseXml
});
});
});
What you can do is
call your loading window
delay so the loading window has a chance to display
run the rest of your code.
You would do this using an interval:
$("#btnAccept").bind("click", function(event, ui) {
var intervalId;
function delayedStuff = function() {
// make sure we only run this once
window.clearInterval(intervalId);
var data = consmuingprocess();
$.ajax({
// set up your ajax request and handlers
});
};
$.mobile.loading( 'show' );
// wait 1/2 second, then run delayedStuff
intervalId = window.setInterval(delayedStuff, 500);
});
But this technique comes with an important caveat: while your very expensive consumingProcess function is running, all animations and javascript still comes to a halt. On Chrome, even animated gifs stop running. All we've done here is just given your page changes a chance to display.
There are a couple of possible solutions available:
Take a closer look at your consumingprocess() function and see if it can be optimized. There is probably a faster way to do whatever it is you're doing that's taking so long.
Use WebWorkers. The downside is compatibility: IE and most older browsers don't support it. I haven't done multi-threaded programming with JavaScript at all, so I don't know how effective this is.

ajax settimeout to refresh div

I am displaying a graph using jQplot to monitor data.
To refresh the div holding the graph, I invoke an ajax call every 5 seconds (see JavaScript excerpt below).
On the server, a PHP script retrieves the data from a database.
On success, the ajax call is reinvoked after 5 seconds with a JavaScript setTimeout(ajax,5000).
On error, the ajax call is retried 10 times with setTimeout(ajax,5000) before displaying an error message.
Monitoring XHR learns that the browser crashes after approximately 200 requests.
As a temporary remedy, a location.reload() is issued after 50 iterations to prevent the browser from crashing.
This works, but is not an ideal situation.
Any better solution to this problem is very much appreciated.
Thanks and regards, JZB
function ajax() {
$.ajax({
cache: false,
url: 'monitor.php',
data : { x: id },
method: 'GET',
dataType: 'json',
success: onDataReceived,
error: onDataError
});
function onDataReceived(series) {
$('#chartdiv_bar').html('');
$.jqplot('chartdiv_bar', [series['initHits']], CreateOptions(series,'Inits'));
errorcount = 0;
setTimeout(ajax, 5000);
}
function onDataError(jqXHR, textStatus, errorThrown) {
errorcount++;
if (errorcount == 10) {
alert("No server response:\n\n" + textStatus + "\n" + errorThrown);
} else {
setTimeout(ajax, 5000);
}
}
}
Since you're re-calling ajax() after a good or fail ajax call, you're starting multiple timers. This is why your browser is crashing.
you may want to try to clear the current timer and then start the next timer
var t; //global
In each of your call back functions:
if(t)
clearTimeout(t);
t = setTimeout(ajax, 5000);
more info on timer here: w3 school
I removed the jqplot call as suggested and the problem disappeared.
Apparently jqplot is the culprit and I found numerous entries referring to jqPlot memory leaks.
I use jQuery 1.6.4 and installed jqPlot Charts version 1.0.0b2_r792 which supposedly addresses memory leak issues.
Furthermore, I replaced
$('#chartdiv_bar').html('');
with
$('#chartdiv_bar').empty();
Thank you for your support.

AJax Testing - Add a delay

I'm trying to run some tests on some Ajax code we have written, now obviously when tested locally it runs very fast and is great. I need to enforce a delay of 3 seconds so that I can see that the loader is being displayed and the user experiance is good enough.
I have tried the following but recieve the error "Useless settimeout" any other suggestions to achieve this? Any browser plugins?
$('#formAddPost').submit(function() {
//Load the values and check them
var title = $(this).find('#Title');
var description = $(this).find('#Description');
var catId = $(this).find('#Categories');
if (ValidateField(title) == false || ValidateField(description) == false) {
$('.error-message').show();
return false;
}
$('.error-message').hide();
//Show the loading icon
$('.add-post').hide();
$('.add-post-loader').show();
//Temp for testing - allows the showing to the loader icon
setTimeout(MakeAJAXCall(title.val(), catId.val(), description.val()), 1500);
return false;
});
function MakeAJAXCall(title, catId, description) {
$.ajax({
url: "/Message/CreatePost/",
cache: false,
type: "POST",
data: ("title=" + title + "&description=" + description + "&categories=" + catId + "&ajax=1?"),
dataType: "html",
success: function(msg) {
$('#TableMessageList').replaceWith(msg);
$('.add-post-loader').hide();
$('.add-post').show();
}
});
}
As you're testing your page for a delay in the server response, can you put a delay in the server side code instead of client side?
You might be able to do that using fiddler.
The examples scripts include some samples that pause the response.
Would this tool from jsFiddle.net be helpful?
Echo Javascript file and XHR requests
http://doc.jsfiddle.net/use/echo.html

Resources