I am using the AudioRecord object, and within AudioRecord.OnRecordPositionUpdateListener I am implementing AudioRecord.read to write data to a byte buffer, after this I am calling another object's method to process the byte buffer and return it afterwards to write to file, the problem is the object's processing is quite long and seems to be stopping the main thread,which is odd i thought the AudioRecord.OnRecordPositionUpdateListener was Threaded
Unless it explicitly says so, assume nothing is threaded in android. Its all callbacks on the UI thread.
The normal way to do this would be to start up a thread in onCreate or onStart of your app, and have it wait for a message from the main thread. Your implementation of onMarkerRead (or whatever other function you need) would then send a message to that thread. You could create a thread whenever the notification function is called, but keeping the thread around avoids thread creation overhead at the OS level every time you get a notification.
Avoid using AsyncTasks here. They sound like the right solution, but since all app tasks are single threaded they could be held up indefinitely.
Related
I know that threads have a message queue and handlers are able to push runnables or messages to them, but when I profile my android application using Android Studio tools, there is a strange process:
android.os.MessageQueue.nativePollOnce
It uses the CPU more than all the other processes. What is it and how can I reduce the time that the CPU spends on it?
You can find the profiler result below.
Short answer:
The nativePollOnce method is used to "wait" till the next Message becomes available. If the time spent during this call is long, your main (UI) thread has no real work to do and waits for next events to process. There's no need to worry about that.
Explanation:
Because the "main" thread is responsible for drawing UI and handling various events, it's Runnable has a loop which processes all these events.
The loop is managed by a Looper and its job is quite straightforward: it processes all Messages in the MessageQueue.
A Message is added to the queue for example in response to input events, as frame rendering callback or even your own Handler.post calls. Sometimes the main thread has no work to do (that is, no messages in the queue), which may happen e.g. just after finishing rendering single frame (the thread has just drawn one frame and is ready for the next one, just waits for a proper time). Two Java methods in the MessageQueue class are interesting to us: Message next() and boolean enqueueMessage(Message, long). Message next(), as its name suggest, takes and returns the next Message from the queue. If the queue is empty (and there's nothing to return), the method calls native void nativePollOnce(long, int) which blocks until a new message is added. At this point you might ask how does nativePollOnce know when to wake up. That's a very good question. When a Message is added to the queue, the framework calls the enqueueMessage method, which not only inserts the message into the queue, but also calls native static void nativeWake(long), if there's need to wake up the queue. The core magic of nativePollOnce and nativeWake happens in the native (actually, C++) code. Native MessageQueue utilizes a Linux system call named epoll, which allows to monitor a file descriptor for IO events. nativePollOnce calls epoll_wait on a certain file descriptor, whereas nativeWake writes to the descriptor, which is one of the IO operations, epoll_wait waits for. The kernel then takes out the epoll-waiting thread from the waiting state and the thread proceeds with handling the new message. If you're familiar with Java's Object.wait() and Object.notify() methods, you can imagine that nativePollOnce is a rough equivalent for Object.wait() and nativeWake for Object.notify(), except they're implemented completely differently: nativePollOnce uses epoll and Object.wait() uses futex Linux call. It's worth noticing that neither nativePollOnce nor Object.wait() waste CPU cycles, as when a thread enters either method, it becomes disabled for thread scheduling purposes (quoting the javadoc for the Object class). However, some profilers may mistakenly recognize epoll-waiting (or even Object-waiting) threads as running and consuming CPU time, which is incorrect. If those methods actually wasted CPU cycles, all idle apps would use 100% of the CPU, heating and slowing down the device.
Conclusion:
You shouldn't worry about nativePollOnce. It just indicates that processing of all Messages has been finished and the thread waits for the next one. Well, that simply means you don't give too much work to your main thread ;)
I am trying to figure out which threads should do what in Android.
The only thing I have found stated in the official documentation is that camera.open() should be put into its own thread.
What about:
camera.startPreview()
camera.stopPreview()
camera.release()
It doesn't state which thread they need. Must they be run on the main thread (ui thread)? Or am I free to choose?
Why am I trying to figure this out? camera.startPreview() when run on the main thread is causing my app to jitter/lag for a short period of time, this heavily affects my application as it is put inside a viewPager and I do not wish to have the camera to always preview (which would cause no lag, but takes up system resources).
Any ideas?
The documentation for Camera states that the class is not thread safe and should not be called from multiple threads at once (I suppose, unless you are performing your own synchronization).
It says that the callbacks will be delivered to the thread that makes the call to open
From the reference (emphasis mine):
This class is not thread-safe, and is meant for use from one event thread. Most long-running operations (preview, focus, photo capture, etc) happen asynchronously and invoke callbacks as necessary. Callbacks will be invoked on the event thread open(int) was called from. This class's methods must never be called from multiple threads at once.
From the open(int) method reference:
Callbacks from other methods are delivered to the event loop of the thread which called open(). If this thread has no event loop, then callbacks are delivered to the main application event loop. If there is no main application event loop, callbacks are not delivered.
Caution: On some devices, this method may take a long time to complete. It is best to call this method from a worker thread (possibly using AsyncTask) to avoid blocking the main application UI thread.
The thread it needs is the one you use to call open(int).
So to answer your question, yes you are relatively free to choose, but you must remain consistent.
My android app has a long running background service, which I also understand runs in the application's main thread and for that reason, any time consuming or blocking task should be moved to a separate thread.
Now, here is the situation, I don't understand/confused about:
When I bind to the service from an activity, i receive an reference to the service which allows me to invoke service methods from my activity. One of the methods allows me to pass a String object from the activity to the service, which is then added to a BlockingQueue. A separate worker thread which is started in the Service's onCreate method, checks the queue for available data and then performs the required task.
What I want to understand is, if at some point, the queue becomes full and an attempt to the queue blocks, will it affect the main thread the service is running on?
Yes. In this situation, if the queue becomes full, the calling thread will block (in your situation, the main thread). So this is a bad design.
The produced data coming from a field of an Activity doesn't force you to use it on the main thread. I suggest you use some Handler for your producer running on its own thread which will allow you to make the processing (and eventually waiting on the queue) outside of the main thread.
This is also good for communicating with your Service since you can use Handlers to communicate with a Service (see Android Services' guide).
Finally, if applying the produced data can be passed directly to an Handler using either
Handler.post(Runnable) or Handler.send(Message)
I am using the thread for login on Server and I want to stop the Thread as the user press back button, I am using stop() and destroy() method and these methods crashing my application, I think these Methods are depreciated that why I am facing this problem. Please Give me the way to stop thread without using stop() and destroy().
Thread.stop() is deprecated since java 1.1 (~17 years ago...). Java of this method explains the reasons in details. This means that you should never call this method. It is still there for backwards compatibility with code written when I was young.
But what to do if you want to "cancel" the operation done in thread? The answer is that you (developer) should care about this yourself. How? It depends on your application. If for example your thread opens i/o stream you can close the stream. If your thread performs series of operations in loop you should check special flag that indicates that thread should exit and update this flag according to needs of your application (in your case when user presses "back" button.
If you still have problem please try to give more details what does your thread do and you will probably get concrete recommendations how to stop it.
For background thread in android try to use service.
I mean you start a service and put a thread in that service.
If you want to stop that service then pressed back button try "Bound" Service. You will get basic idea here.
http://developer.android.com/guide/components/services.html
Only use a thread if you want to do work repeatedly for a long time. I have never needed to start a thread.
You should look at using an AsyncTask.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
It works by using a Thread from the ThreadPool. AsyncTask's are easy to stop, have a method to override for background tasks and one to override for post task work which is suitable for updating the UI (as long as the task was started by the UI thread).
I am currently developing Android app, it needs download content from internet. I use thread to do that and then call runOnUiThread method to update GUI.
I placed a refresh menu on it, if user tried to refresh the content, the download thread will be created and started. The problem is that how can I control the thread order, I need to accept the latest request's response and abandon previous thread requests if there were some other requests still running because the request parameters may have been changed by user. Currently I was using a threadId to do this thing, when a thread finished, it will check its threadId, if it was the latest recored one, it then takes control and render the response. My question is that is there any other proper better solution for this?
Do I need to stop threads when user exit the app? I remember that some book said that do not try stop thread manually and wait itself finish is a good practice, is that true? Should I stop them by calling "stop" or "interrupt" method?
I read some documents around threading in Android and found the class HandlerThread, what is it? In what kind of situation I need to use it?
Rather than starting a new thread for every refresh action I would create a single thread for all the background download work that loops and downloads content as lined up in a queue. That ensures that you don't download content concurrently and also saves resources.
In the GUI you simply queue a refresh request whenever the user prompts you to and can abort a running download by calling HttpRequestBase.abort on the http method instance. The background thread should receive and catch a SocketException and move on to the next queued request.
To end the background thread you just have to end its loop. You can use the Looper and Handler classes to help you with all of the above, the HandlerThread class you mentioned is simply a handy class to create a thread that has a Looper.
The problem with interrupting a thread is that it won't break you out of a blocking I/O request and handling an InterruptException correctly can be complicated. So depending on the situation I would say yes, it is better practice to end the thread by returning from its run method.
i discover this week AsyncTask, and i replace Thread by AsyncTask in some place in my program,
You have doc & sample here, really easy to use :
http://developer.android.com/reference/android/os/AsyncTask.html
when i was using thread GUI was lock, and now it's not locked.
And it's possible to cancel a AsyncTask (but i never try)
You can use an IntentService to start your background operations, the service will operate as "work queue processor" and will execute your calls in order.