7

I am working on app that check some of the status of phone every 5 seconds. I done it that:

Thread checking = new Thread() {
    public void run(){
        while( <<some status>> ) {
            <<checkstatus and do something>>
            Thread.sleep(5000);
        }
    }
}

This is bad for the battery? How can I do it in the other way? Service stop working after couple seconds.

Seraphim's
  • 12,559
  • 20
  • 88
  • 129
Mateusz Kaflowski
  • 2,221
  • 1
  • 29
  • 35

2 Answers2

7

To answer your question, it depends what you are doing inside the while loop.

If you are not using and waking up any "expensive" components (such as internet, bluetooth, other sensors, and screen), you should be fine. Essentially this is how the OS works in the background anyways and using a Thread is one of the cheapest ways.

Also, if your task is CPU intensive, you would drain the battery as well.

Your service should work fine if you do it right.

Another way would be using Handlers, which will abstract much of the thread managements for you.

Edison
  • 5,961
  • 4
  • 23
  • 39
  • Thank you for answer. I check if there are some unread SMSes end give user reminder of that. This is the best way to do that? Is there possibility that android kill my thread? – Mateusz Kaflowski Oct 08 '12 at 21:42
  • 2
    Please refer to http://stackoverflow.com/questions/1973071/broadcastreceiver-sms-received for information on Receiving SMS. You should probably use a receiver instead. – Edison Oct 08 '12 at 22:40
3

Thread.sleep() makes current thread to suspend, which means CPU will be available for other threads or will simply go off. Please also note sleep forces context switch, but you are on the safe side with big sleep interval. So, generally speaking, everything is up to you.

You can use, for example, PowerTutor to make sure your application is properly designed and implemented.

Renat Gilmanov
  • 17,735
  • 5
  • 39
  • 56