TimSim
TimSim

Reputation: 4036

Creating a low priority Android service

Amazingly, no one on the internet ever needed to create a low priority Android service, but I do. The service may occasionally need to do some intensive CPU or database work, so I want it to have the lowest possible priority. If it makes any difference, I need the service to read entries (could be several thousand) from a database in one go and then iterate through the list and add and subtract some values. It's very important that this creates the lowest CPU load as possible, I don't care if it's completed in 1 second or 10 seconds.

Android dev docs provide an example like this:

  @Override
  public void onCreate() {
    // Start up the thread running the service.  Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block.  We also make it
    // background priority so CPU-intensive work will not disrupt our UI.
    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
  }

Full example (http://developer.android.com/guide/components/services.html) involves a service handler and a looper, which are not explained in this example. Are these necessary to make the service low priority or is this just dev docs complicating things and there is another way to make sure the service is low priority?

Upvotes: 3

Views: 1909

Answers (2)

jyoti
jyoti

Reputation: 31

I have tried many different ways but this code snippet helped me for the same process.

android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

Upvotes: 3

Nick Palmer
Nick Palmer

Reputation: 2753

The important thing for your use case is to process the information in a thread you create with Process.THREAD_PRIORITY_BACKGROUND. You can also process things in another thread that you have called Thread.setPriority on. (See the docs on Thread)

The android convention for sending commands to another thread is using a Handler and a Looper, but you are not required to use these to ensure low prority. A Handler gives you a convention for sending messages to the thread to be processed one at a time. It also gives conventions for posting items to be run after some delay or run after some time. A Handler is associated with a Looper which takes care of dispatching messages to the handler.

Upvotes: 3

Related Questions