Question

I am making an android app in which i need to monitor the sound levels from the mic. My logic works if I'm taking the sound level value every 50-100ms. The way I see it...to monitor these values I have two options

1) A while loop

while(true){
  //get sound levels and do my logic
}

2) A handler that reposts its self every let's say 50 ms to check the sound levels

final Handler handler3=new Handler();
handler3.postDelayed(new Runnable(){
    @Override
    public void run() {
        //get sound levels and do my logic
        handler.postDelayed(this, 50);
    }                   
}, 50);

It seems cheaper (in battery and cpu power) to me to use the handler solution. But I don't know much about the inner workings of java and android and how expensive it is to post a handler so I just wanted to make sure i do the right thing in the end. Also if there is a cheaper solution i'd be glad to hear it

Était-ce utile?

La solution

The loop is WAY cheaper than handler, but you have to implement it in a separate thread with appropriate sleep calls otherwise it will block your app main thread, making your app unresponsive. Additinally it requires synchronisation to access shared objects.

The Handler.postDelayed() function takes some CPU, but it has a benefit that no thread synchronisation is necessary if you use it.

Autres conseils

I think that depends on what you want to do exactly. Is there anything else you would like to do during the loop? When the loop runs your app cannot do anything else. It just loops round and round.

You might want to have some sort of button which can be pressed to stop listening. You might want to have some graph which shows the noise or audio level.

In order to keep the UI running smoothly all the time, I would recommend to go for the handler-approach. Your UI thread will then never be bothered by what's going on with the audio processing...

I'm not a so deep expert to be able to judge how much cheaper a while() loop is, but I think it's definitely cheaper - but you have above mentioned drawback. From programming point-of-view, it's also more complicated to work with handlers as you do multi-threading. You do not have multiple threads with the while() approach.

However, I would recommend to do the audio processing in a thread separate from the UI thread.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top