FusedLocationProviderClient stop giving locationResult after several LocationRequest - broadcastreceiver

Please help if anybody has idea what happened with this case.
I have BroadcastReceiver which register to ForegroundService. This BroadcastReceiver will listen to Intent.ACTION_SCREEN_ON and called startLocationUpdates() if it receive any.
fun startLocationUpdates(context: Context, entity: LockEntityDB?) {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
mSettingsClient = LocationServices.getSettingsClient(context)
mLocationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
super.onLocationResult(locationResult)
val location = locationResult?.lastLocation
locationResult?.let {
saveLocation(context, it.lastLocation)
locationUpdatesCount(context)
}
//something will do with entityDb
}
}
mOneTimeLocationRequest = LocationRequest().apply {
interval = 5 * 1000
fastestInterval = 1000
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
numUpdates = 1
}
val builder = LocationSettingsRequest.Builder()
builder.addLocationRequest(mOneTimeLocationRequest!!)
mLocationSettingsRequest = builder.build()
mSettingsClient
?.checkLocationSettings(mLocationSettingsRequest)
?.addOnSuccessListener {
mFusedLocationClient?.requestLocationUpdates(mOneTimeLocationRequest, mLocationCallback, null)
}
?.addOnFailureListener { e ->
kTimberLog(context, "loc " + e.toString())
}
}
So the idea if user turn on the phone, it will send Intent.ACTION_SCREEN_ON and FusedLocationProviderClient will update actual user location.
The problem is, when user try to turn on the phone after 5-6x FusedLocationProviderClient never give any locationResult anymore.
The more weirdest part all this locationResult for the 6th times and so on will start reappearing when user open the MainActivity.
Additional info : I m testing this code on 3 emulator : Nexus 5 API 23, PIXEL 3 API 29, Galaxy Nexus API 29. It works fine for Nexus 5 API 23.
Anybody know what is the reason of this behavior? Thank you very much

After struggling for few days, I found the solution here :
https://developer.android.com/training/location/request-updates#continue-user-initiated-action
After adding this line into my manifest, everything looks working fine
<service
android:name="MyBackgroundService"
android:foregroundServiceType="location" ... >
...
I hope can help somebody who are stuck in same problem

Related

Katalon Studio deleting groovy code from script when switching to manual or recording

Did anybody see this as well, or am I doing something wrong?
I am working on a test case with Katalon Studio, in script mode. I have some Groovy script in it, (in particular a class definition, see start of code below). When I switch mode to work in manual or record mode, and then back to script mode, the groovy code (the class declaration in the example below) has disappeared...
Not very practical! Anything that should be done to avoid this?
Many thanks!
E.
Code example:
//Katalon Imports here
class Product {
String nozo
String price_string
Number qty = 1
Number price_ht = 0
Number price_ttc = 0
Product(String nozo, String price_string, Number qty = 1) {
this.nozo = nozo
this.price_string = price_string
def get_price = (this.price_string =~/(\d+)\s(\d+\.\d{2})/)
if(get_price) {
this.price_ttc = get_price[1] + get_price[2]
}
else this.price_ttc = 0
this.price_ht = this.price_ttc / 1.2
}
def get_price_order_line_ht() {
return this.price_ht * this.qty
}
}
// Intialisation of test data
Number qty_pdt1 = 2
'Open home page'
WebUI.openBrowser('http://localhost:8080/')
'Navigate to subrange'
WebUI.doubleClick(findTestObject('Object Repository/vb_desktop/home_page_desktop_fr/a_Lampadaire'))
// Etc...

Google form that turns on and off each day automatically

I love Google Forms I can play with them for hours. I have spent days trying to solve this one, searching for an answer. It is very much over my head. I have seen similar questions but none that seemed to have helped me get to an answer. We have a café where I work and I created a pre-order form on Google Forms. That was the easy part. The Café can only accept pre-orders up to 10:30am. I want the form to open at 7am and close at 10:30am everyday to stop people pre ordering when the café isn't able to deal with their order. I used the very helpful tutorial from http://labnol.org/?p=20707 to start me off I have added and messed it up and managed to get back to the below which is currently how it looks. It doesn't work and I can't get my head around it. At one point I managed to turn it off but I couldn't turn it back on!! I'm finding it very frustrating and any help in solving this would be amazing. To me it seems very simple as it just needs to turn on and off at a certain time every day. I don't know! Please help me someone?
FORM_OPEN_DATE = "7:00";
FORM_CLOSE_DATE = "10:30";
RESPONSE_COUNT = "";
/* Initialize the form, setup time based triggers */
function Initialize() {
deleteTriggers_();
if ((FORM_OPEN_DATE !== "7:00") &&
((new Date()).getTime("7:00") < parseDate_(FORM_OPEN_DATE).getTime ("7:00"))) {
closeForm("10:30");
ScriptApp.newTrigger("openForm")
.timeBased("7:00")
.at(parseDate_(FORM_OPEN_DATE))
.create(); }
if (FORM_CLOSE_DATE !== "10:30") {
ScriptApp.newTrigger("closeForm")
.timeBased("10:30")
.at(parseDate_(FORM_CLOSE_DATE))
.create(); }
if (RESPONSE_COUNT !== "") {
ScriptApp.newTrigger("checkLimit")
.forForm(FormApp.getActiveForm())
.onFormSubmit()
.create(); } }
/* Delete all existing Script Triggers */
function deleteTriggers_() {
var triggers = ScriptApp.getProjectTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
}
/* Allow Google Form to Accept Responses */
function openForm() {
var form = FormApp.getActiveForm();
form.setAcceptingResponses(true);
informUser_("Your Google Form is now accepting responses");
}
/* Close the Google Form, Stop Accepting Reponses */
function closeForm() {
var form = FormApp.getActiveForm();
form.setAcceptingResponses(false);
deleteTriggers_();
informUser_("Your Google Form is no longer accepting responses");
}
/* If Total # of Form Responses >= Limit, Close Form */
function checkLimit() {
if (FormApp.getActiveForm().getResponses().length >= RESPONSE_COUNT ) {
closeForm();
}
}
/* Parse the Date for creating Time-Based Triggers */
function parseDate_(d) {
return new Date(d.substr(0,4), d.substr(5,2)-1,
d.substr(8,2), d.substr(11,2), d.substr(14,2));
}
I don't think you can use .timebased('7:00'); And it is good to check that you don't have a trigger before you try creating a new one so I like to do this. You can only specify that you want a trigger at a certain hour like say 7. The trigger will be randomly selected somewhere between 7 and 8. So you really can't pick 10:30 either. It has to be either 10 or 11. If you want more precision you may have to trigger your daily triggers early and then count some 5 minute triggers to get you closer to the mark. You'll have to wait to see where the daily triggers are placed in the hour first. Once they're set they don't change.
I've actually played around with the daily timers in a log by creating new ones until I get one that close enough to my desired time and then I turn the others off and keep that one. You have to be patient. As long as you id the trigger by the function name in the log you can change the function and keep the timer going.
Oh and I generally created the log file with drive notepad and then open it up whenever I want to view the log.
function formsOnOff()
{
if(!isTrigger('openForm'))
{
ScriptApp.newTrigger('openForm').timeBased().atHour(7).create()
}
if(!isTrigger('closeForm'))
{
ScriptApp.newTrigger('closeForm').timeBased().atHour(11)
}
}
function isTrigger(funcName)
{
var r=false;
if(funcName)
{
var allTriggers=ScriptApp.getProjectTriggers();
var allHandlers=[];
for(var i=0;i<allTriggers.length;i++)
{
allHandlers.push(allTriggers[i].getHandlerFunction());
}
if(allHandlers.indexOf(funcName)>-1)
{
r=true;
}
}
return r;
}
I sometimes run a log entry on my timers so that I can figure out exactly when they're happening.
function logEntry(entry,file)
{
var file = (typeof(file) != 'undefined')?file:'eventlog.txt';
var entry = (typeof(entry) != 'undefined')?entry:'No entry string provided.';
if(entry)
{
var ts = Utilities.formatDate(new Date(), "GMT-6", "yyyy-MM-dd' 'hh:mm:ss a");
var s = ts + ' - ' + entry + '\n';
myUtilities.saveFile(s, file, true);//this is part of a library that I created. But any save file function will do as long as your appending.
}
}
This is my utilities save file function. You have to provide defaultfilename and datafolderid.
function saveFile(datstr,filename,append)
{
var append = (typeof(append) !== 'undefined')? append : false;
var filename = (typeof(filename) !== 'undefined')? filename : DefaultFileName;
var datstr = (typeof(datstr) !== 'undefined')? datstr : '';
var folderID = (typeof(folderID) !== 'undefined')? folderID : DataFolderID;
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var targetFound = false;
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
if(append)
{
datstr = fi.getBlob().getDataAsString() + datstr;
}
targetFound = true;
fi.setContent(datstr);
}
}
if(!targetFound)
{
var create = fldr.createFile(filename, datstr);
if(create)
{
targetFound = true;
}
}
return targetFound;
}

close connection elasticsearch, is it necessary?

im create a API using scala and library Spray.IO. my API, search into elasticsearch.
my questions is also related with question.
var klt:TransportClient = EsClient_08012017.klien1
var arg = Array(JsObject(Map("id"->JsString("-1"), "item" -> JsString("-1"), "score"-> JsString("-1"))))
if(cariIndex(namaIndexCari)==true && cariIndex(namaIndexCari+"_2")==true)
{
if(hitungJumlahIndex(namaIndexCari) > hitungJumlahIndex(namaIndexCari+"_2"))
{
val ar = ambilRekomendasi(idPenggunaCari, namaTipeCari, namaIndexCari, jumlah, false)
val atd = acakTanpaDuplikat(ar)
arg = parsingJsObject(atd)
}
else
{
val ar = ambilRekomendasi(idPenggunaCari, namaTipeCari, namaIndexCari+"_2", jumlah, false)
val atd = acakTanpaDuplikat(ar)
arg = parsingJsObject(atd)
}
}
else
{
val ar = ambilRekomendasi(idPenggunaCari, namaTipeCari, namaIndexCari, jumlah, false)
val atd = acakTanpaDuplikat(ar)
arg = parsingJsObject(atd)
}
klt.close()
arg
for 1st time, hit API its fine. but, the 2nd hit API im get some error
None of the configured nodes are available: [{#transport#-1}{127.0.0.1}{127.0.0.1:9300}]
what i want to achieve are, each of hit API its also like close connection to ES and open connection. but, the reference link said "it's okay without close connections". thanks for help, or link, or reference!
Never close it unless you are closing your application

Basecamp API - retrieving hours

I've been asked to look at the creation of a report that will pull time entry data for a list of projects. Give the project name/id, retrieve a sum of all time spent on it, and a sum of the hours from the past week.
But I can't see where in the new API anything that will give me the time entries, at least, the retrieval process is not in the Basecamp documentation.
I've been looking at this page, which describes the API:
https://github.com/basecamp/bcx-api
Turns out that you can get it from their old API:
https://mystuff.basecamphq.com/projects/#project_id#/time_entries.xml
This will give you the time entries as XML, which is a pain. It also paginates the results. In the header that you get back are two fields, that tell you how many records are there total, and how many pages:
var pageCount = headers["X-Pages"];
var recCount = headers["X-Records"];
You can process the records that come back as follows:
function processRecords(response)
{
var respObj =
{
totalHours: 0,
thisWeekHours: 0
}
var doc = null;
if (response.getContentText)
{
doc = Xml.parse(response.getContentText(), true);
}
else if (response.getElements)
{
doc = response;
}
else
{
var name = typeof response;
if (response.constructor) name = response.constructor.name;
throw new Exception("Incompatible type: " + name);
}
var root = doc.getElement();
var records = root.getElements("time-entry");
if (records.length > 0)
{
for (i = 0;i < records.length; i++)
{
var hours = Number(records[i].hours.getText());
var recordDate = records[i].date.getText();
if (recordDate >= previousSunday && recordDate <= previousSaturday)
{
respObj.thisWeekHours = respObj.thisWeekHours + hours;
}
respObj.totalHours = respObj.totalHours + hours;
}
}
return respObj;
}
What we have seen so far is there is no easy way to get actual time spent on any project. You can do something simple like time from the day project is created till its closed/deleted.
The bet way we see doing this is looking at each todo-list and then to-dos under it. Find out the cumulative time spent on each to-do under each todo-list for that project and that will be the actual (nearest possible accurate time) time spent on the project.
You can use the API to get this todo level details and that will do the trick.
If someone has better option let us know as well :) We are doing the above as of today.

Blackberry 10: Unable to record voice

I want to record call voice during the call time on BlackBerry 10 OS. For this I used Telephony Phone and Call State Listener. I start as found Call State "Connected" and stop when call "Disconnected".
But at start time recorder records only 160Byte of data each time.
and at stop time recorder shows "Already unprepared".
For this I use recorder.prepare() but it still didn't work for me. Please suggest and help me. Here is the code
void ApplicationHeadless::onCallUpdated(const Call &call)
{
QMetaObject MetaCallTypeObject = CallType::staticMetaObject;
QMetaEnum CallTypeEnum = MetaCallTypeObject.enumerator(
MetaCallTypeObject.indexOfEnumerator("Type"));
QMetaObject MetaCallStateObject = CallState::staticMetaObject;
QMetaEnum CallStateEnum = MetaCallStateObject.enumerator(
MetaCallStateObject.indexOfEnumerator("Type"));
CallType::Type CurrentCallType = call.callType();
CallState::Type CurrentCallState = call.callState();
QString conn = "Connected";
QString dcon = "Disconnected";
QDateTime now = QDateTime::currentDateTime();
bb::multimedia::AudioRecorder recorder;
if (conn.compare(CallStateEnum.valueToKey(CurrentCallState)) == 0) {
recorder.setOutputUrl(QUrl("/tmp/" + now.toString() + ".m4a"));
recorder.setOutputUrl(QUrl("file://" + QDir::currentPath() + "/data/recording121.m4a"));
recorder.record();
}
if (dcon.compare(CallStateEnum.valueToKey(CurrentCallState)) == 0) {
recorder.reset();
}
}
Thanks in advance..