Android Emulator
Android Emulator
Android Emulator
As we know the modern JVM is high performance and provides excellent memory
management. But it needs to be optimized for low-powered handheld devices as well.
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.
Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.
The Dex compiler converts the class files into the .dex file that run on the Dalvik VM.
Multiple class files are converted into one dex file.
Let's see the compiling and packaging process from the source file:
The javac tool compiles the java source file into the class file.
The dx tool takes all the class files of your application and generates a single .dex file. It
is a platform-specific tool.
The Android Assets Packaging Tool (aapt) handles the packaging process.
1. </manifest>
Elements of the AndroidManifest.xml file
The elements used in the above xml file are described below.
<manifest>
manifest is the root element of the AndroidManifest.xml file. It has package attribute
that describes the package name of the activity class.
<application>
application is the subelement of the manifest. It includes the namespace declaration.
This element contains several subelements that declares the application component
such as activity etc.
The commonly used attributes are of this element are icon, label, theme etc.
android:icon represents the icon for all the android application components.
android:label works as the default label for all the application components.
android:theme represents a common theme for all the android activities.
<activity>
activity is the subelement of application and represents an activity that must be
defined in the AndroidManifest.xml file. It has many attributes such as label, name,
theme, launchMode etc.
android:label represents a label i.e. displayed on the screen.
android:name represents a name for the activity class. It is required attribute.
<intent-filter>
intent-filter is the sub-element of activity that describes the type of intent to which
activity, service or broadcast receiver can respond to.
<action>
It adds an action for the intent-filter. The intent-filter must have at least one action
element.
<category>
It adds a category name to an intent-filter.
1. Android Emulator
The Android emulator is an Android Virtual Device (AVD), which represents a
specific Android device. We can use the Android emulator as a target device to execute
and test our Android application on our PC. The Android emulator provides almost all the
functionality of a real device. We can get the incoming phone calls and text messages. It
also gives the location of the device and simulates different network speeds. Android
emulator simulates rotation and other hardware sensors. It accesses the Google Play
store, and much more
Testing Android applications on emulator are sometimes faster and easier than doing on
a real device. For example, we can transfer data faster to the emulator than to a real
device connected through USB.
The Android emulator comes with predefined configurations for several Android phones,
Wear OS, tablet, Android TV devices.
The Android emulator takes additional requirements beyond the basic system
requirement for Android Studio. These requirements are given below:
o SDK Tools 26.1.1 or higher
o 64-bit processor
o Windows: CPU with UG (unrestricted guest) support
o HAXM 6.2.1 or later (recommended HAXM 7.2.0 or later)
o
Install the emulator
The Android emulator is installed while installing the Android Studio. However some
components of emulator may or may not be installed while installing Android Studio. To
install the emulator component, select the Android Emulator component in the SDK
Tools tab of the SDK Manager.
1.3 Select a hardware profile and then click Next. If we don?t see the hardware profile
we want, then we can create or import a hardware profile. The System Image page
appears.
1.4 Select the system image for the particular API level and click Next. This leads to
open a Verify Configuration page.
1.5 Change AVD properties if needed, and then click Finish.
2. In the toolbar, choose the AVD, which we want to run our app from the target device
from the drop-down menu.
3. Click Run.
Launch the Emulator without first running an app
To start the emulator:
1. Open the AVD Manager.
2. Double-click an AVD, or click Run
While the emulator is running, we can run the Android Studio project and select the
emulator as the target device. We can also drag an APKs file to install on an emulator,
and then run them.
3. Android Activity Lifecycle
In android, Activity represents a single screen with a user interface (UI) of an
application and it will acts an entry point for users to interact with an app.
Generally, the android apps will contain multiple screens and each screen of our
application will be an extension of Activity class. By using activities, we can place all our
android application UI components in a single screen.
From the multiple activities in android app, one activity can be marked as a main
activity and that is the first screen to appear when we launch the application. In android
app each activity can start another activity to perform different actions based on our
requirements.
For example, a contacts app which is having multiple activities, in that the main activity
screen will show a list of contacts and from the main activity screen we can launch other
activities that provide screens to perform tasks like add a new contact and search for
the contacts. All these activities in the contact app are loosely bound to other activities
but will work together to provide a better user experience.
}
This is how we can activities in android application based on our requirements.
By using activity cal-back methods we can define how our activity can behave when the
user enter or leaves our application.
This section will give you detailed information about callback methods to handle activity
transitions between states during the lifecycle.
onCreate()
This is the first callback method and it fires when the system creates an activity for the
first time. During the activity creation, activity entered into a Created state.
If we have an application start-up logic that needs to perform only once during the life
cycle of an activity, then we can write that logic in onCreate() method.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Once onCreate() method execution is finished, the activity will enter into Started state
and the system calls the onStart() method.
onStart()
The onStart() callback method will invoke when an activity entered into Started State
by completing onCreate() method. The onStart() method will make an activity visible to
the user and this method execution will finish very quickly.
@Override
protected void onStart()
{
super.onStart()
}
After completion of onStart() method execution, the activity enters into Resumed state
and system invoke the onResume() method.
onResume()
When an activity entered into Resumed state, the system invokes onResume() call back
method. In this state activity start interacting with the user that means user can see the
functionality and designing part of an application on the single screen.
The app will stay in this Resumed state until an another activity happens to take focus
away from the app like getting a phone call or screen turned off, etc.
In case if any interruption events happen in Resumed state, the activity will enter
into Paused state and the system will invoke onPause() method.
After an activity returned from Paused state to Resumed state, the system again will
call onResume() method due to this we need to implement onResume() method to
initialize the components that we release during onPause() method
@Override
public void onResume() {
super.onResume();
if (mCamera == null) {
initializeCamera();
}
}
If any interruption happens in Resumed state, the activity will enter into Paused state
and the system will invoke onPause() method.
onPause()
Whenever the user leaves an activity or the current activity is being Paused then the
system invokes onPause() method. The onPause() method is used to pause operations
like stop playing the music when the activity is in a paused state or pass an activity
while switching from one app to another app because every time only one app can be
focused.
@Override
public void onPause() {
super.onPause();
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
After completion of onPause() method execution, the next method is
either onStop() or onResume() depending on what happens after an activity entered into
a Paused state.
onStop()
The system will invoke onStop() callback method when an activity no longer visible to
the user, the activity will enter into Stopped state. This happens due to current activity
entered into Resumed state or newly launched activity covers complete screen or it’s
been destroyed.
The onStop() method is useful to release all the app resources which are no longer
needed to the user.
@Override
protected void onStop()
{
super.onStop();
}
The next callback method which raised by the system is either onRestart(), in case if the
activity coming back to interact with the user or onDestroy(), in case if the activity
finished running.
onRestart()
The system will invoke onRestart() method when an activity restarting itself after
stopping it. The onRestart() method will restore the state of activity from the time that is
being stopped.
onDestroy()
The system will invoke onDestroy() method before an activity is destroyed and this is the
final callback method received by the android activity.
The system will invoke this onDestory() callback method either the activity is finishing or
system destroying the activity to save space.
@Override
public void onDestroy()
{
super.onDestroy();
}
The onDestroy() method will release all the resources which are not released by previous
callback onStop() method.
Following is the pictorial representation of the Android Activity Life cycle which shows
how Activity will behave in different stages using callback methods.
Whenever the user trying to leave an activity like switching from one app to another
app, the system will use callback methods to dismantle the activity completely or
partially to resume the activity from where the user left off.
Based on our requirements we can implement the activity in the android app using the
callback method and it’s not necessary to use all callback methods in each android
application.
package com.tutlane.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Activity Lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("Activity Lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("Activity Lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("Activity Lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("Activity Lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("Activity Lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("Activity Lifecycle","onDestroy invoked");
}
}
(1) No Activity
As the name suggests No Activity means creating a new empty project. When the
developer selects this activity there will be neither an XML file nor a Java/Kotlin file. No
files are automatically generated when you select No Activity. The project structure will
look like the following:
Tabbed Activity creates a new blank activity with tabs. These files are automatically
created when you select Tabbed Activity and the following is the welcome page:
The following are the basic core application components that can be used in Android
application.
Activities
Intents
Content Providers
Broadcast Receivers
Services
All these application components are defined in the android app description file
(AndroidMainfest.xml) like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<manifest …..>
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" ……>
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
…….
</application>
</manifest>
This is how we can define an android application components
in AndroidManiFest.xml file.
Android Activities
In android, Activity represents a single screen with a user interface (UI) and it will acts
an entry point for the user’s to interact with app.
For example, a contacts app that is having multiple activities like showing a list of
contacts, add a new contact, and another activity to search for the contacts. All these
activities in the contact app are independent of each other but will work together to
provide a better user experience.
Android Intents
In android, Intent is a messaging object which is used to request an action from another
component.
Starting an Activity
Starting a Service
Delivering a Broadcast
There are two types of intents available in android, those are
1. Implicit Intents
2. Explicit Intents
To know more about Intents in android check this Android Intents.
Android Services
In android, Service is a component that keeps an app running in the background to
perform long-running operations based on our requirements. For Service, we don’t have
any user interface and it will run the apps in background like play music in background
when the user in different app.
Local Services
Remote Services
To know more about Services in android check this Android Services.
Android Broadcast Receivers
In android, Broadcast Receiver is a component that will allow a system to deliver events
to the app like sending a low battery message to the app. The apps can also initiate
broadcasts to let other apps know that required data available in a device to use it.
Generally, we use Intents to deliver broadcast events to other apps and Broadcast
Receivers use status bar notifications to let the user know that broadcast event occurs.
To know more about Broadcast Receivers in android check this Android Broadcast
Receivers.
By using Content Providers, other apps can query or modify the data of our app based
on the permissions provided by content provider. For example, android provides a
Content Provider (ContactsContract.Data) to manage contacts information, by using
proper permissions any app can query the content provider to perform read and write
operations on contacts information.
To know more about Content Providers in android check this Android Content Provider.
Additional Components
In android, we have additional components which are used to build the relationship
between the above components (Activities, Intents, Content
Providers, Services and Broadcast Receivers) to implement our application logic, those
are
Compon
ent Description
Layouts These are used to define the user interface (UI) for an activity or
app
Views These are used to build a user interface for an app using UI
elements like buttons, lists, etc.
After finishing the Activity configuration, Android Studio auto generates the activity class
and other required configuration files.
Now an android project has been created. You can explore the android project and see
the simple program, it looks like this:
2) Write the message
File: activity_main.xml
Android studio auto generates code for activity_main.xml file. You may edit this file
according to your requirement.
1. <?xml version="1.0" encoding="utf-8"?>
2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="first.javatpoint.com.welcome.MainActivity">
8.
9. <TextView
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:text="Hello Android!"
13. app:layout_constraintBottom_toBottomOf="parent"
14. app:layout_constraintLeft_toLeftOf="parent"
15. app:layout_constraintRight_toRightOf="parent"
16. app:layout_constraintTop_toTopOf="parent" />
17.
18. </android.support.constraint.ConstraintLayout>
19. }
File: MainActivity.java
1. package first.javatpoint.com.welcome;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {
9. super.onCreate(savedInstanceState);
10. setContentView(R.layout.activity_main);
11. }
12. }
To understand the first android application, visit the next page (internal details of hello
android example).
Andorid Toast can be used to display information for the short period of time. A toast
contains message to be displayed quickly and disappears after sometime.
The android.widget.Toast class is the subclass of java.lang.Object class.
You can also create custom toast as well for example toast displaying image. You can
visit next page to see the code for custom toast.
Toast class
Toast class is used to show notification for a particular interval of time. After sometime it
disappears. It doesn't block the user interaction.
Constants of Toast class
There are only 2 constants of Toast class which are given below.
Constant Description
public static final int displays view for the long duration
LENGTH_LONG of time.
public static final int displays view for the short duration
LENGTH_SHORT of time.
Methods of Toast class
The widely used methods of Toast class are given below.
Method Description
public static Toast makeText(Context context, makes the toast containing text
CharSequence text, int duration) and duration.
public void setMargin (float horizontalMargin, float changes the horizontal and vertical
verticalMargin) margin difference.
Output:
<EditText
android:id="@+id/send_text_id"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="20dp"
android:hint="Input"
android:textSize="25dp"
android:textStyle="bold" />
<Button
android:id="@+id/send_button_id"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginLeft="150dp"
android:layout_marginTop="150dp"
android:text="send"
android:textStyle="bold" />
</RelativeLayout>
This will make the UI of the Application
send_button = findViewById(R.id.send_button_id);
send_text = findViewById(R.id.send_text_id);
// add the OnClickListener in sender button after clicked this button following
Instruction will run
send_button.setOnClickListener(v -> {
// get the value which input by user in EditText and convert it to string
String str = send_text.getText().toString();
// Create the Intent object of this class Context() to Second_activity class
Intent intent = new Intent(getApplicationContext(), Second_activity.class);
// now by putExtra method put the value in key, value pair key is
// message_key by this key we will receive the value, and put the string
intent.putExtra("message_key", str);
// start the Intent
startActivity(intent);
});
}
}
Step 4: Creating Second_Activity to Receive the Data.
The steps to create the second activity are as follows:
android project > File > new > Activity > Empty Activity