Search code examples
javaandroidmultithreadingperformanceservice

Better performance for my Service by setting a Thread with a higher priority?


I wrote an app that basically take screenshots every few seconds and perform some analysis on that image. The whole work is done basically inside a Thread and that thread is created and started in a foreground service.

  @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
         testThread = new TestThread(MyService.this, true, username, email);
         testThread.start();
         sendNotification("Running...");
    }

My main goal is performance. Why? Because my service gets killed after few hours since I am using computer vision algorithms.

First off, I want to say that I've chosen Service instead of WorkManager because it's a very long running task (it should run for an indefinite amount of time).

By reading this: https://developer.android.com/topic/performance/threads#java I learned that threads in the foreground group get about 95% of the total execution time from the device, while the background group gets roughly 5%. Now since my Thread is created and started inside a Service, by default the priority should be -2 which is THREAD_PRIORITY_FOREGROUND, am I correct? By setting a higher priority like Int THREAD_PRIORITY_URGENT_AUDIO would I increase the performance of my service, hence making my service last longer? Thanks.


Solution

  • This is just never going to work on Android. The Android OS reserves the right to kill any service at any time for any reason. In fact background services are typiucally killed about 2 minutes after they are no longer the foreground app, unless the foreground app had explicitly bound them. You can use a foreground service, but that has additional restrictions and STILL will be killed after a while. Reliable background processing is something the Android OS explicitly does NOT provide, in order to save battery power and extend device life.

    If the device is allowed to be in one place, the best way to do this is via adb with a PC attached running a script to take a screenshot via abd every few seconds. And then you can do the computer vision on the much more powerful PC. If you can't leave a PC attached, you're really not going to have much luck, or much battery life while this is running.

    Also, changing the priority won't really help much. THe Linux scheduler doesn't just give the CPU to the highest priority. It's a complex algorithm involving recent usage and whether your process is CPU or IO bound. Bumping it doesn't just give you what you want. For the most part you can only really voluntarily lower your priority. Which makes sense- otherwise every app would raise all of their threads to max to always get all the CPU time they need, which would result in priority being useless.