public class LoginTask extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
//TODO: Before process async task (show progress bar, loader, fade..)
}
@Override
protected Boolean doInBackground(String... params) {
//Set username and password
this.username = params[0];
this.password = params[1];
try {
//Setup URL connection
URL url = new URL("www.myurl.com" + "/connect""");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
//Set Basic Authentication
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
//Proceed in function of status code response
int status = connection.getResponseCode();
switch (status) {
case 200:
case 201:
//TODO: process response server (get token)
// Return true in case of successfull login
// Return false otherwise
case 400:
}
} catch (java.net.MalformedURLException e) {
Log.w(TAG, "Exception while constructing URL" + e.getMessage());
} catch (IOException e) {
Log.w(TAG, "Exception occured while logging in: " + e.getMessage());
} catch (JSONException e) {
Log.w(TAG, "Exception occured while logging in: " + e.getMessage());
}
return false;
}
@Override
protected void onPostExecute(Boolean success) {
//TODO: After async task finished based on task success
//(Change activity, hide progressbar...)
}
}
// Call async LoginTask
public class LoginClass{
public void login(String username, String password){
loginTask=new LoginTask();
loginTask.execute(username, password);
}
}
Basic async login task
Pros:
+ Keep the main thread in charge of the UI, and delegate authentication to another thread.
Pros:
+ Keep the main thread in charge of the UI, and delegate authentication to another thread.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.