Using AsyncTask
It would be something like this
public class TalkToServer extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
/*
* do things before doInBackground() code runs
* such as preparing and showing a Dialog or ProgressBar
*/
}
@Override
protected void onProgressUpdate(Void... values) {
/*
* updating data
* such a Dialog or ProgressBar
*/
}
@Override
protected Void doInBackground(Void... params) {
//do your work here
return null;
}
@Override
protected void onPostExecute(Void result) {
/*
* do something with data here
* display it or send to mainactivity
* close any dialogs/ProgressBars/etc...
*/
}
}
Then you can execute it with
TalkToServer myTask = new MyTask(); // can add params for a constructor if needed
myTask.execute(); // here is where you would pass data to doInBackground()
You may not need onProgressUpdate()
or onPreExecute()
if you aren't using them to show a Dialog
, progress, or other tasks before or during doInBackground()
.
onPreExecute() can be used to initialize and show a ProgressDialog
. Then it could be dismissed in onPostExecute()
After a task finishes
onPostExecute()
will be called. If the class is an inner-class of your Activity
then you can update UI
elements there or call a function to run code once the task finishes. If it is a separate file than the Activity
then you can use an interface
and create a callBack
to the Activity
and run code there once the task finishes.
This answer talks about using an interface for a callback if you need
Make sure any UI
updating is done in any method besides doInBackground()
or sent back to the Activity
in any function besides doInBackground()
. Heavy-lifting such as network operations should be done in doInBackground()
.
Also, be sure to read through the AsyncTask Docs completely. Especially the Threading Rules
How to use AsyncTask correctly in Android
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
public class AsyncExample extends Activity{
private String url="http://www.google.co.in";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new AsyncCaller().execute();
}
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.show();
}
@Override
protected Void doInBackground(Void... params) {
//this method will be running on background thread so don't update UI frome here
//do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
}
}
}
AsyncTask Android example
Ok, you are trying to access the GUI via another thread. This, in the main, is not good practice.
The AsyncTask executes everything in doInBackground()
inside of another thread, which does not have access to the GUI where your views are.
preExecute()
and postExecute()
offer you access to the GUI before and after the heavy lifting occurs in this new thread, and you can even pass the result of the long operation to postExecute()
to then show any results of processing.
See these lines where you are later updating your TextView:
TextView txt = findViewById(R.id.output);
txt.setText("Executed");
Put them in onPostExecute()
.
You will then see your TextView text updated after the doInBackground
completes.
I noticed that your onClick listener does not check to see which View has been selected. I find the easiest way to do this is via switch statements. I have a complete class edited below with all suggestions to save confusion.
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class AsyncTaskActivity extends Activity implements OnClickListener {
Button btn;
AsyncTask<?, ?, ?> runningTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = findViewById(R.id.button1);
// Because we implement OnClickListener, we only
// have to pass "this" (much easier)
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// Detect the view that was "clicked"
switch (view.getId()) {
case R.id.button1:
if (runningTask != null)
runningTask.cancel(true);
runningTask = new LongOperation();
runningTask.execute();
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Cancel running task(s) to avoid memory leaks
if (runningTask != null)
runningTask.cancel(true);
}
private final class LongOperation extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// We were cancelled; stop sleeping!
}
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed"); // txt.setText(result);
// You might want to change "executed" for the returned string
// passed into onPostExecute(), but that is up to you
}
}
}
Android: AsyncTask to make an HTTP GET Request?
Yes you are right, Asynctask is used for short running task such as connection to the network. Also it is used for background task so that you wont block you UI thread or getting exception because you cant do network connection in your UI/Main thread.
example:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet("YOU URLS TO JSON");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
}
Using AsyncTask in Service
Is that a normal practice of using AsyncTask in Service
No. The point of AsyncTask
is to be able to do some work on the main application thread after the background work is completed. Services rarely, if ever, need to do work on the main application thread.
Or is it better to create background thread in another way?
Yes: new Thread()
would be a strong candidate as a straight-up replacement for AsyncTask
. In other cases, some form of thread pool might make sense.
Simple counter using AsyncTask class
onProgressUpdate(Progress...), invoked on the UI thread after a call
to publishProgress(Progress...). The timing of the execution is
undefined. This method is used to display any form of progress in the
user interface while the background computation is still executing.
For instance, it can be used to animate a progress bar or show logs in
a text field.
The timing of the update on your UI thread is not guaranteed so you could see the events come out of order like you describe. You might want to add logic to your progress to just not decrease the value at all and only increase, basically skip the value if it is less than what you saw last time.
using asynctask to speed up android app launch time
I can't just make your code an AsyncTask
but I can give you an example and some help. This is an example of AsyncTask
public class TalkToServer extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@Override
protected String doInBackground(String... params) {
//do your work here
return something;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// do something with data here-display it or send to mainactivity
}
All of your network stuff you will put in doInBackground()
then if you need to update the UI
you did that in the other methods. After finishing the network stuff you can update UI
in onPostExecute()
.
This is how you would call the task
TalkToServer myAsync = new TalkToServer() //can add params if you have a constructor
myAsync.execute() //can pass params here for `doInBackground()` method
If it is an inner class of your MainActivity
then it will have access to member variables of MainActivity
. If its a separate class then you can pass context
to constructor like
TalkToServer myAsync = new TalkToServer(this);
and create a constructor to accept Context
and any other params you want
I strongly suggest going through the docs below and make sure you understand how it works. Maybe the biggest thing to understand when getting started is that doInBackground()
doesn't run on the UI
so you don't want to try and update any Views
here but in the other AsyncTask
methods or by passing data back to the MainActivity
and update there
AsyncTask
Using AsyncTask to read items from a database
onPostExecute(Result) is exactly the place where you should initialize your listview and set adapter. Cause onPostExecute() is running in main UI thread.
Related Topics
Getcolor(Int Id) Deprecated on Android 6.0 Marshmallow (API 23)
Cursorloader Usage Without Contentprovider
How to Change the Text on the Action Bar
Android: Broadcast Receiver for Screen on and Screen Off
How to Get Onclick Event on Webview in Android
Launch Sms Application with an Intent
List of Android Permissions Normal Permissions and Dangerous Permissions in API 23
How to Display Toast in Android
What Is Difference Between Getsupportfragmentmanager() and Getchildfragmentmanager()
How to Draw Interactive Polyline on Route Google Maps V2 Android
How to Record a Video in My Android App
How to Resume Existing Fragment from Backstack
How to Sign Android App With System Signature
Noclassdeffounderror For Code in an Java Library on Android
Error Inflating Class Android.Support.Design.Widget.Navigationview
How Set Maximum Date in Datepicker Dialog in Android