Android Programming 101 : Basics

ibrahimcanerdogan
14 min readNov 23, 2022

--

Photo by Alexander London on Unsplash

Android Architecture

The working structure of the Android operating system is evaluated in different layers.

Core services such as Kernel Layer, operating system, security, hardware drivers are managed.

The Hardware Abstraction Layer (HAL) layer is the abstract structures that have the necessary features for the upper layers to use. It provides access to the Kernel layer to meet the hardware needs. Thus, more secure connections are made with the Kernel layer.

Then there is “Native C/C++ Libraries” as a layer. However, this layer “Android Runtime” is used in applications developed after Android 5.0.

The Java API Framework layer is the layer that is directly accessed and used during application development. All Android libraries are available to us. Content Providers includes 3 main groups as View System and Manager.

  • Content Providers: This is the section that manages application data and content.
  • View System: It is the part that enables the creation and management of images.
  • Manager: Managers are involved in all operations related to the system. Activity Manager, LocationManager, Resources etc. administrators are located in the Java API Framework layer.

The System Apps layer is the layer where the applications reside. In this layer, there are applications that come ready-made by Android and that we have developed. Calender, Email etc. transactions come to us.

Photo by Clark Tibbs on Unsplash

Android Project Directory

The Android project is placed on 2 basic directories, “app” and “Gradle Scripts”.

Gradle Scripts provides the management of libraries in the Android project and the compilation of the project. The “build.gradle(Project: …)” file marked as Project contains the adjustments made for the entire project. The “build.gradle(Module: app)” file represents the project we created.

  • compileSdkVersion: Specifies the API level at which the project will be compiled.
  • applicationId: It is the domain address that makes the project unique in Google Play.
  • versionCode: The number that should be incremented continuously when the application is published. Project with the same number cannot be published.
  • versionName: It is the version number where the project will be seen by Google. It is given as “1.0.0”.

The AndroidManifest.xml file is located in app>manifest. The project is introduced to the operating system through this “xml”.

Resources, that is, “res” package is included in the app package. Res contains all files related to interface and user interactions.

  • drawable: It is the file where the images are kept. It can keep files in XML or PNG format. It is recommended to keep XML files.
  • layout: It is the structure that represents all screens and visuals. The screen or a part of this screen is kept in this file as XML.
  • mipmap: It is used to keep the dimensions of an image in different resolutions (hdpi, mdpi, xdpi etc.). Keeping files in vector format will prevent different uses for different resolutions, but if we are using photos, it is not possible to use vectors.
  • values: strings.xml, colors.xml and styles.xml files are included in this file. Styles, string parameters or color codes can be kept for the application.
Photo by Hal Gatewood on Unsplash

Android Design

Designs on Android are carried out through XML files. Although this process begins to change with Jetpack Compose, the use of XML will not leave its place to this change for a long time.

On the palette on XML, there are different UI components as “Text”, “Button”, “Widgets”, “Layouts”, “Containers”, “Google” and “Legacy” categories.

  • Text: There are components that will receive various inputs from the user.
  • Buttons: In this menu, there are clickable components in different formats.
  • Widgets: It is a palette component that includes features such as visual, video or website “view” components in different structures or “bar” options that will appear on the screen.
  • Layouts: This is the part where we can choose the structure where the user appears and all the palette components will be located. Here, there are views with various sequences according to various needs.
  • Containers: It is the part that contains widgets with other types of features. There are components that make the application look more professional and useful.
  • Google: This section contains advertising or map components offered by Google.
  • Legacy: Components that are no longer recommended for use and that are considered “obsolete” are included in this section.

Multi-Language Support

In an opened .xml file, we click on the “Edit Translations…” option from the “Default(en-us)” option in the top menu. Thanks to the “Add Locale” button on the page that opens, the texts written in strings.xml can be changed according to the desired language.

This usage is automatically assigned according to the language determined by the operating system used by the application user on their device.

Drawable

Images are drawn with XML files in the <vector> tag to give healthier results despite the resolution change. Not every image has to be added with a vector. There are visuals to be used in the project.

When the drawable package of “.svg” extension files is right clicked, “Vector Asset” option can be added to android project in vector tag in “xml” file format. Such files are advantageous especially in terms of the size of the project compared to the use of other images with .png extension.

Photo by Vladimir Proskurovskiy on Unsplash

Android Working Structure

The Android operating system performs the control of all the applications it contains. It controls each application separately in terms of Context, that is, resources.

Contexts are structures that continue to run on their own and can terminate. Context structure is divided into 3 main parts.

  • ApplicationContext: It is the structure that is valid throughout the application. For some features, this context structure should be used.
  • Service: It is valid for object specific. It is used in background processes.
  • Activity: It is valid for object specific. It is used in visual processing.

Activity Lifecycle

The Activity object consists of independent parts. These parts have independent life cycles. It is controlled by the life cycle.

We see, in turn, the steps that an “Activity” object will run when called.

1. constructor: In this step, the object is extracted to memory.
2. onCreate: This method is called when the screen is created. The images in the object are extracted to memory.
3. onStart
4. onResume

5. onPause: When this method runs, it means that the application is in the background. It continues to work in onResume when the application is returned after waiting in the background. Since the time here is indefinite For example, if the data is drawn in the constructor, onCreate or onStart in an application that draws instant data, the previous data will be displayed on the screen until the expected time.
6. onStop: Applications that wait as onPause for a long time will switch to onStop phase. At this stage when the user returns to the application, the onStart function is first called after onRestart. The functions in the onStop phase are in the operating system.
7. onDestroy: All objects and images of your activity are dropped from memory.

The images on the screen will not be shown to the user until (including) the onResume function. Long-term operations in these functions make it longer for the user to see the screen. After onResume, the user starts to see the screen.

Fragment

With Fragment, it is possible to show more than one screen on an Activtiy. They cannot survive on their own like a Context structure, so they need an Activity. It is managed by FragmentManager on Activity.

More than one fragment can be opened at the same time on the activity. In this structure, which is called multi-fragment, an example can be given as a list on the right side of the tablet screen and detailed operations on the left side. Or, while the top bar is a fragment, which is desired to be seen constantly on phones, a structure can be established in which the pages are displayed at the bottom.

Fragments have their own lifecycle. Since a Fragment is on the Activity, it can be affected by the Activity lifecycle, but the Activity object is not affected by the Fragment lifecycle.

Photo by Marga Santoso on Unsplash

User Interactions

Android is a structure where user interaction is very detailed and important. User Interface, called UI, is used to interact with the user. When we look at the UI in terms of hardware, it appears as a screen. The equivalent of this term for a developer is actually “view”.

In Android, “view” is created with .xml extension files. Components such as “TextView”, “Button” are placed on this created UI. In this way, a communication is provided with the user. Apart from that, the user can show messages such as “SnackBar”, “Toast” to report a situation or do much more with the tools provided.

Important and “why?” when providing interactions on Android. Many features that we will learn to use will be explained at this stage.

  • The design made on XML is included in a life on the Activity. From Activity to this view

window.decorView.rootView

form available.

Toast & SnackBar

With “Toast” and “Snackbar”, the desired information or texts for different purposes are displayed to the user at any time.

 Toast.makeText(this, "Example Text", Toast.LENGTH_LONG).show()

ToggleButton & Switch

“ToggleButton” and “Switch” are used to manage the user’s on-off states. These created elements are accessed via setOnCheckedChangeListener to trigger the changes.

The called setOnCheckedChangeListener function receives a CompoundButton.OnCheckedChangeListener from the developer. It can be used as an example as follows. Button-related features can be accessed through CompoundButton. The Boolean value is used to reach the instantaneous value of the button on the screen.

switch.setOnCheckedChangeListener(func)

var func = CompoundButton.OnCheckedChangeListener { b: CompoundButton, x: Boolean ->
// bla bla bla
}

Checkbox & RadioButton

“Checkox” and “RadioButton” are used in processes such as marking and giving approval on the screen. Generally, the use of Checkbox is preferred in cases where multiple selections will be made. RadioButton is used when it is desired to select one operation among many options.

Only one of the RadioButton components included in the RadioGroup can be selected.

ImageView & WebView

The ImageView component is placed in the .xml file when an image is desired to be used on the screen. You can place image on Activity on this ImageView in various ways.

The ScaleType property is an important property because it specifies many types of placement, such as placing the image in the center of the screen, covering the entire area, starting above.

WebView allows any address to be displayed to the user on the application. WebView object can be redirected to the desired site with .loadUrl.

In order to use WebView, INTERNET access permission must be granted in AndroidManifest.xml. Also, in order to login to sites with “http” domain instead of “https”, “android:usesCleartextTraffic=’true’” must be added in the <application ….> tag.

AlertDialog

Sometimes short-term messages may not be enough to inform the user. For this, we can show messages that we can be sure that the user sees, that can be approved, that is, that contain buttons. Thanks to AlertDialog, this type of interaction can be made to users.

To create an AlertDialog, an AlertDialog.Builder object must be created. Through this object, the message, title or button names and activities to be displayed to the user can be given. The object can then be displayed to the user.

var alert = AlertDialog.Builder(this)
alert.setTitle("Uyarı")
alert.setMessage("Kullanıcı Mesajı")

alert.setPositiveButton("OK", DialogInterface.OnClickListener { dInterface, i ->
Toast.makeText(this, "Press OK", Toast.LENGTH_SHORT).show()
})
alert.setNegativeButton("Cancel", null)

val completedAlert = alert.create()

completedAlert.show()

Intent

It is possible to switch between activities with intent. During this transition, information can be moved or tracked.

With the use of “startActivity”, only a transition can be made between activities. When going back on the screen, the intent is directed with “startActivityForResult” to perform a capture. ActivityOnResult is used to catch this redirect.

val intent = Intent(this, MainActivity2::class.java)
//startActivity(intent)
startActivityForResult(intent, 0)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Toast.makeText(this, "Geri Geldi!", Toast.LENGTH_SHORT).show()
}

If data will be sent to other Activity;

val intent = Intent(this, MainActivity2::class.java)
intent.putExtra("key","Data Value")
startActivity(intent)

If data will be received in the sent Activity;

val intentData = intent.getStringExtra("key")

Data can be moved with Intent, but it does not provide the transport of large data such as images. Apart from that, overloading the data on the intent slows down the screen transitions.

So, when we communicate between two intents, how can data be retrieved when returning from the intended intent? For this, we actually create an intent like a normal intent, but we don’t just give a class where the redirect is. In that;

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)

if(requestCode == 0 && resultCode == Activity.RESULT_OK) {
var str = data?.getStringExtra("receiveValue")
Toast.makeText(this, str, Toast.LENGTH_SHORT).show()
}
}
var i = Intent()
i.putExtra("receiveValue", "Back Information")
setResultActivity(Activity.RESULT_OK, i)
finish()

Handler

Handlers are flexible structures that work in the background and enable us to manage the events that we want to be repeated at certain intervals. When we perform long operations that will be displayed on the screen as a result, the “Handler” structure is preferred.

The Handler object can be called at any time or after a certain millisecond as follows.

Handler().post {
Toast.makeText(this, "Handler Post", Toast.LENGTH_SHORT).show()
}
Handler().postDelayed ({
Toast.makeText(this, "Handler Post", Toast.LENGTH_SHORT).show()
}, 6000)

Splash

The “Splash” structure, which is frequently encountered in modern Android applications, can be explained as presenting an animation, image or text to the user for a short time at the start of the application. On this screen, the company or person that publishes the application usually shows its logo to the user.

Splash can actually be used to keep the user from waiting for a process that may take a long time at opening, apart from the purpose of advertising. This will save time during the execution of transactions.

The splash structure can be used in more than one way. For example, it can be defined as a “layout” on AndroidManifest.xml.

Below is a basic creation using Handler. A design was made with “clSplash” in the .xml file of the “Activity” class, which was first shown to the user. This view, which is visible as deafult, is disabled under the onCreate method.

Handler().postDelayed({
clSplash.visibility = View.GONE
}, 2500)

Popup

Users can see the notifications at the top of the application. For this, it is necessary to create a PopupWindow object. Thanks to this object, various properties related to the notification to be displayed can be given.

For example, a basic popup can be created as follows. For this, a “Layout” must be created over the .xml file beforehand. This file contains components such as button and textView, allowing the user to see it.

val inflater = getSystemService(Activity.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val v = inflater.inflate(R.layout.popup, null)
val popup = PopupWindow(
v,
windowManager.defaultDisplay.width,
ViewGroup.LayoutParams.WRAP_CONTENT)

popup.showAtLocation(v, Gravity.TOP, 0, 0)
v.textViewHeader.text = "Header"
v.textViewText.text = "Text"

v.buttonCancel.setOnClickListener {
Toast.makeText(this, "Click Button", Toast.LENGTH_SHORT).show()
popup.dismiss()
}

AsyncTask

AsyncTask is used if the operations we will do in the application take a long time. These processes may need to be done in the background or may be required to run in different options. The whole purpose is to ensure that the operations that the user sees on the screen are actually performed faster and more efficiently.

AsyncTask operations as “Deprecated” are now an old technology. The fact that it is no longer used in development processes will ensure that the developed application is more up-to-date.

“Kotlin Coroutines” is used instead of this technology. In the new system, it has become more manageable than asynchronous operation. In this way, the developer is given the opportunity to work on the Thread as you wish, if you wish.

Since Kotlin Coroutines is a bit more advanced, it is necessary to use different resources, especially official documents, to learn it. It should be known that the studies on this subject give the application an extremely high performance.

Permissions

On Android, most permissions can be requested from the user. Since transactions such as internet use are not considered “dangerous”, they are dependent on the user’s knowledge. However, operations such as gallery access, camera access or reading contacts must be obtained with a confirmation from the user.

All permissions are given with <uses-permission> tag in AndroidManifest.xml. In this way, it is stated that only the application needs this feature. The use of this feature of the application directly in non-dangerous permissions has been opened.

For example, if we want to access the camera, we can ask this on the “Main Activity” without the user logging into the application, or we can ask this when the user wants to use the camera within the application.

When the permissions are not obtained in accordance with the desired conditions, when the application wants to be uploaded to markets such as Google Play, it receives a response as rejection.

Photo by Jo Szczepanska on Unsplash

Material Design

Material Design is a component library developed by Android as a standard and display guide in applications. By using the tools in this library, the applications are brought to a modern and different dimension in appearance.
You can find detailed information about the library HERE.

FloatingActionButton

FloatingActionButton (Fab) is the button used to do an additional job in the Activity. It appears as a round button in the lower right corner of the screens that does not touch the screen edges.

It is defined as a function that is desired to be highlighted. For example, the “Create” button in the Gmail application is a Fab example and writing mail is highlighted.

Fab has no difference in function from other buttons. Since it is a Material Design tool, it has a 3-dimensional appearance.

Text Input Layout

This tool corresponds to the “Plain Text” tool, except for Material Design. However, it gives a more professional impression in terms of appearance. There is a floating label (Floating Label) structure in the TextInputLayout.

The property value given as “Hint” appears as a title when the user clicks on it. Apart from that, it simply allows us to perform an error check. You can show the errors or warnings you want for the input to the user under the layout.

ToolBar

It is the structure used as a fixed on the upper part of the application throughout or in a part of it. ActionBar is a new fulfilled component. The ToolBar has a better appearance and a structure that is easier to develop.

The ToolBar is located in the AppBarLayout. It allows us to define functions in the form of animations for the elements in the AppBarLayout.

“?attr/actionBarSize” şeklinde bir kullanımla ToolBar özelliğini Android tarafından belirlenen standart ölçüde verebilirsiniz.

CardView

CardView is used for a regular and easier combination of components such as Visual, Button and Text to be used together. Making many features such as shading and oval feature with a single line of code provides an advantage for the development of the project.

It is frequently used as a list object, especially in creating iterative components on the RecyclerView image.

BottomNavigationView

BottomNavigationView, which we see frequently in almost all applications today, provides the implementation of fixed menus at the bottom of the application. TabView gives us this feature when Material Design is not used.

Many UI elements like this are included in the Material Design library with its more modern and easy-to-use.

Thank you

IBRAHIM CAN ERDOGAN

--

--

ibrahimcanerdogan
ibrahimcanerdogan

Written by ibrahimcanerdogan

Hi, My name is Ibrahim, I am developing ebebek android app within Ebebek. I publish various articles in the field of programming and self-improvement.

No responses yet