AlarmManager or JobScheduler compatible with all Android versions? - alarmmanager

I need some help deciding which classes to adopt in my app that has to fulfill these requirements:
Firing of the alarms at exact times (down to the second)
Can have multiple alarms in the system (triggering at different times).
Should awaken the device if asleep and keep it awake until the user completes a defined task.
Should run on as many Android versions as possible, at least from 4.0 and up (the fact that you can use an old phone to run this app is a plus).
I've coded a small demo with AlarmManager & BroadcastReceiver to get an understanding of how all of this works. I've studied the docs for AlarmManager, BroadcastReceiver, WakefulBroadcastReceiver, and JobScheduler and even though I understand the differences, I don't know which one(s) will satisfy my requirements.
From the documentation, I get the impression that I might need to write multiple versions of my app to accommodate the different Android versions it will run on. This would be a nightmare!
Any suggestions on which classes to use? I would hate to go in one given direction only to later find out that I need to rewrite everything.
Thanks!

You don't need multiple versions of your app, you just need multiple "scheduler" implementations, each with just a couple files, and all call the same app logic.
Firing of alarms at exact times (down to the second)
Well, there's only one option that handles this. You need an AlarmManager.setExact. This is strongly discouraged, because it tends to waste battery.
Can have multiple alarms in the system (triggering at different times).
Every option there handles that, as long as you give them different ids.
Should awaken the device if asleep and keep it awake until the user completes a defined task.
Sounds like you need to have your alarm call Context.StartForegroundService, and leave that foreground service running until the user completes the task. Again, this is discouraged, because it wastes battery.
Should run on as many Android versions as possible, at least from 4.0 and up (the fact that you can use an old phone to run this app is a plus).
AlarmManager and foreground services run on all versions of Android, though the call to start a foreground Service has changed slightly with Android O, the concept is identical.
While your app is doing something important that needs to execute RIGHT NOW, even if the screen is off, then you should grab a wakelock. A wakelock prevents the CPU from pausing itself, so that you can process what needs to immediately occur. If the code can wait until the screen is turned on, then please do not use a wake lock. JobService grabs a wakelock always, so JobService code does not need to grab a separate wakelock. If you have no service running, including a JobService, then Android will randomly stop your app, even if you have a wakelock. So you always need a service of some sort, while doing any important work.

Related

Why does my program run faster on first launch than on next launches?

I have been working for 2.5 years on a personal flight sim project on my leisure time, written in C++ and using Opengl on a windows 7 PC.
I recently had to move to windows 10. Hardware is exactly the same. I reinstalled Code::blocks.
It turns out that on first launch of my project after the system start, performance is OK, similar to what I used to see with windows 7. But, the second, third, and all next launches give me lower performance, with significant less fluidity in frame rate compared to the first run, detectable by eye. This never happened with windows 7.
Any time I start my system, first run is fast, next ones are slower.
I had a look at the task manager while doing some runs. The first run is handled by one of the 4 cores of my CPU (iCore5-6500) at approximately 85%. For the next runs, the load is spread accross the 4 cores. During those slower runs on 4 cores, I tried to modify the affinity and direct my program to only one core without significant improvement in performance. The selected core was working at full load, though.
My C++ code doesn't explicitly use any thread function at this stage. From my modest programmer's point of view, there is only one main thread run in the main(). On the task manager, I can see that some 10 to 14 threads are alive when my program runs. I guess (wrongly?) that they are implicitly created by the use of joysticks, track ir or other communication task with GPU...
Could it come from memory not being correctly freed when my program stops? I thought windows would free it properly, even if I forgot some 'delete' after using 'new'.
Has anyone encountered a similar situation? Any explanation coming to your minds?
Any suggestion to better understand these facts? Obviously, my ultimate goal is to have a consistent performance level whatever the number of launches.
trying to upload screenshots of second run as viewed by task manager:
trying to upload screenshots of first run as viewed by task manager:
Well I got a problems when switching to win10 for clients at my work too here few I encountered all because Windows10 has changed up scheduling of processes creating a lot of issues like:
older windowses blockless thread synchronizations techniques not working anymore
well placed Sleep() helps sometimes. Btw. similar problems was encountered when switching from w2k to wxp.
huge slowdowns and frequent freezes for few seconds on older single threaded apps
usually setting affinity to single core solves this. You can do this also in task manager just to check and if helps then you can do this in code too. Here an example on how to do it with winapi:
Cache size estimation on your system?
messed up drivers timings causing zombies processes even total freeze and or BSOD
I deal with USB in my work and its a nightmare sometimes on win10. On top of all this Win10 tends to enforce wrong drivers on devices (like gfx cards, custom USB systems etc ...)
auto freeze close app if it does not respond the wndproc in time
In Windows10 the timeout is much much smaller than in older versions. If the case You can try running in compatibility mode (set in icon properties on desktop) for older windows (however does not work for #1,#2), or change the apps code to speed up response. For example in VCL you can call Process Messages from inside of blocking code to remedy this... Or you can use threads for the heavy lifting ... just be careful with rendering and using winapi as accessing some winapi (any window/visual related stuff) functions from outside main thread causes havoc ...
On top of all this old IDEs (especially for MCUs) don't work properly anymore and new ones are usually much worse (or unusable because of lack of functionality that was present in older versions) to work with so I stayed faith full to Windows7 for developer purposes.
If none of above helps then try to log the times some of your task did need ... it might show you which part of code is the problem. I usually do this using timing graph like this:
both x,y axises are time and each task has its own color and row in graph. the graph is scrolling in time (to the left side in my case) and has changeable time scale. The numbers are showing actual and max (or sliding avg) value ...
This way I can see if some task is not taking too much time or even overlaps its next execution, peaks are also nicely visible and all runs during runtime without any debug tools which might change the behavior of execution.

Blocking processes to start on startup from a service & continue running service after some processes are down.

I have a C++ windows service running on system privileges and I need to make some changes in some of my DLLs that are loaded to several windows processes (explorer.exe, etc.).
The only time to do so is when these processes are down. I'm trying to make to impact to the UX minimal, so I don't wan't to force quit those or to popup any annoying message boxes and ask the user to do so.
I have tried to start this task on the startup of my service, the issue is several of these processes start before I finished it.
I'm trying to understand if there is a way to delay the start of processes on Windows startup, until I finish my task. Is there any event or anything familiar that I can set that will block those?
The other option is to do the needed task on shutdown. I did not find a way to do so yet, and all the related questions seem a bit old (how to delay shutdown and run a process in window service
), and regard to older version of windows.
This solution needs to be compatible with Windows versions greater than 7.
You can do this by using MoveFileEx and setting MOVEFILE_DELAY_UNTIL_REBOOT which will replace the file at the next reboot.
This should be well before any other processes have started, but without more details on your usecase its hard to tell if this'll work for you. Either way, searching for this flag should give you lots of information about this kind of issue.
According to the documentation, this has been supported since XP.

Synchronous single file download - is it the right approach in a GUI Qt application?

I'm developing an updater for my application in Qt, primarily to get to know the framework (I realize there are multiple ready-made solutions available, that's not relevant here). It is a basic GUI application using a QMainWindow subclass for its main window and an MyAppUpdater class to perform the actual program logic.
The update information (version, changelog, files to be downloaded) is stored on my server as an XML file. The first thing the updater should do after it sets up the UI is query that server, get the XML file, parse it and display info to the user. Here's where I have a problem though; coming from a procedural/C background, I'd initiate a synchronous download, set a timeout of maybe 3 seconds, then see what happens - if I manage to download the file correctly, I'll parse it and carry on, otherwise display an error.
However, seeing how inconvenient something like that is to implement in Qt, I've come to believe that its network classes are designed in a different way, with a different approach in mind.
I was thinking about initiating an asynchronous download in, say, InitVersionInfoDownload, and then connecting QNetworkReply's finished signal to a slot called VersionInfoDownloadComplete, or something along these lines. I'd also need a timer somewhere to implement timeout checks - if the slot is not invoked after say 3 seconds, the update should be aborted. However, this approach seems overly complicated and in general inadequate to the situation; I cannot proceed without retrieving this file from the server, or indeed do anything while waiting for it to be downloaded, so an asynchronous approach seems inappropriate in general.
Am I mistaken about that, or is there a better way?
TL;DR: It's the wrong approach in any GUI application.
how inconvenient something like that is to implement in Qt
It's not meant to be convenient, since whenever I see a shipping product that behaves that way, I have an urge to have a stern talk with the developers. Blocking the GUI is a usability nightmare. You never want to code that way.
coming from a procedural/C background, I'd initiate a synchronous download, set a timeout of maybe 3 seconds, then see what happens
If you write any sort of machine or interface control code in C, you probably don't want it to be synchronous either. You'd set up a state machine and process everything asynchronously. When coding embedded C applications, state machines make hard things downright trivial. There are several solutions out there, QP/C would be a first class example.
was thinking about initiating an asynchronous download in, say, InitVersionInfoDownload, and then connecting QNetworkReply's finished signal to a slot called VersionInfoDownloadComplete, or something along these lines. I'd also need a timer somewhere to implement timeout checks - if the slot is not invoked after say 3 seconds, the update should be aborted. However, this approach seems overly complicated
It is trivial. You can't discuss such things without showing your code: perhaps you've implemented it in some horribly verbose manner. When done correctly, it's supposed to look lean and sweet. For some inspiration, see this answer.
I cannot proceed without retrieving this file from the server, or indeed do anything while waiting for it to be downloaded
That's patently false. Your user might wish to cancel the update and exit your application, or resize its window, or minimize/maximize it, or check the existing version, or the OS might require a window repaint, or ...
Remember: Your user and the environment are in control. An application unresponsive by design is not only horrible user experience, but also makes your code harder to comprehend and test. Pseudo-synchronous spaghetti gets out of hand real quick. With async design, it's trivial to use signal spy or other products to introspect what the application is doing, where it's stuck, etc.

Listen For Process Start and End

I'm new to Windows API programming. I am aware that there are ways to check if a process is already running (via enumeration). However, I was wondering if there was a way to listen for when a process starts and ends (for example, notepad.exe) and then perform some action when the starting or ending of that process has been detected. I assume that one could run a continuous enumeration and check loop for every marginal unit of time, but I was wondering if there was a cleaner solution.
Use WMI, Win32_ProcessStartTrace and Win32_ProcessStopTrace classes. Sample C# code is here.
You'll need to write the equivalent C++ code. Which, erm, isn't quite that compact. It's mostly boilerplate, the survival guide is available here.
If you can run code in kernel, check Detecting Windows NT/2K process execution.
Hans Passant has probably given you the best answer, but... It is slow and fairly heavy-weight to write in C or C++.
On versions of Windows less than or equal to Vista, you can get 95ish% coverage with a Windows WH_CBT hook, which can be set with SetWindowsHookEx.
There are a few problems:
This misses some service starts/stops which you can mitigate by keeping a list of running procs and occasionally scanning the list for changes. You do not have to keep procs in this list that have explorer.exe as a parent/grandparent process. Christian Steiber's proc handle idea is good for managing the removal of procs from the table.
It misses things executed directly by the kernel. This can be mitigated the same way as #1.
There are misbehaved apps that do not follow the hook system rules which can cause your app to miss notifications. Again, this can be mitigated by keeping a process table.
The positives are it is pretty lightweight and easy to write.
For Windows 7 and up, look at SetWinEventHook. I have not written the code to cover Win7 so I have no comments.
Process handles are actually objects that you can "Wait" for, with something like "WaitForMultipleObjects".
While it doesn't send a notification of some sort, you can do this as part of your event loop by using the MsgWaitForMultipleObjects() version of the call to combine it with your message processing.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion
\Image File Execution Options
You can place a registry key here with your process name then add a REG_SZ named 'Debugger' and your listner application name to relay the process start notification.
Unfortunately there is no such zero-overhead aproach to recieving process exit that i know of.

How to detect incoming call on N900 and display info window based on caller?

Does the N900 allow me to display additional information in parallel to the native application or does the latter always have priority over my process?
I'm interested in displaying additional information based on caller id.
If it's possible, can you name any pitfalls or give small python code examples / or tipps to get started?
detecting incoming call might be the smallest problem you will see in this journey - you can start with this thread
now consider few other factors before you decided whether you want to continue or not:
calls come not only as phone call but also as SIP call, Skype call, GTalk call, etc
call signaling is relatively resource-heavy due to time constraints vs blocked by I/O, etc
call dialog should work ok in portrait and landscape, so you might need to go down extending call architecture not writing my own little thing in 1-2 weekends
internal eMMC storage is not quick and gets slow on 2+ threads trying to write
if you are Ok with risk to spent time and bump into limitations of Maemo5 platform put on end-of-lifecycle hook -- consider learning down googleing keywords maemo5 telepathy mission-control . this is starting point not definitive guide -- you have to learn quit many different things before you start to approach plugging call progress dialogs.