When you need to either do a lot of processing, access the SQLite database, or communicate with the internet you should run it in another thread. Otherwise, the Android user interface will appear frozen to the user.
Here's how you can easily add threading to your Android app:
First we have to declare a new class inside our Activity:
protected class ProcessingTask extends AsyncTask<String, Void, String>{
The String, Void, and String classes indicate how the next two functions behave. Ignore them for now.
We need to declare two functions within it:
any number of String parameters and returns a String to onPostExecute.
The first line of code, with AsyncTask<String,Void,String>
specifies which types of objects the doInBackground and onPostExecute should handle.
The Void is for an unused function in this example. You should ignore it until you are comfortable with AsyncTask.
To use this new task, you instantiate it and execute it in the main UI thread like so:
When the task is executed, it will spawn a new thread and do the processing work there.
Using tasks is vital to creating a good user experience on Android apps.
Here's how you can easily add threading to your Android app:
First we have to declare a new class inside our Activity:
protected class ProcessingTask extends AsyncTask<String, Void, String>{
The String, Void, and String classes indicate how the next two functions behave. Ignore them for now.
We need to declare two functions within it:
@Override
protected String doInBackground(String... params ) {
//Do something with the parameters, then return a String
return "Return Object";
}
@Override
protected void onPostExecute( Stringresult ) {
//Do something with the result object.As you can see here, the doInBackground function takes
}
any number of String parameters and returns a String to onPostExecute.
The first line of code, with AsyncTask<String,Void,String>
specifies which types of objects the doInBackground and onPostExecute should handle.
The Void is for an unused function in this example. You should ignore it until you are comfortable with AsyncTask.
To use this new task, you instantiate it and execute it in the main UI thread like so:
ProcessingTask task = new ProcessingTask();
task.execute("Testing Parameters", "You can send more than 1!");
When the task is executed, it will spawn a new thread and do the processing work there.
Using tasks is vital to creating a good user experience on Android apps.