AsyncTask is an abstract Android class which helps the Android applications to handle the Main UI thread in efficient way. AsyncTask class allows us to perform long lasting tasks/background operations and show the result on the UI thread without affecting the main thread.
/*....calling to AsyncTask........*/
new JSONTask().execute(uniqueID, url, username, password);
/*.... AsyncTask Class........*/
public class JSONTask extends AsyncTask<String, String, String>{
private String TAG = "AsyncTask : ";
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
String username = params[2];
String password = params[3];
String base64DeviceID = params[0];
try {
URL url = new URL(params[1]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setRequestProperty("token", base64DeviceID);
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username", username)
.appendQueryParameter("firebase_token", firebase_token)
.appendQueryParameter("password", password)
.appendQueryParameter("user_type", "customer");
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
StringBuilder response = new StringBuilder();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream()),8192);
String strLine = null;
while ((strLine = input.readLine()) != null)
{
response.append(strLine);
}
input.close();
}
return response.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String finalResponse) {
super.onPostExecute(finalResponse);
JSONObject parentObject = null;
progressDialog.dismiss();
try {
if (finalResponse!=null) {
parentObject = new JSONObject(finalResponse);
}else{
Toast.makeText(Login.this, "No response", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Comments
Post a Comment