Learn Android — Connect to Internet — 1

The world’s most popular mobile OS — from phones and watches to cars and TVs.

Akshansh Dhing
Parsed Inc.
5 min readJun 30, 2018

--

Welcome to the Learn Android series. Here I explain you the why’s of the Android programming world instead of just the how’s to help you understand the core of Android programming. I’ll share with you explanations and code snippets on how to implement the most basic things in Android.

In the previous article, we learned about adding visual polish to our application by adding custom views like Toolbar and Menus. We’ll learn more about it as we proceed. But in this article, we’ll learn about how we can connect our application to the internet.

Previous Article →

Why do we need to learn about connecting our application to the internet? Because it is from the internet that we can connect to the millions of users worldwide and respond back in real-time. We load the data from distant servers into our application from the internet.

First of all, to connect to the internet, we need to add permissions to our application to tell the Android OS that we will be using the internet. These permissions are added in the Manifest.xml file.

What is the manifest file and what does it contain?
Manifest contains meta information (data about the data). These includes the information about packaged files. It contains —

  1. App’s Package Name — which was generated when we entered the required details.
  2. Components of the application—that is, information about the activities, intent-filters, services, broadcast receivers, and more.
  3. Permissions — that our application needs in order to access the protected parts of the system and other applications. It requires developers to request for access and users to granting access to the parts of the Android system.
  4. Hardware and Software features of the application — which effects which devices can download our app. These features includes screen sizes, etc.

Most of the Android apps use HTTP client to send the data over the network. By default, Android comes bundled with the HttpURLConnection class. But there are many open-source libraries, which provide better performance than the above class and those can be found by simple Google search for Android Networking libraries. For networking, we need to introduce a new concept —

Multi — Threading.

Threading refers to the process of running multiple threads simultaneously or parallelly. Threads are lightweight sub-processes that share a common memory area. These allow quick switching between them and use up less memory than implementing complete new processes.

The main advantage is that it doesn’t block whatever operation a user is performing. This allows for a seamless user experience. And since we perform more than one operation at a time, it saves time for the user and the application. So why threading for Android applications? Because —

Network operations should always be performed on a separate thread.

So we can avoid creating an unresponsive UI, which makes the app feel buggy. We must perform Network Operations on a different thread or the Android OS throws a NetworkOnMainThreadException. The main thread by default is the UI thread where the basic operations are performed.

To perform Network operations, there is an in-built class called the AsyncTask which is used to run the network operations on a background thread. We create and implement a subclass of the AsyncTask. Let’s check out the skeleton of how the subclass will look like —

private class MyAsyncTask extends AsyncTask<Params, Progress, Result> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected Result doInBackground(Params... params) {
return null;
}

@Override
protected void onPostExecute(Result result) {
super.onPostExecute(result);
}
}

The AsyncTask class takes in 3 parameters — Params, Progress, and Result. All of the parameters are non-primitive in nature. If we do not want to pass any parameter we can pass the “Void” data type to indicate null values.

Furthermore, we must override the doInBackground() method adond implement all the network operation code inside this method. The other two methods — onPreExecute() and onPostExecute() can be implemented when needed.

As the names suggest, onPreExecute() method is carried out before the background operation is executed and onPostExecute() after the background operation is executed. Most of the times, these methods are used to initialize, set and update storage and progress variables.

In the doInBackground() method, we see a different syntax for the parameter with data type, 3 dots and then variable name. The three dots indicate that we can pass in any number of parameters without actually defining the number previously. These are stored in an array and we can access those using the index number of the arrays. These help us in case when we need to pass in more than one URL for example.

Also, before making the network operation, we need to check if the device is connected to the internet. This is why we included the Access Network State permission in the Manifest file. We have in-built classes to check the network state too. Let’s see how can we check for the connectivity —

ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();if (networkInfo != null && networkInfo.isConnected()) {
//Perform the network operations since it is connected. Call the created AsyncTask and perform execute operation.
} else {
//We do not have network connectivity, implement notifying the users and updating progress variables.
}

This way we can easily connect to the internet. We’ll learn more about how to pull data from the internet and explore some even better libraries — open source and in-built — compared to AsyncTask and also learn how to optimize network request in the following tutorials.

Next up →

Stay tuned for regular updates. Follow me and Parsed Inc. to never miss another one!

Also, let’s become friends on LinkedIn, GitHub, Twitter and Facebook!

To learn more about me and my work, visit my website!

Follow ParsedInc. on Facebook, LinkedIn, and Instagram!

If you enjoyed this article, feel free to 👏👏👏 a few times and share with a friend to help it reach someone who needs to read it. Thanks!

--

--