AsyncroTask Basics:
1. AsyncTask provide easy way to use of the UI thread.
2. Perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
3. AsyncTask is designed to be a helper class around Thread and Handler and does not use a generic threading framework.
4. AsyncTasks should ideally be used for short operations (a few seconds at the most.)
5. The AsyncTask class must be loaded on the UI thread.
6. The task instance must be created on the UI thread.
7. execute(Params...) must be invoked on the UI thread.
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;
public class JsonRequestAsycn extends AsyncTask<String, Void, String> {
public AsyncResponse delegate=null;
@Override
protected String doInBackground(String... urls) {
String response = "";
HttpEntity resEntity;
try {
for (String url : urls) {
// Create the client
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
// Execute HTTP Post Request and get response
// Set connection timeout
int timeoutConnection = 15000 ;
HttpConnectionParams.setConnectionTimeout(httpGet.getParams(), timeoutConnection);
// set socket timeout
int timeoutSocket = 15000 ;
HttpConnectionParams.setSoTimeout(httpGet.getParams(), timeoutSocket);
HttpResponse responsePOST = client.execute(httpGet);
resEntity = responsePOST.getEntity();
response=EntityUtils.toString(resEntity);
}
} catch (Exception e) {
return "TimeOut";
// e.printStackTrace();
}
return response;
}
@SuppressLint("DefaultLocale")
@Override
protected void onPostExecute(String result) {
//Toast.makeText(context, "data"+result, Toast.LENGTH_LONG).show();
try{
delegate.processFinish(result);
}
catch(Exception e)
{
Log.d("error hai",""+e);
}
}
@Override
protected void onPreExecute()
{
//pd = ProgressDialog.show(, "","Please wait...");
}
0 comments:
Post a Comment