Sitemap

Android Architecture and Application Elements

8 min readAug 4, 2022

--

In this story , I will tell you Android basics. I will share the information that I have gathered from many places here.

Android Operating System Architecture

At the bottom of the architecture is the linux kernel. This is the most basic layer. Memory management, security, process and network management operations are performed. The Hardware Abstraction Layer contains the interfaces of the hardware libraries to be provided to the upper layers. In other words, when you use APIs such as camera, bluetooth using android SDK, hardware library is found with the help of this layer and necessary functions are called. In an upper layer, there are different local libraries written in C/C++, Dalvik Virtual Machine or Android Runtime (ART). These libraries include SQLite, Graphics, Media etc.. Application Framework contains Android SDK elements. While developing an application, using SDK elements, the device’s hardware can be accessed, location information can be obtained, database operations can be performed, and services can be written to run in the background. Let’s go to the top layer -> Applications… Web browser, phone book, settings are in this layer.

Press enter or click to view image in full size

Dalvik Virtual Machine (Most android developers don’t know his name is Dalvik . Omg.. I also just learned :))

Press enter or click to view image in full size
Dalvik, Iceland

Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.

The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile devices. It optimizes the virtual machine for memory, battery life and performance. Java codes are compiled into (.class) bytecode first, as in the JVM. Dalvik VM interprets this compiled code and converts it into executable files (.dex — dalvik executable) suitable for your phone.

Android Runtime (ART)

It does the same job as the Dalvik VM, they are different libraries. It was developed after Dalvik VM and is used instead of Dalvik VM on Android 5.0 (API 21) and later devices. Compared to Dalvik VM, ART is better in many areas such as error reporting, compilation.

Basic Application Android Elements

Activity

Represents a single screen in the application. All screens derive from an Activity class. (AppCompatActivity or Activity). The first screen in the application is Default Activity.

Fragment

An Activity element that represents a certain part or all of a screen. With the launch of tablets, we got bigger screens and added space in apps. In order to use these areas more dynamically and flexibly, Google developed the Fragment Api.

Press enter or click to view image in full size

You can put two or more fragment in one activity. Fragments are pieces of screen that can be used over and over again. They allow us to get rid of unnecessary code duplication.

Intent

Intent represents messages sent between core android components. Thanks to this message, we can trigger an activity to start, call a service or notify all applications on the phone. It is divided into two as Explicit Intent and Implicit Intent.

Press enter or click to view image in full size

An explicit intent is highly specific, where you know the exact activity to be launched, often a screen in your own app.

Get Çağla Çorak’s stories in your inbox

Join Medium for free to get updates from this writer.

An implicit intent is a bit more abstract, where you tell the system the type of action, such as opening a link, composing an email, or making a phone call, and the system is responsible for figuring out how to fulfill the request. You’ve probably seen both kinds of intents in action without knowing it. Generally, when showing an activity in your own app, you use an explicit intent.

It is easiest to see from this photo.

Press enter or click to view image in full size

Service

Services are components that run in the background of your application and do not have any interface. Once a service starts running, it continues to run no matter what application is open. Does not require user interaction.

Press enter or click to view image in full size
Service Lifecycle in Android

Broadcast Receivers

It allows us to be aware of events and react when they happen. It can also be used to send news from the application to the system-wide or other parts of the application.Unlike activities, android BroadcastReceiver doesn’t contain any user interface. Broadcast receiver is generally implemented to delegate the tasks to services depending on the type of intent data that’s received. Following are some of the important system wide generated intents.

  1. android.intent.action.BATTERY_LOW : Indicates low battery condition on the device.
  2. android.intent.action.BOOT_COMPLETED : This is broadcast once, after the system has finished booting
  3. android.intent.action.CALL : To perform a call to someone specified by the data
  4. android.intent.action.DATE_CHANGED : The date has changed
  5. android.intent.action.REBOOT : Have the device reboot
  6. android.net.conn.CONNECTIVITY_CHANGE : The mobile network or wifi connection is changed(or reset)

To set up a Broadcast Receiver in android application we need to do the following two things.

  1. Creating a BroadcastReceiver
  2. Registering a BroadcastReceiver

— Creating a BroadcastReceiver

Let’s quickly implement a custom BroadcastReceiver as shown below.

public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {

Toast.makeText(context, "Action: " + intent.getAction(), Toast.LENGTH_SHORT).show();
}
}

— Registering the BroadcastReceiver in android app

A BroadcastReceiver can be registered in two ways.

  1. By defining it in the AndroidManifest.xml file as shown below.
<receiver android:name=".ConnectionReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>

2. By defining it programmatically.

IntentFilter filter = new IntentFilter();
intentFilter.addAction(getPackageName() + "android.net.conn.CONNECTIVITY_CHANGE");

MyReceiver myReceiver = new MyReceiver();
registerReceiver(myReceiver, filter);

To unregister a broadcast receiver in onStop() or onPause() of the activity the following snippet can be used.

@Override
protected void onPause() {
unregisterReceiver(myReceiver);
super.onPause();
}

Note: To make the broadcast receiver unavailable to external applications, add the attribute android:exported=false in the manifest. When we send a broadcast, it is possible for the external applications too to receive them. This can be prevented by specifying this limitation.

Press enter or click to view image in full size

Content Providers

Content Provsders are interfaces for data sharing. When you create a database in your application, it is only accessible to your application. No other app can access it. But some information must be shared system-wide. Content providers at this stage allow you to make the database accessible to different applications or to access the content provided by these applications.

  • Music Playlist
  • Calls Logs
  • Contact List
  • Message Threads
  • Gallery Application
  • File Manager, etc

Methods of Content Provider in Android

Six methods are used while implementing the Content Provider. Following are the methods:

1. onCreate()

This method is called to initialize the provider whenever a content provider is created.

2. query()

The query method takes parameters to fetch data from the database. The data is accessed through a cursor object.

3. insert()

This method is used to insert a row in the database.

4. update()

This method is used to alter the data fields present in the database.

5. delete()

This method is used to delete records from the database

6. getType()

It returns the MIME(Multipurpose Internet Mail Extension) type of the data, which can be used as the content URI.

User data is usually stored in SQLite Database inside the user’s device. We can perform several read, write, update, delete operations on the data.

Press enter or click to view image in full size

We know that the Content Provider provides us data, but we need to establish a connection to get this data. The link is made using the “ContentResolver” object. The ContentResolver objects help the application to communicate with the Content Provider.

Now, in the next step, we need to connect our ContentResolver object with the user interface. By this step, the user can interact directly with the Content Provider by using the user interface. For this purpose, we require another object called CursorLoader.

The CursorLoader task is to receive the user’s query request and forward it to the Content Provider. The content Provider executes the query and provides the user the requested data.

The structure of any Content URI can be divided into four types:

  • Prefix -Usually, the prefix is set to content://.
  • Authority — It contains the name of the Provider.
  • Path — It contains the location of the data.
  • ID — This is an optional parameter that is used to access specific records.

Any Content URI will look as follows:

content://<authority>/<path>/<optional_id>

How to integrate to the app?

  1. In AndroidManifest.xml :

<uses-permission android:name=”android.permission.READ_CONTACTS”/>

2. app –> res –> layout –> activity_main.xml and add a list view to display the contacts.

3. MainActivity.kt:

package com.example.contentprovider

import android.content.pm.PackageManager
import android.os.Bundle
import android.provider.ContactsContract
import android.widget.ListView
import android.widget.SimpleCursorAdapter
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat

class MainActivity : AppCompatActivity()
{
//this variable stores the contact details
//in the form of an array
var contact_fields = listOf<String>(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone._ID

).toTypedArray()

//using listview to show your contacts in list form
lateinit var list_view:ListView;

override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

//Binding ListView to a variable
//to display the contact list

list_view = findViewById(R.id.contact_list_view);

//Checking if the user has granted
//permission to access his contacts or not

if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS) !=
PackageManager.PERMISSION_GRANTED)
{
//If permission not granted
//then seek permission from user

ActivityCompat.requestPermissions(this,
Array(1){android.Manifest.permission.READ_CONTACTS},
100)
}
else
{
//if permission granted then access user contacts
readUserContacts();
}
}

override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
)
{
//This function is called
super.onRequestPermissionsResult(requestCode, permissions, grantResults)

if(requestCode == 100 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
//if permission granted
//then display contacts
readUserContacts()
}
}
private fun readUserContacts()
{
var source = listOf<String>(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER

).toTypedArray()

var destination = intArrayOf(android.R.id.text1, android.R.id.text2)

var result_set = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
contact_fields, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)

var adapter = SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, result_set,
source, destination, 0);

list_view.adapter = adapter



}
}

4. Test the result.

Thank you for your patient . See you in my other articles. :)

--

--