Do you have any ideas on how to solve in an android long time of waiting on server response?
I am making a request to the API saving profile.
This request is fast
But the server is processing it rather long 10sec to 3min (like scanning cheap flight on some tickets sites)
After the response, I need to redirect the user to a confirmation screen or home screen of the app.
I solved this by setting the longer timeout to 45 sec and then always redirecting to confirmation + alert that it takes longer.
On the home screen, I am displaying "Processing..." label until the server finishes
But this solution has some problems like:
what about user going out by home button if it takes longer, or switching applications, and if just display goes to sleep while untouched more than 30sec? Then activity/fragment is recreated and response seems to not arrive.
I consider adding push notification when processing is done this could help a little. Is there any way to solve such an issue? Maybe some background Service? But isn't Android Services deprecated? I think only Foreground Services are valid to use, or maybe new WorkManagers (but this doesn't seem to fit this scenario). And how from then wakeup screen and move it to the next page.
Code sample:
// Fragment
viewModel.saveData(data)
// View Model
fun saveData(data: Data) : LiveData<Resource<DataResponse>> {
_dataEvent.postValue(Event(Resource.loading(null)))
val apiSource = dataRepo.saveData(data)
_dataEvent.addSource(apiSource) { resource ->
_dataEvent.removeSource(apiSource)
val resource = resource ?: Resource.error(null, null)
_dataEvent.postValue(Event(resource))
}
return apiSource
}
// Observing Data Event
viewModel.dataEvent.observe(this,
Observer { event ->
if(event?.peekContent()?.status == Resource.Status.LOADING) {
showProgressAlert(context)
event.getContentIfNotHandled() // consume loading event
}
val resource = event?.getContentIfNotHandled()
if(resource != null) {
hideProgressAlert()
if (resource.status == Resource.Status.SUCCESS) {
showSuccessAlert(context)
navigateToConfirmPage()
} else if (resource.status == Resource.Status.ERROR) {
if (throwable is SocketTimeoutException) {
showTimeoutAlert(context)
navigateToConfirmPage()
} else {
showErrorAlert(context)
}
}
}
If this request is taking a long time then you should perform it in a background thread, Since android oreo background services became very restricted if you want to implement it you can use JobIntentService or JobScheduler or make it a ForegroundService but in this case you will have to show a notification to the user while the service is running, You can read more about it here https://developer.android.com/about/versions/oreo/background
Another approach is to use RXjava which handles threading and perform background services very smoothly
Related
I'm using CameraX's image analysis use case that keeps calling the analyze() method in my custom Analyzer class. Inside analyze(), before doing anything else, I need to send a request to a connected device and wait for its response; the latency is very low and I'm already doing it synchronously with no issues, but I was told it's better to make it asynchronous just in case the device responds too slowly.
I know that MLKit's process() returns a Task<List<T>> and I already call onSuccessListener { } on it, so I was wondering if I can use a similar approach (I can't return a Task<T> from my function, how do I create one?). Otherwise would you suggest threads, or coroutines, or something else?
Edit: below there's a simplified example of what I'm trying to do. For a given frame sent by the camera I just need to perform only the current analysis in line, then I return so that analyze() will be called again with the next frame, on which it will perform the next analysis.
It might look hacky but it's for an app that continuously runs in foreground on a single-purpose device (let's call it Dev A) with no user interaction provided by touch or other conventional means, so it needs some kind of trigger to start doing what is required.
The trigger might as well be when the first image analysis in line is successful, but running MLKit or TFLite models from real time camera feed all day long makes Dev A overheat excessively. The best solution so far seems to be waiting for the trigger to come from an external device (Dev B) that operates independently.
Since Dev B may respond with some delay I need to communicate with it asynchronously, hence the reason for the question in the first place. While there are certainly several architectural nuances to discuss, the current root of the problem is that I can't decide (or rather I don't know) how to handle the repeating "connection" with Dev B in a non-blocking way.
I mean, can I just treat this issue like any other case where multithreading is needed, or the fact that the camera is involved might pose additional threats? The backpressure strategy is set to STRATEGY_KEEP_ONLY_LATEST, so in theory if the current call to analyze() hasn't finished yet the new frames are dropped and nothing bad happens even if inside the method I'm still waiting for the async call to Dev B to finish, or am I missing something?
var connected = false
lateinit var result: Boolean
var analysis1 = true
var analysis2 = true
override fun analyze() {
if (!connected) {
result = connectToDevice() // needs to be async
connected = true
}
// need positive result to proceed, otherwise start over
if (!result) {
connected = false
return
}
if (analysis1) {
// perform analysis #1...
analysis1 = false
// when an analysis is done, exit early and perform next analysis on next frame
return
}
if (analysis2) {
// perform analysis #2...
analysis2 = false
// same as above
return
}
// when all analyses are done, reset all flags to start over
connected = false
analysis1 = true
analysis2 = true
}
I have an app that makes an http request via the localhost to a separate, third-party app which I do not control, and waits for a response from that call before continuing. The workflow goes like this:
User is inside my app
User presses a button, which launches and calls out to the third-party application
User interacts with the third-party application
When the third-party application finishes its work, my app picks up the completed http response, and pulls itself back to the forefront via MoveTaskToFront for the user to continue working.
This functions properly in Android 9 and below, but the last step does not work in Android 10, I believe due to the new restrictions on launching activities from the background.
I have no control over the third-party app, so I cannot modify it to close itself when finished working, or request that the calling app be returned to the foreground when appropriate. Does anyone know of a workaround for this?
Edit: as requested, I've added the code snippet with the call out. This is a Xamarin project, so it's written in C#, but this particular code section is Android-platform-specific, so I am able to make Android system calls.
First I have to bring up the third-party app:
Intent intent = CrossCurrentActivity.Current.AppContext.PackageManager.GetLaunchIntentForPackage("com.bbpos.android.tsys");
if (intent != null)
{
// We found the activity now start the activity
intent.AddFlags(ActivityFlags.ClearTask);
CrossCurrentActivity.Current.AppContext.StartActivity(intent);
}
Then I call into it via the localhost, process the response, and want to switch back to my app.
using (var client = new HttpClient())
{
// by calling .Result we're forcing synchronicity
var response = client.GetAsync("http://127.0.0.1:8080/v2/pos?TransportKey=" + pTransportKey + "&Format=JSON").Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
// as above, forcing synchronicity
string responseString = responseContent.ReadAsStringAsync().Result;
var result = JsonConvert.DeserializeObject<GeniusTransactionResponse>(responseString);
var manager = (ActivityManager)Application.Context.GetSystemService(Context.ActivityService);
var test = manager.AppTasks.First().TaskInfo.Id;
manager.AppTasks.First().MoveToFront();
//manager.MoveTaskToFront(CrossCurrentActivity.Current.Activity.TaskId, 0);
return result;
}
else
{
return null;
}
}
Quick update in case anyone else has this same issue: I was able to work around this by adding an Accessibility Service to the project. Simply having an Accessibility Service registered and enabled by the user allows MoveTaskToFront to function as it did in APIs <29; the actual service doesn't need to do anything.
What I want to achieve is, when user enter geofencing, the beacons foreground service will start to run and after one beacon detected, I will kill this foreground service and start to run it on the background just like the sample code on android-beacon-library-reference library.
private fun monitorBeacons(startForegroundService: Boolean) {
var beaconManager = WolApp.appContext?.beaconManager
if (beaconManager == null) {
WolApp.appContext?.beaconManager = BeaconManager.getInstanceForApplication(WolApp.appContext!!)
beaconManager = WolApp.appContext?.beaconManager
beaconManager?.backgroundMode = true
beaconManager?.beaconParsers?.clear()
beaconManager?.beaconParsers?.add(BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"))
beaconManager?.removeAllMonitorNotifiers()
}
if (startForegroundService) {
setupForegroundNotificationService(WolApp.appContext!!)
} else {
WolApp.appContext?.regionBootstrap?.disable()
WolApp.appContext?.regionBootstrap = null
try {
WolApp.appContext?.beaconManager?.disableForegroundServiceScanning()
} catch (e: IllegalStateException) {}
if (beaconManager?.scheduledScanJobsEnabled == false) {
beaconManager.setEnableScheduledScanJobs(true)
beaconManager.backgroundBetweenScanPeriod = BeaconManager.DEFAULT_BACKGROUND_BETWEEN_SCAN_PERIOD
beaconManager.backgroundScanPeriod = BeaconManager.DEFAULT_BACKGROUND_SCAN_PERIOD
}
}
if (WolApp.appContext?.regionBootstrap == null) {
WolApp.appContext?.regionBootstrap = RegionBootstrap(WolApp.appContext!!, regions)//regions are some iBeacon regions
}
if (!startForegroundService) {
WolApp.appContext?.backgroundPowerSaver = BackgroundPowerSaver(WolApp.appContext!!)
}
}
For setupForegroundNotificationService method is same with android-beacon-library-reference library.
I'm not quite sure if I'm doing this right or wrong, can anyone help, please?
It is a little bit tricky to switch a foreground service on or off because you are trying to change the behavior of multiple threads of execution that are already running behind the scenes in existing services.
The key thing missing from the code shown is that you must also make sure you have stopped the library from scanning before you can switch. This is complex because it is asynchronous -- it takes time for the scanner to shut down its threads.
If using regionBootstrap, the call to regionBootstrap.disable() does this. (You can also use beaconManager.unbind(...) if not using regionBootstrap). But the problem is those APIs do not give you a callback when the scaning service is fully shut down. And restarting it again before it is shut down can cause problems. I do not have a great suggestion here , other than perhaps using a timer -- say one second between stop and start?
You might also want to look at this discussion of a similar setup:
https://github.com/AltBeacon/android-beacon-library/issues/845
I developed an android turn based game and so far I can make the first move but when I want the user would wait for the second player to play the app crashes.
What I tried to do is when the player finishes his move I call a function like this:
public void TheThread()
{
boolean fy=false;
while(!fy)
{
if(CheckMove2())
fy=true;
}
}
The checkmove2 function connects the parse table and check if is there a turn and return boolean.
I beleive this is not the right way to do it,thanks for your help.
Edit:
ChecKmove2() function:
private boolean CheckMove2() {
fx=false;
ParseQuery query = new ParseQuery("serverturn");
query.whereEqualTo("Receiver", Sender);
query.getFirstInBackground(new GetCallback() {
public void done(ParseObject updatePO, ParseException ParseError) {
if(ParseError == null){
fx=true;
String objID;
x=updatePO.getInt("x");
y=updatePO.getInt("y");
try {
updatePO.delete();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
///here comes the game algorithm.
if(fx)
return true;
return false;
}
Edit: the app not crashes its just stop and alert: "The app is not responding" and then asks if I want to wait or close the app.The checkmove function works perfectly I checked it with other devices,the problem is to use this checkmove function in a while loop so the user would wait for the opponent turn.
Your application is crashing because in that scenario you've caused an endless loop (if there are no other moves waiting). So the OS will, most likely force close your application because it thinks its become unresponsive.
What you're better off doing is this:
Create a background service with an AyncTask to check for other players moves at specific intervals (10 - 15 mins maybe?)
Once a move is found. Alert the player to it by using a Notification which would link to your app via an Intent
As a side note, you should always use background threads/async tasks etc to talk to networks.
On your place i would do next:
In parse cloudCode afterSave or beforeSave of the object you are waiting for, send a socket message to your app when the needed object is updated. For example using pubnub.com
I think this is a decent solution, but running some loopy checking logic seemes so unprofessional.
In general it works like this:
two players subscribe to a channel
when one finishes move, from cloud code send a message to this
channel
catch it in your app.
The message can trigger update from parse or can contain the needed data itself.
I'm trying to implement a convenient-to-use system for handling status bar notifications for android, and i was thinking about the following:
Create a database, where i store when and what to show
Create a service what runs in the background using the 'interval' Service, what the API provides
In that service check if any notification needs to be shown according to the database, then show it.
The only problem is, that, i cannot detect, if i need to start the service or not. I tried these things, but none of them worked well so far:
1.) Save if the service was already started on the local storage:
// Do this on application startup
var isRunning = Ti.App.Properties.getBool("service_running", false);
if(!isRunning)
{
var service = Titanium.Android.createService(...);
service.addEventListener('start', function()
{
Ti.App.Properties.setBool("service_running", true);
});
service.addEventListener('stop', function()
{
Ti.App.Properties.setBool("service_running", false);
});
service.start();
}
This obviously won't work, because the android systems native onStop and onDestroy events will not be dispatched, if the Service doesn't terminates unusually (like the user force stops the app), so the stop event also won't be fired.
2.) Try to access any active service via Titanium.Android.getCurrentService(), but i got an error saying Titanium.Android has no method called getCurrentService(). This is pretty strange, because the IDEs code completion offered me this method.
3.) Use an Intent to clear the previously running Service
var intent = Titanium.Android.createServiceIntent
(
{
url : 'notification/NotificationService.js'
}
);
intent.putExtra('interval', 1000 * 60);
//Stop if needed
Titanium.Android.stopService(intent);
//Then start it
Titanium.Android.startService(intent);
But it seems like i need to have the same instance of Intent, that started the service to stop it, because doing this on application startup, then exiting and restaring it results in multiple Services to run.
At this point i ran out of ideas, on how to check for running services. Please if you know about any way to do this, let me know! Thanks for any hints!
EDIT
Here are the source materials which gave me the idea to try the above methods (maybe only i use them incorrectly):
The local storage: Titanium.App.Properties
The method for accessing running services: Titanium.Android.getCurrentService
The method for stoping a service with an Intent: Titanium.Android.stopService
And the full source for the NotificationHandler "class" and NotificationService.js that I wrote, and their usage: link
Use Bencoding AlarmManager and it will provide all you need to schedule an alarm notification : https://github.com/benbahrenburg/benCoding.AlarmManager
This module provides what you need. It's really easy - just set repeat to daily when sheduling a Notification or Service.
Refer https://gist.github.com/itsamiths/6248106 for fully functional code
I am checking if the service is started then show daily notification or else start service and then show daily notification
var isRunning = Ti.App.Properties.getBool("service_running", false);//get service running bool status
if (isRunning) {
Ti.API.info('service is running');
} else {
Ti.API.info('service is not running');
alarmManager.addAlarmService({
service : 'com.mkamithkumar.whatstoday.DailyEventNotificatoinService',
hour : "08",
repeat : 'daily'
});
}
I come one year late, but maybe this can help others in the future.
We had the same idea: run the service forever and do the checks on every cycle (I must check 20 different communications).
And I had the same problem: how to detect that the service is running, to don't run again to don't duplicate the checks.
To solve that problem, what I did is get the current time on every cycle and save it to store.
Then, before launch a new service, I check if the last execution was to far in time: if true, then the service was stopped, else is running.
Not very elegant, but was the only way I found to avoid the problem of the user killing the app (and the service).
This is my code for the "launcher" of the service. In my case, I test 30 seconds far away:
exports.createAndroidServiceForNotifications = function(seconds) {
var moment = require('alloy/moment');
var diffSeconds = moment().diff(Ti.App.Properties.getString('serviceLastRun', new Date().getTime() - 60000), 'second');
if (diffSeconds > 30) {
var now = new Date().getTime();
var delta = new Date(now + (seconds * 1000));
var deltaMS = delta - now;
var intent = Ti.Android.createServiceIntent({
url : 'notificationsService.js'
});
intent.putExtra('interval', deltaMS);
Ti.Android.startService(intent);
}
};