Delphi 10.4.1, Service in Android App with Timer - android

I found that with Delphi 10.4.1, putting a Timer component on the datamodule of a service associated with a multi-device app, starting the service the app closes immediately.
I assume it's a bug that has since been fixed in later versions.
I need to keep a cycle running within the service that periodically updates (every 2-3 hours) the data inside with data coming from an external server.
Not being able with timer, therefore in my case, to use timers, I had thought of a thread with a while loop inside it which verifies the timestamp and carries out the queries needed every certain period of time.
But I don't know if this would consume too many resources on the phone.
Would you have any suggestions?

Try using a native Android timer, not the Delphi TTimer. There is a source code coming with DelphiWorlds KastiFree that I use successful standalone without the rest of this package.
Find the unit here:
AndroidTimer

Related

Can i use flutter isolate for backround processes without touching Java/Kotlin?

I'm trying to create an app that manages a BLE connection in the background (receives notifications, reconnects and subscribes to a characteristic when connection is lost and the phone is moved near the BLE device again).
Right now I have the app somewhat built - everything that I need works relatively well but only when the app is open. Although the code isn't up to standard as this is my first app and I don't have any previous experience with Java/Kotlin/Dart (this is also why I'd rather not touch anything outside of flutter).
I need the app to send me local push notifications when tabbed out of the app or when screen lock is on and as far as I understand one could do this with isolates. I've searched a lot but found one guide which is kind of hard to understand as a beginner and also uses Kotlin.
Can I get away with only dart code for background code execution (described above) and is it suitable for a beginner?
Also, let me know if you have any alternative solutions since all I need is to get a notification on my phone whenever it receives a notification from a BLE device (and also auto connecting). I've already tried this with kivy since I'm more familiar with python but with no luck.
Talking about BLE there's this plugin by the way: https://pub.dev/packages/flutter_reactive_ble
As for the isolates, they are not ideal for this even though they do run separately, they'll get killed eventually. There's also a little helper package that makes working with isolates very straightforward if you want to try it: https://pub.dev/packages/computer
And so actually for the task at hand (background execution) I would suggest researching/using this one: https://pub.dev/packages/background_fetch
I would not encourage you to use any timer-based solution that tries to wake up your phone every 15 minutes or so, since that uses unnecessary CPU time.
Now I'm not that much into Flutter, but at least on Android, the "correct" way to have an ongoing connection (auto-connect) is to have a Foreground Service in the process running, so the process does not get killed. Then subscribe to characteristic notifications as usual, and handle the values as they arrive, either in Java or Flutter (by using some Java <-> Dart bridge).

In Android, should a contact sync adapter run in a separate process?

In my app, I'm using a contact sync adapter, but it has a lot of information that it shares with the main app. There are settings that the adapter needs to work proplery (like login information and if the user changes any sync settings), so I currently have it running in the same process, and it communicates with the main ap using getApplicationContext(), and then I have some shared variables in the Application that the sync adapter is using during the sync process.
But in the training document, and a few tutorials online, the sample adapter is set up to run in its own process -- it's using android:process=":sync" in the manifest. Is that necessary? And if it does run in a separate process, how can I communicate back to the main app?
In our context, due to fast searching requirement, we are using remote service to hold a huge database in memory.
The reason we are using remote service, instead of local service is that, we believe running the service in separate process, will make us harder to hit maximum memory per process limitation (The limitation is vary based on different devices and OS version).
In our initial design, we are using AIDL. Later, we switch to Messenger. I cannot recall the reason behind. I will check back our source code history log to figure out why. But, I think it is mostly, Messenger is less complicated than AIDL, and we do not need the multi-thread capability provided by AIDL.
Running Service in its own process may be helpful
1) if you want your service to withstand your main app's process destruction (but START_STICKY is more than enough for that case),
2) if you'd like to designate this process for all "sync" tasks of your application (as stated in the tutorial),
3) if you want other apps to use your Service.
To communicate with the Service running in separate process, you use Bound Services.
However, running Service in separate process increases the complexity of communicating with it, so consider if any of cases mentioned above relates to your app purposes.
I think it should be separated, but it's not required.
In general, separating a Service process is well worth to consider if it may be used independently from system components or other applications. In this perspective, the lifecycle of the process should be managed independently from other components such as Activity in the same app, so Android can mark which process is currently used easily and precisely to decide which process to be killed in case of a memory shortage. Also the service can keep running even if the front activity crashed unexpectedly.
It's hard to maintain sharing data between separate processes. For login credentials and preferences, I guess you may go with a combination of SharedPreferences and OnSharedPreferenceChangeListener.
When the application starts, it may cache different things, in particular for the UI. By splitting the sync logic in a different process, you allow the UI process to be killed when the device is running low in memory, which will free these UI caches.
Hence, this technique is primarily of interest to apps that run services for a long time. Typical examples:
the service that plays music in a music app
the service that uploads the video in Youtube
However:
this increases the complexity of the app
if done incorrectly, it can actually increase the overall memory footprint of the app

When to use and when not to use a Service in Android

I have been developing for Android for little less then 2 years, and I am still puzzled by this seemingly simple question.
When should one implement a service?
From my experience there are some rare cases but I am questioning this because on every phone there are quite a lot of them running and I doubt it's just a poor application design.
This is essentially core of my question but following are some of my experiences and thoughts about the subject which can explain my question in more detail.
In all apps that I have developed only one really required a service. It was a background sound recorder and I was using it as Foreground service with notification since I wanted buttons to be able to control it (like music players do for example).
Except this I never really saw a requirement for the constantly running service because:
A) Intent listeners (Manifest registered BroadcastReceivers) are quite a useful feature and using them as you know is usually enough for many use-cases (for example showing notifications).
B) If scheduled execution is a must one can subscribe to alarm events.
C) I know that service in Android is quite different then for example in Windows since in Android services are just a "package" to organize your code in and have a the system manage the lifetime of the object. Services use the Main Thread but it's customary to spawn new threads in them.
D) In the development documentation services are suggested for network communication and background calculations but I don't get why you should not just use AsyncTasks for that. I am a big fan of these and use them extensively for lot of things from downloading data from the internet to doing FFT calculations under time critical conditions.
E) I get the usefulness of Foreground services but why are people using background services so much (excluding the system apps).
Those are my thoughts about the SERVICE and I hope someone with more experience will be able to explain these PROS and CONS (along with others that I probably missed).
When should one implement a service?
When you have work -- delivering value to the user -- that:
Needs some time to complete, perhaps longer than you have time for in the component wishing the work to be done, or
Is delivering that value under user control (e.g., music player, controlled by play/pause buttons in a UI), or
In rare cases, needs to be running continuously, as it delivers value continuously
there are quite a lot of them running and I doubt it's just a poor application design
Some are likely to be poor implementations, either due to technical misunderstandings, or other concerns (e.g., making marketing happy) trumping making users happy.
It was a background sound recorder and I was using it as Foreground service with notification since I wanted buttons to be able to control it (like music players do for example)
That is a reasonable use for a service, IMHO.
Intent listeners are quite a useful feature and using them as you know is usually enough for many use-cases (for example showing notifications)
I assume that by "Intent listeners" you mean manifest-registered BroadcastReceivers. In that case, if the work to be done by the BroadcastReceiver will take more than a millisecond, that work should be delegated to an IntentService for completion. onReceive() is called on the main application thread, and it is not safe for a manifest-registered BroadcastReceiver to fork a bare thread, as the process could go away shortly after onReceive() returns. However, in these cases, the service is usually short-lived (e.g., do some network I/O and disk I/O, then go away).
In the development documentation services are suggested for network communication and background calculations but I don't get why you should not just use AsyncTasks for that
An AsyncTask is a fine solution for background work that is:
Requested by the UI (activity or fragment), and
Will take less than a second or so, and
Is non-critical
For example, if you are downloading avatars to show in a ListView, AsyncTask is probably a fine choice, whether you use them directly or use some image-fetching library that uses them internally.
Conversely, if the user buys an MP3 through your app, and you need to download that MP3 file, an AsyncTask is not a good solution. That could easily take over a second. While the download is going on, the user could switch away from the app (e.g., press HOME). At that point, your process is eligible to be terminated... perhaps before your download is complete. Using an IntentService to manage the download is a signal to the OS that you are really doing work here, adding value to the user, and so the process will be left alone for a little while.
Note that if the background work might take 15+ seconds, WakefulBroadcastReceiver or my WakefulIntentService is probably a good idea, so the device does not fall asleep while you are trying to wrap up this bit of work.
I can name some of the Service uses from my experience:
to implement
location listener,
sound module, generating various voices
in app content updates,
API, provide services to other apps
in app billing
Communication with webservices (if requests frequency is high)
actually (excluding 5.) they all are working for the whole app duration, they are using some of the other android services, also they manage their state. I suppose one of the important thing here is state management during application life cycle changes.
I prefer to look at AsyncTasks in a same way as Executors (ExecutorService), they should be executed sequentially and for small tasks.
In the android website, you can find a table when to use Service, Thread, or WorkManager (the new API for scheduling jobs, currently in alpha as of this comment posted). https://developer.android.com/guide/background/#table-choose
The website also state that you need to use started service only as last resort. The Android platform may not support started services in the future. Refer to this link https://developer.android.com/topic/performance/scheduling#services
You should avoid using started services that run perpetually or perform periodic work, since they continue to use device resources even when they aren't performing useful tasks. Instead, you should use other solutions that this page describes, and that provide native lifecycle management. Use started services only as a last resort. The Android platform may not support started services in the future.
If you consider UI and bound services, u would think that both can exist and not be doing anything for certian periods. In such scenarios, your UI can be recreated a lot of times however service does not. And this is where service is important. Lets say you are processing images and then rotate device you want processing to continue while UI is being recreated. You recording a voice and then rotate device. These are one of the places where I find service very important. (Having lot of heavy data processing, interaction with web, that could be few seconds)

implementing long running background tasks in phonegap

I am trying to run a snippet of javascript which keeps polling the server for updates. what is the best way to get this working with minimal impact on application performance from the end user perspective.
I tried spawning it off in a separate iframe but the resultant performance was pretty bad.
I am currently working on android so if the solution involves writing a phonegap plugin to poll the server instead of javascript that should be fine for now. I need to update data in local storage after polling the server.
I have implemented this in IOS. The problem with phonegap is that you can't create a timer task that runs javascript because if your .html page changes the task would be killed.
Unless you just have ONE .html and you are dynamically changing the body part. If that is the case then look up setInterval in javascript.
If that isn't the case then implementing something on javascript isn't a solution, in IOS I have implemented a custom plugin for running asynchronous web service calls. You could do something similar, writing a plugin that runs a AsyncTask doInBackground() and then postback the results in the javascript. There are many tutorials on how to create a custom plugin in phonegap. Hope it helps
If you are planning to poll only when the application is in use the setInterval() works fairly well. My application is using jQuery Mobile which by default only updates DOM rather reloading entire page, that way my setInterval() keeps running once started.
Android already has a support of Background services, which you can use for the long and continuous running tasks.
One solution which I have used with above combination:
when the app is running I use setInterval() to check for update periodically.
Background checks whether application is running or not before starting the update checks
If the app is not running then I use the background service code just to check whether there are any updates on server or not
If there are updates then I put a system tray notification to notify user that there are updates waiting for him
As soon as he starts the application, I call the service to fetch the updates.
This way my main logic remains in the Javascript side and I need not to write same logic in both Javascript and native again.
If updates are not very frequent then you should consider using PushNotification

Does this Android application require a Service/IntentService?

/** Start of pseudocode **/
1) After a specified delay, the application requests data from a Bluetooth device.
2) The application saves and analyzes the data.
3) IF the analysis results are abnormal, the application sets off an alarm and returns to step 1) with a shortened delay.
ELSE the application returns to step 1) as normal.
/** End of pseudocode **/
I currently have an implementation working that utilizes a Timer and TimerTasks to analyze some data in a .txt file repeatedly after various delays. Later on in the application's development the data will be received from a Bluetooth device (the Android emulator doesn't support Bluetooth).
I can't have the main UI thread busy handling this stuff - I need some form of asynchronous (multi-threaded) approach (ie. the TimerTask).
I also need this analysis process to continue even if the user switches to another application.
Do I need to use a Service/IntentService to ensure this Bluetooth reception & analysis procedure remains active?
As a beginner Android developer, I would appreciate any advice on the subject. I am currently trying to understand Services and IntentServices.
If you are trying to understand Service and IntentService, I would recommend you to take a look at this post and related posts. It compares various task execution mechanisms in Android and provides a rough guideline on when to use what.
Yes, services are designed exactly for that: asynchronous tasks that can take a long time and need to keep running even when the activity is closed.
I have done similar task in the past with reading bluetooth data using service. You may need to look into using headless service. The service runs even when you go to other apps and when you come back binds with your activity.

Categories

Resources