After Android-Studio
it warned me that there is too much load to the main thread.
Skipped 113 frames: the application may be doing too much work on its main thread
I have created a runnable to launch a thread with some processes:
new Thread(new Runnable() {
@Override
public void run() {
UpdateUI(); //Actualiza datos de la Interfaz de usuario
}
}
But it returns the error:
Only the original thread that created a view hierarchy can touch its views.
I've searched SO and you can launch a thread
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
//Cambiar controles
}
});
But since I have to do a lot of checks or else a thread is executed at the same time, it returns the main thread overload. I even notice that the side menu slows down when it closes.
How do you make a thread but be able to access interface elements in order to modify their data or state?
To fix the error:
You can resort to
runOnUIThread
orAsyncTask
depending on the task to be performed, if it requires a lot of process directly toAsyncTask
runOnUiThread to run a thread with access to interface elements:
AsyncTask
To execute a task that consumes a lot, and keep the user informed of the process and at the end refresh the UI:
doInBackground
homeworkThe following allow you to interact with the UI elements
onProgressUpdate
to report your progressonPostExecute
at the end refresh the UI.Example of an AsyncTask:
Some advices
I had a similar problem and solved it as follows in this example in the event handler code: