In my app I want to submit the device's location when in background to a web app. Currently I am using BubbleWrap for the POST request.
Note, that I may be able to use anything other than BubbleWrap if needed.
The current behavior is the following:
I start up the app
I bring it to background
[Waiting for request on web app, watching the logs, nothing happens]
I bring the app to the foreground
The app sends the device's location
What should happen:
I start up the app
I bring it to background
The app sends the device's location
The app keeps listening for significant location changes and sends its location on significant change
This is the code:
class AppDelegate
def application(application, didFinishLaunchingWithOptions:launchOptions)
[ommitted]
UIApplication.sharedApplication.registerForRemoteNotificationTypes(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)
true
end
def applicationDidEnterBackground(application)
#locationManager.startMonitoringSignificantLocationChanges
end
def applicationDidEnterForeground
#locationManager.stopMonitoringSignificantLocationChanges
end
def application(app, didRegisterForRemoteNotificationsWithDeviceToken:deviceToken)
#device_token = deviceToken.description.gsub(" ", "").gsub("<", "").gsub(">", "")
# Log the push notification to the console
puts #device_token
end
def application(app, didFailToRegisterForRemoteNotificationsWithError:error)
show_alert "Error when registering for device token", "Error, #{error}"
end
def device_token
#device_token
end
def location_manager
if #locationManager.nil?
#locationManager = CLLocationManager.alloc.init
#locationManager.setDesiredAccuracy(KCLLocationAccuracyBest)
#locationManager.delegate = self
end
#locationManager
end
# iOS >= 4
def locationManager(manager, didUpdateToLocation:current_location, fromLocation:last_location)
puts "Location #{current_location} [iOS 5]"
end
# iOS >= 6
def locationManager(manager, didUpdateLocations:locations)
data = {latitude: locations.last.coordinate.latitude,
longitude: locations.last.coordinate.longitude,
device_token: #device_token }
BW::HTTP.post("http://192.168.1.100:4567/", {payload: data}) do |response|
if response.ok?
#json = BW::JSON.parse(response.body.to_str)
#p json['id']
else
App.alert(response.error_message)
end
end
end
def locationManager(manager, didFailWithError:error)
puts "failed"
end
def show_alert(title, message)
alert = UIAlertView.new
alert.title = title
alert.message = message
alert.show
end
end
Additional info:
I have declared the following in my Rakefile app.info_plist['UIBackgroundModes'] = ['location'].
Any hints or tips on why this is may not be working?
My guess is that because the BW::HTTP.post(...) is asynchronous, your app quits before the block is called.
Related
private fun shareOperation(file: File) {
val uri = Uri.fromFile(file)
val storage = FirebaseStorage.getInstance()
val pdfRef = storage.reference.child("pdf/${uri.lastPathSegment}")
pdfRef.putFile(uri).addOnFailureListener { e ->
Log.e(TAG, "Couldn't share " + e.message)
}.addOnCompleteListener{
it.addOnCompleteListener {
pdfRef.downloadUrl.addOnSuccessListener { e ->
run {
link = e.toString()
Log.i(TAG,link!!) // Here i get the link to file in firebase storage
}
}
}
}
// Here link gets null
}
i was expecting somehow i can get the link to the file and can use it for sharing intent
You are performing an asynchronous call to upload the file, that is correct since any UI blocking action must be performed in background. The variable link will be null until the run code is executed in the background thread.
You need to code inside the run block whatever you want to happen when the link is available.
BTW looks weird what you are doing with the nested addOnCompleteListener, there should be an easier way to code that. You should probably spend time learning how to code with listeners and background threads.
Can we use the GPS antenna in way that we can control the polling speed? like every 10 seconds and every 1 second. Assume the power usage is manageable. I just want to get accurate location asap.
We can use Android default LocationManager class which is not google API.
And also Huawei Mapkit LocationManager
val locationManager = HuaweiLocationManager(this) locationManager.registerLocationUpdates(onSuccess = { viewModel.updateCurrentLocation(it) })
and subscribe to update in different speed.
fun registerLocationUpdates(
interval: Long = 10000,
onSuccess: ((location: Location?) -> Unit)? = null,
onFail: ((locationAvailability: LocationAvailability?) -> Unit)? = null
) {
val mLocationRequest = LocationRequest()
// Set the location update interval (in milliseconds).
mLocationRequest.interval = interval
// Set the weight.
mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
// Create location callback
if (mLocationCallback == null)
mLocationCallback = createLocationCallback(onSuccess, onFail)
// Request location update
mFusedLocationProviderClient.requestLocationUpdates(
mLocationRequest,
mLocationCallback,
Looper.getMainLooper()
)
.addOnSuccessListener {
// Requesting location updates is started successfully.
LogUtils.d("LocationKit -> Start Location Updates Successfully")
}
.addOnFailureListener { exception ->
// Failed to start location updates.
LogUtils.d("LocationKit -> Start Location Updates Failed with exception: ${exception.localizedMessage}")
}
}
I am trying to retrieve OTP in Huawei device. but it is not working.
I have created the app in Huawei developer console with all the requirements.
Below is the code i am using to retrieve the sms.
private fun initSmsManager() {
val task = ReadSmsManager.start(this#MainActivity)
task.addOnCompleteListener {
if (task.isSuccessful) {
// The service is enabled successfully. Continue with the process.
Toast.makeText(this, "ReadSms service has been enabled.", Toast.LENGTH_LONG).show()
} else
Toast.makeText(this, "The service failed to be enabled.", Toast.LENGTH_LONG).show()
}
task.addOnSuccessListener(this, OnSuccessListener {
if(task.isSuccessful){
Toast.makeText(this, "ReadSms service has been enabled.", Toast.LENGTH_LONG).show()
myReceiver = MyBroadcastReceiver();
val intentFilter = IntentFilter(READ_SMS_BROADCAST_ACTION)
registerReceiver(myReceiver, intentFilter)
}
})
task.addOnFailureListener(this, OnFailureListener {
Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show();
})
}
Broadcast receiver
class MyBroadcastReceiver : BroadcastReceiver() {
companion object {
val TAG = MyBroadcastReceiver::class.java.simpleName
}
override fun onReceive(context: Context?, intent: Intent?) {
val bundle = intent!!.extras
if (bundle != null) {
val status: Status? = bundle.getParcelable(ReadSmsConstant.EXTRA_STATUS)
if (status?.statusCode == CommonStatusCodes.TIMEOUT) {
// Service has timed out and no SMS message that meets the requirement is read. Service ended.
// doSomethingWhenTimeOut()
} else if (status?.statusCode == CommonStatusCodes.SUCCESS) {
if (bundle.containsKey(ReadSmsConstant.EXTRA_SMS_MESSAGE)) {
// An SMS message that meets the requirement is read. Service ended.
//doSomethingWhenGetMessage(bundle.getString(ReadSmsConstant.EXTRA_SMS_MESSAGE))
bundle.getString(ReadSmsConstant.EXTRA_SMS_MESSAGE)?.let {
Log.d(TAG, it)
val local = Intent()
local.action = "service.to.activity.transfer"
local.putExtra("sms", it)
context!!.sendBroadcast(local)
}
}
}
}
}
}
Any help in this would be beneficial.
Please confirm the following points:
Check whether the broadcast for receiving SMS verification codes is enabled. You can do that by performing breakpoint debugging or recording logs.
Check whether the SMS message format meets the rules for automatically reading SMS messages.
For details,See Docs.
Check whether the hash_value field is correct.
If no error occurs during the preceding check, could you pls provide a complete log trace then i will try to find out what can be wrong about this issue. :)
All code is working fine it works well on debug mode when I build released apk then keystore changed also hash changes for release mode. If you know anything about how to run on release mode , please let us know. Maybe some changes are made in Huawei developer account
I'm trying to write my very first liquidsoap program. It goes something like this:
sounds_path = "../var/sounds"
# Log file
set("log.file.path","var/log/liquidsoap.log")
set("harbor.bind_addr", "127.0.0.1")
set("harbor.timeout", 5)
set("harbor.verbose", true)
set("harbor.reverse_dns", false)
silence = blank()
queue = request.queue()
def play(~protocol, ~data, ~headers, uri) =
request.push("#{sounds_path}#{uri}")
http_response(protocol=protocol, code=20000)
end
harbor.http.register(port=8080, method="POST", "^/(?!\0)+", play)
stream = fallback(track_sensitive=false, [queue, silence])
...output.whatever...
And I was wondering if there is any way to push to the queue from the harbor callback.
Else, how should I proceed about making requests originate from HTTP calls? I really want to avoid telnet. My final objective is having an endpoint that I can call to make my stream play a file on demand and be silent the rest of the time.
give this a go its liquidsoap so its tricky to understand but it should do the trick
########### functions ##############
def playnow(source,~action="override", ~protocol, ~data, ~headers, uri) =
queue_count = list.length(server.execute("playnow.primary_queue"))
arr = of_json(default=[("key","value")], data)
track = arr["track"];
log("adding playnow track '#{track}'")
if queue_count != 0 and action == "override" then
server.execute("playnow.insert 0 #{track}")
source.skip(source)
print("skipping playnow queue")
else
server.execute("playnow.push #{track}")
print("no skip required")
end
http_response(
protocol=protocol,
code=200,
headers=[("Content-Type","application/json; charset=utf-8")],
data='{"status":"success", "track": "#{track}", "action": "#{action}"}'
)
end
######## live stuff below #######
playlist= playlist(reload=1, reload_mode="watch", "/etc/liquidsoap/playlist.xspf")
requested = crossfade(request.equeue(id="playnow"))
live= fallback(track_sensitive=false,transitions=[crossfade, crossfade],[requested, playlist])
output.harbor(%mp3,id="live",mount="live_radio", radio)
harbor.http.register(port=MY_HARBOR_PORT, method="POST","/playnow", playnow(live))
to use the above you need to send a post request with json data like so:
{"track":"http://mydomain/mysong.mp3"}
this is also with the assumption you have the harbor running which you should be able to find out using the liquidsoap docs
there are multiple methods of sending into the queue, there is telnet, you can create a http input, or a metadata request to playnow via the harbor, let me know which one you opt for and i can provide you with a code example
I'm trying to mimic a periodic token refresh. We have javascript code in our frontend that periodically checks if a token refresh needs to occur, and if so, issues a call to refresh the token. This is ran every couple minutes or so as long as anyone is using the application.
The typical user of our application will leave the app open without doing anything on it for time greater than the token lifetime. So I can't simply check and perform a token refresh on each call without adjusting the script to not mimic real life usage (because calls would need to occur more frequently).
Any ideas if, or how, this could be possible?
Okay, the best solution I could come up with was essentially to create my own "Pause" class, that breaks long pauses down into small pauses, and between each checks to see if the token needs refreshed. Looks roughly like this:
//new RefreshADToken().create() creates a ChainBuilder that refreshes the token if it's necessary
object PauseHelpers {
val tooBigOfPauseThreshold = 150 //300 seconds = 5 minutes, so anything over 150 is too big
def adPause(duration: Int): ChainBuilder = {
doIfOrElse(duration > tooBigOfPauseThreshold) {
val iterations = duration / tooBigOfPauseThreshold
repeat(iterations, "pause_counter") {
pause(tooBigOfPauseThreshold)
.exec(new RefreshADToken().create())
}.pause(duration % tooBigOfPauseThreshold).exec(new RefreshADToken().create())
} {
pause(duration).exec(new RefreshADToken().create())
}
}
}
//... then
import orhub.modules.actions._
class POC extends Simulation {
//some stuff
var scn = scenario("poc")
.feed(hospitalUsersFeeder)
.exec(session => {
session.set("env", environment)
})
.exec(new ADPause(120 * 60).create())