1) To run a task that runs in background, define a class that extends AsyncTask class
2) It takes 3 template arguments,
Type of object passed to the class, type of method that shows progress, type of return value from class
3) The part of the code that should be executed in background is defined in doInBackground method. The code under this method cannot communicate with the UI. Ie, it can change the view text etc. The part of the code to be executed after the background taskl is over may be defined under onPostExecute method.
public class MainActivity extends AppCompatActivity {
//Running a task in background thread
//AsyncTask is used when we want to run this part of the code in a different thread from main thread!
//AsyncTask<Dtype sent to DownloadTask class, Dtype of method that shows progress, Dtype returned by DownloadTask class
public class DownloadTask extends AsyncTask<String, Void, String> {
//this method takes a variable length argument. Ie, can pass arbitary no of args
@Override
protected String doInBackground(String... urls) {
//CODE THAT WILL WORK WITH URLS
return result;
}
}
// this method is executed after the background task is done. (not mandatory to implement)
@override
protected void onPostExecute(String result){
super.onPostExecute(result)
... //do something with result in main thread
}
}
Execution
NOTE : The object.execute( ... ) method can be called only once per instance
DownloadTask task = new DownloadTask();
try {
//mandatory to surround with try and catch when calling async tasl!
String result = task.execute("https://www.ecowebhosting.co.uk").get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
1) Add permission in AndroidManifest.xml
<!--add permission to use internet--> <uses-permission android:name="android.permission.INTERNET" /> <application ... />Incase we forget some permission, the build log will show up with permission denied message
2) Downloading the page source
protected String doInBackground(String... urls) {
Log.i("URLs" , urls[0]);
Log.i("URLs" , urls[1]);
String result = "";
URL url;
HttpURLConnection urlConnection = null;
//Mandatory try catch
try {
//url
url = new URL(urls[0]);
//create connection with url
urlConnection = (HttpURLConnection)url.openConnection();
//get input stream from url connection
InputStream in = urlConnection.getInputStream();
//we need a reader to read input stream,
InputStreamReader reader = new InputStreamReader(in);
//reads one char at a time
int data = reader.read();
while(data!=-1){
char current = (char)data;
result += current;
data = reader.read();
}
} catch (java.io.IOException e) {
e.printStackTrace();
}
return result;
}
}