0% found this document useful (0 votes)
12 views55 pages

Android App Development Lab Manual

The document is a lab manual for Android App Development at Dr. Akhilesh Das Gupta Institute of Professional Studies for the academic year 2023-2024. It outlines various experiments related to Android app development, including setting up the development environment, building user interfaces, creating activities, implementing fragments, and deploying apps. Additionally, it includes the institute's vision, mission, and program educational objectives for the Department of Information Technology.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views55 pages

Android App Development Lab Manual

The document is a lab manual for Android App Development at Dr. Akhilesh Das Gupta Institute of Professional Studies for the academic year 2023-2024. It outlines various experiments related to Android app development, including setting up the development environment, building user interfaces, creating activities, implementing fragments, and deploying apps. Additionally, it includes the institute's vision, mission, and program educational objectives for the Department of Information Technology.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

DR.

AKHILESH DAS GUPTA INSTITUE OF PROFESSIONAL STUDIES


(FORMERLY DR. AKHILESH DAS GUPTA INSTITUTE OF TECHNOLOGY & MANAGEMENT)
FC-26, Shastri Park, New Delhi-110053

LAB MANUAL

Android APP Development

Academic Year: 2023-2024 Semester: 6th

Name of Faculty: Ms. Anshika Negi


Department: IT
Program: [Link] Sem: 6th
Paper Code: OSD-334P
Subject Name: Android App Development
[Link]. EXPERIMENTS Date T. Sign
1 Setting Up the Development Environment
● Install and configure Android Studio.
● Create a new Android project.
● Familiarize yourself with the project structure.
2 Building a Basic User Interface
● Design a simple user interface using XML.
● Add various user interface components, such as
buttons, text fields, and images.● Implement event
handling for user interactions.
3 Creating Activities and Navigating Between Screens
● Create multiple activities within an app.
● Implement navigation between activities using
intents.
● Pass data between activities using intent extras.
4 Implementing Fragments
● Create fragments to represent reusable UI
components.
● Integrate fragments into activities.
● Manage fragment transactions and backstack.
5 Implementing Services and Broadcast Receivers
● Implement a background service for performing
a long-running task.
● Register and receive broadcasts using broadcast
receivers.
● Communicate between services, broadcast
receivers, and activities.
6 Implementing Data Storage and Retrieval
● Use shared preferences for saving and retrieving
data.
● Implement SQLite database for data persistence.
● Fetch data from web services and parse JSON
responses.
7 Integrating Multimedia and Location Services
● Capture and display images using the camera and
gallery.● Implement audio and video playback in the
app.● Integrate location-based services and display
maps.
8 Testing and Debugging Android Apps
● Use debugging tools in Android Studio to identify
and fix issues.
● Perform unit testing to ensure app functionality.
● Optimize app performance using profiling tools.
9 Deploying Android Apps
● Create a signed APK for deployment.
● Install and run the app on physical devices
and emulators.
● Publish the app to the Google Play Store.
10 Team Project
● Collaborate in a team to develop a complete
Android app.
● Plan and document the project requirements,
design, and implementation.
● Present the final app and demonstrate its
functionality.
Dr. Akhilesh Das Gupta Institute of Technology and
Management
(Formerly Northern India Engineering College)
FC-26, Shastri Park, New Delhi-110053

INSTITUTE VISION AND MISSION

To produce globally competent and socially


VISION

responsible technocrats and entrepreneurs who


can develop innovative solutions to meet the
challenges of 21st century.

MISSION
1. To provide value-based education through multi grade teaching
methodologies and modern education facilities.

2. To sustain an active partnership program with industry and other


academic institutes with an aim to promote knowledge and resource sharing.

3. To conduct value-added training programme to enhance employability.

4. To provide a conducive environment for development of ethical and


socially responsible technocrats, managers and entrepreneurs.

DEPARTMENT OF INFORMATION TECHNOLOGY

To produce successful IT graduates with a strong


VISION

technical background and managerial skills for


promoting growth in industry and society.

M1: To provide managerial and professional


MISSION

skills among the students through value added


programs.
M2: To provide an atmosphere where faculty and
students can be engaged in continuous learning
and contribute in the overall growth of the society.
M3: To provide industry oriented technical
environment to help students excel in diversified
fields.
PROGRAM EDUCATIONAL OBJECTIVES

PEO1: To produce graduates with strong


fundamentals in Information Technology
engineering to help them excel in their
respective fields.
PEO2: To develop graduates who will
show willingness to learn new things
and will work as a team.
PEO3: To enable graduates to be proficient in coding
and problem-solving skills.

Program Specific Outcomes (PSO)

At the end of program, the student,


PSO1 Understanding: Graduates should
be able to understand the concepts and
applications in all areas of Information
Technology.
PSO2 Problem Solving skills: Graduates should be able to apply

PSO3 Benefit to the Society: Graduates


the gained technical knowledge to solve real world problems.

will be motivated to work with multi-


disciplinary teams and should use their
engineering knowledge and services for
the benefit of society.
EXPERIMENT NO.1

Aim : Setting Up the Development Environment


● Install and configure Android Studio.
● Create a new Android project.
● Familiarize yourself with the project structure

Step 1 - System Requirements


The required tools to develop Android applications are open source and can be downloaded from
the Web. Following is the list of software's you will need before you start your Android application
programming.
Java JDK5 or later version
Java Runtime Environment (JRE) 6
Android Studio

Step 2 - Setup Android Studio


Android Studio is the official IDE for android application [Link] works based on IntelliJ
IDEA, You can download the latest version of android studio from Android Studio 2.2 Download, If
you are new to installing Android Studio on windows,you will find a file, which is named as android-
[Link] just download and run on windows machine according
to android studio wizard guideline.
If you are installing Android Studio on Mac or Linux, You can download the latest version from Android
Studio Mac Download,or Android Studio Linux Download, check the instructions provided along with
the downloaded file for Mac OS and Linux. This tutorial will consider that you are going to setup your
environment on Windows machine having Windows 8.1 operating system. Installation So let's launch
Android [Link],Make sure before launch Android Studio, Our Machine should required installed
Java JDK. To install Java JDK,take a references of Android environment setup

Once you launched Android Studio, its time to mention JDK7 path or later version in
android studio installer.
Below the image initiating JDK to android SDK

Need to check the components, which are required to create applications, below the image has
selected Android Studio, Android SDK, Android Virtual Machine and performance(Intel chip).
Need to specify the location of local machine path for Android studio and Android SDK, below
the image has taken default location of windows 8.1 x64 bit architecture.

Need to specify the ram space for Android emulator by default it would take 512MB of
local machine RAM.
At final stage, it would extract SDK packages into our local machine, it would take a while time
to finish the task and would take 2626MB of Hard disk space.

After done all above steps perfectly, you must get finish button and it gonna be open
android studio project with Welcome to android studio message as shown below.

You can start your application development by calling start a new android studio project. in a new
installation frame should ask Application name, package information and location of the project.
After entered application name, it going to be called select the form factors your application
runs on, here need to specify Minimum SDK

The next level of installation should contain selecting the activity to mobile, it specifies the default
layout for Applications
Step 3 - Create Android Virtual Device
To test your Android applications, you will need a virtual Android device. So before we start
writing our code, let us create an Android virtual device. Launch Android AVD Manager
Clicking AVD_Manager icon as shown below

After Click on a virtual device icon, it going to be shown by default virtual devices which are
present on your SDK, or else need to create a virtual device by clicking Create new Virtual
device button
EXPERIMENT -2
Aim: Building a Basic User Interface.
• Design a simple user interface using XML
• Add various user interface components, such as buttons, text fields, and images.
• Implement event handling for user interactions.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- activity_main.xml -->
<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="[Link]">

<!-- TextView -->


<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter your name:"
android:layout_marginTop="20dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>

<!-- EditText -->


<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Your name"
android:layout_below="@id/textView"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"/>

<!-- Button -->


<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_below="@id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"/>

<!-- ImageView -->


<ImageView
android:id="@+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/ic_launcher_foreground"
android:layout_below="@id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"/>

</RelativeLayout>

[Link]
package [Link].project2;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState)
{ [Link](savedInstanceState);
setContentView([Link].activity_main);

Button button = findViewById([Link]);


[Link](new [Link]() {
@Override
public void onClick(View v) {
// Handle button click event here
EditText editText = findViewById([Link]);
String name = [Link]().toString();
[Link]([Link], "Hello, " + name + "!",
Toast.LENGTH_SHORT).show();
}
});
}
}
Output:
EXPERIMENT-3
Aim: Creating Activities and Navigating Between Screens:
• Create multiple activities within an app.
• Implement navigation between activities using intents.
• Pass data between activities using intent extras.

activity_main.xml
<!-- activity_main.xml -->
<RelativeLayout
xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your text here"
android:layout_marginTop="20dp"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"/>

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:layout_below="@id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"/>

</RelativeLayout>

Activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Data from MainActivity:"
android:layout_centerInParent="true"/>

</RelativeLayout>
[Link]
package [Link].project2;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

private EditText editText; // Declare the EditText


private Button button; // Declare the Button

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

editText = findViewById([Link]); // Initialize the


EditText
button = findViewById([Link]); // Initialize the Button

[Link](new [Link]()
{ @Override
public void onClick(View v) {
// Get text from EditText
String textToSend = [Link]().toString();

// Create an Intent to start Activity B and pass the


text
Intent intent = new Intent([Link],
[Link]);
[Link]("text",
textToSend); startActivity(intent);
}
});
}
}

[Link]
package [Link].project2;

import [Link];
import [Link];
import [Link];
import [Link];

public class SecondActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_second);
/ Retrieve the text from the
Intent Intent intent = getIntent();
if (intent != null && [Link]("text")) { String
receivedText = [Link]("text");

// Display the text in a TextView


TextView textView = findViewById([Link]);
[Link](receivedText);
}
}
}

Output:
EXPERIMENT-4

Aim: Implementing Fragments

1. Create fragments to represent reusable Ul components.


2. Integrate fragments into activities.
3. Manage fragment transactions and backstack.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="[Link]">

<fragment
android:id="@+id/fragment1"
android:name="[Link].Fragment1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
/>

<fragment
android:id="@+id/fragment2"
android:name="[Link].Fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>

fragment_fragment1.xml
<FrameLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F5F5DC"
tools:context="[Link].Fragment1">

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
File: fragment_fragment2.xml

<FrameLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F0FFFF"
tools:context="[Link].Fragment2">

<!-- TODO: Update blank fragment layout -->


<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>

[Link]

package [Link];

import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState)
{ [Link](savedInstanceState);
setContentView([Link].activity_main);

/ Initially add Fragment1 to the container


Fragment1 fragment1 = new Fragment1();
getSupportFragmentManager().beginTransaction()
.add([Link].fragment_container, fragment1)
.commit();
}

/ Method to replace Fragment1 with Fragment2 and add the transaction to the
backstack public void replaceFragment() {
Fragment2 fragment2 = new Fragment2();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
[Link]([Link].fragment_container, fragment2);
[Link](null); // Add transaction to backstack [Link]();

}
@Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
{ getSupportFragmentManager().popBackStack(); // Pop transaction from backstack
} else {
[Link](); // Default back button behavior
}
}
}

[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Fragment1 extends Fragment {

@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState); }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return [Link]([Link].fragment_fragment1, container, false);
}
}

File: [Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];
public class Fragment2 extends Fragment {

@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
return [Link]([Link].fragment_fragment2, container, false);}}
OUTPUT:
EXPERIMENT-5

Aim: Implementing Services and Broadcast Receivers

1. Communicate between services, broadcast receivers, and activities.


2. Implement a background service for performing a long-running task.
3. Register and receive broadcasts using broadcast receivers
We will create an alarm clock which will act as static broadcast receiver
Designing layout for the Android Application:

activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="20dp"
android:checked="false"
android:onClick="OnToggleClicked" />
</LinearLayout>
activity_alarm_receiver.xml.
<?xml version="1.0" encoding="utf-8"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AlarmReceiver">
</[Link]>

activity_alarm_receiver.xml.

<?xml version="1.0" encoding="utf-8"?>


<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AlarmReceiver">
</[Link]>

Java Coding for the Android Application([Link]):


package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity
{
TimePicker alarmTimePicker;
PendingIntent pendingIntent;
AlarmManager alarmManager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
[Link](savedInstanceState);
setContentView([Link].activity_main);
alarmTimePicker = (TimePicker) findViewById([Link]);
alarmManager = (AlarmManager)
getSystemService(ALARM_SERVICE); }
public void OnToggleClicked(View view)
{
long time;
if (((ToggleButton) view).isChecked())
{
[Link]([Link], "ALARM ON", Toast.LENGTH_SHORT).show();
Calendar calendar = [Link]();
[Link](Calendar.HOUR_OF_DAY, [Link]());
[Link]([Link], [Link]());
Intent intent = new Intent(this, [Link]); pendingIntent =
[Link](this, 0, intent, 0);
time=([Link]()-([Link]()%60000));

if([Link]()>time)
{
if (calendar.AM_PM == 0)
time = time + (1000*60*60*12);
else
time = time + (1000*60*60*24);
}
[Link](AlarmManager.RTC_WAKEUP, time, 10000, pendingIntent);
}
else
{
[Link](pendingIntent);
[Link]([Link], "ALARM OFF", Toast.LENGTH_SHORT).show();
}
}
}

[Link].(implements static broadcast receiver , works in background )

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class AlarmReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
[Link](context, "Alarm! Wake up! Wake up!",
Toast.LENGTH_LONG).show(); Uri alarmUri =
[Link](RingtoneManager.TYPE_ALARM); if (alarmUri == null)
{
alarmUri =
[Link](RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = [Link](context, alarmUri);
[Link]();
}}
[Link].
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
package="[Link]" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver" >
</receiver>
</application>
</manifest>

Output:
EXPERIMENT-6
Aim: Implementing Data Storage and Retrieval
1. Use shared preferences for saving and retrieving data.
2. Implement SQLite database for data persistence.
3. Fetch data from web services and parse JSON responses.

Student Contract Class([Link]):


public class
StudentContract { public
static final String
DATABASE_NAME =
"student_db"; public static final int
DATABASE_VERSION = 1; private static
final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP =
",";

public static final class StudentEntry {


public static final String TABLE_NAME =
"students"; public static final String
COLUMN_ROLL_NO = "roll_no"; public static
final
String COLUMN_NAME = "name"; public static final String
COLUMN_BRANCH = "branch"; public static final String
COLUMN_MARKS = "marks"; public static final String
COLUMN_PERCENTAGE = "percentage";

public static final String CREATE_TABLE =


"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ROLL_NO + " INTEGER PRIMARY KEY," +
COLUMN_NAME + TEXT_TYPE + COMMA_SEP +
COLUMN_BRANCH + TEXT_TYPE + COMMA_SEP +
COLUMN_MARKS + " REAL" + COMMA_SEP +
COLUMN_PERCENTAGE + " REAL" +
");";
}}

StudentDbHelper Class ([Link]):


public class StudentDbHelper extends
SQLiteOpenHelper { public
StudentDbHelper(Context context) {
super(context, StudentContract.DATABASE_NAME,
null, StudentContract.DATABASE_VERSION);
}
@Override public void onCreate(SQLiteDatabase db)
{ [Link]([Link].CREATE_TABLE);
}
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{ // Handle database schema changes if needed
}
}

[Link]:
public class MainActivity extends
AppCompatActivity { private EditText
rollNoEditText, nameEditText,
marksEditText; private Spinner branchSpinner; private Button addButton,
retrieveButton; private StudentDbHelper dbHelper; @Override protected
void onCreate(Bundle
savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
rollNoEditText = findViewById([Link].roll_no_edit_text); nameEditText
= findViewById([Link].name_edit_text); marksEditText =
findViewById([Link].marks_edit_text); branchSpinner
= findViewById([Link].branch_spinner); addButton =
findViewById([Link].add_button); retrieveButton =
findViewById([Link].retrieve_button); dbHelper = new
StudentDbHelper(this);

ArrayList<String> branches=new ArrayList<>(); [Link]("CSE");


[Link]("IT"); [Link]("ECE"); ArrayAdapter<String>
branchAdapter = new ArrayAdapter<>(this,
[Link].simple_spinner_item, branches);
[Link]([Link].simple_spinn
er_dropdown_item);
[Link](branchAdapter);

[Link](new [Link]() {
@Override
public void onClick(View v) {
String rollNo = [Link]().toString().trim();
String name = [Link]().toString().trim();
String branch = [Link]().toString();
String marksString = [Link]().toString().trim();

if (![Link]() && ![Link]() && ![Link]() &&


![Link]()) {
double marks = [Link](marksString); double
percentage = (marks / 100) * 100; ContentValues values =
new ContentValues();
[Link]([Link].COLUMN_ROLL_N
O, rollNo);
OUTPUT:
EXPERIMENT-7

Aim : Integrating Multimedia and Location Services:


[Link] and display images using the camera and gallery.
[Link] audio and video playback in the app.
[Link] location-based services and display maps.

[Link].

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link]; import
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class UseGps extends Activity implements OnMapReadyCallback {

private static final int REQUEST_IMAGE_CAPTURE = 1;


private static final int REQUEST_PICK_IMAGE = 2;

Button buttonSend, buttonCapture, buttonSelect;


EditText textSMS, textLon;
ImageView imageView;
VideoView videoView;
LocationManager mlocManager;
LocationListener mlocListener;
GoogleMap mMap;

@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link]);

buttonSend = findViewById([Link]);
buttonCapture = findViewById([Link]);
buttonSelect = findViewById([Link]);
textSMS = findViewById([Link]); textLon =
findViewById([Link]); imageView =
findViewById([Link]); videoView =
findViewById([Link]);

// Request location permissions


if ([Link](this,
[Link].ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
[Link](this, new
String[]{[Link].ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION);
}

// Initialize location manager and listener


mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();

/ Request location updates


[Link](LocationManager.GPS_PROVIDER, 0, 0,
mlocListener);

/ Obtain the SupportMapFragment and get notified when the map is ready to be
used. SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById([Link]);
[Link](this);

/ Button click listeners


[Link](view -> {
/ Handle sending location or other actions
});

[Link](view -> {
dispatchTakePictureIntent();
});
[Link](view -> {
openGallery();
});
/ Play video
playVideo(); }
@Override
protected void onDestroy() {
[Link]();
/ Stop location updates when activity is destroyed
if (mlocManager != null) {
[Link](mlocListener);
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
[Link](requestCode, permissions,
grantResults); if (requestCode == REQUEST_LOCATION_PERMISSION) {
if ([Link] > 0 && grantResults[0]
== PackageManager.PERMISSION_GRANTED) {
/ Location permission
granted } else {
/ Location permission denied
[Link](this, "Location permission denied", Toast.LENGTH_SHORT).show();
}
}
}
public class MyLocationListener implements LocationListener
{ public void onLocationChanged(Location loc) {
double lat = [Link]();
double lon = [Link]();
[Link]([Link](lat));
[Link]([Link](lon));
/ Move camera to current location
[Link]([Link](new LatLng(lat, lon),
15));
}

public void onProviderDisabled(String provider)


{ [Link](getApplicationContext(), "GPS Disabled",
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider)
{ [Link](getApplicationContext(), "GPS Enabled",
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onMapReady(GoogleMap googleMap)
{ mMap = googleMap;
/ Enable current location button
[Link](true);
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if
([Link](getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}

private void openGallery() {


Intent galleryIntent = new Intent(Intent.ACTION_PICK,
[Link].EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, REQUEST_PICK_IMAGE);
}

private void playVideo() {


// Set video path
String videoPath = "[Link]://" + getPackageName() + "/"
+ [Link];
[Link]([Link](videoPath));
/ Start video
[Link]();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{ [Link](requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK)
{ Bundle extras = [Link]();
Bitmap imageBitmap = (Bitmap) [Link]("data");
[Link](imageBitmap);
} else if (requestCode == REQUEST_PICK_IMAGE && resultCode == RESULT_OK &&
data != null) {
Uri selectedImage = [Link]();
[Link](selectedImage);
}
}
}

[Link]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="System" />
<EditText
android:id="@+id/editTextSMS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top" />
<EditText
android:id="@+id/textlon"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top" />
<Button
android:id="@+id/buttonSend"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send" />
<Button
android:id="@+id/buttonCapture"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Capture Image" />
<Button
android:id="@+id/buttonSelect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Select Image" />
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp" />
</LinearLayout>

Output:
EXPERIMENT-8
Aim: Testing and Debugging Android Apps
Use debugging tools in Android Studio to identify and fix
issues.
Perform unit testing to ensure app functionality.
Optimize app performance using profiling tools
Debug your app
Android Studio provides a debugger that lets you do the
following and more:
• Select a device to debug your app on.
• Set breakpoints in your Java, Kotlin, and C/C++ code.
• Examine variables and evaluate expressions at runtime.

This page includes instructions for basic debugger operations..

Enable debugging

Before you can begin debugging, do the following:

Enable debugging on your device.

If you're using the emulator, debugging is enabled by default. But for a


connected device, you need to enable debugging in the device
developer options.

Run a debuggable build variant.

Use a build variant that includes debuggable true (isDebuggable = true in Kotlin
scripts) in the build configuration.

Usually, you can select the default "debug" variant that's included in every
Android Studio project, even though it's not visible in the [Link] file.
However, if you define new build types that should be debuggable, you must
add debuggable true to the build type:

GroovyKotlin
android {
buildTypes {
customDebugType {
debuggable true
...
}
}
}
If your app depends on a library module that you also want to debug, that library
must also be packaged with debuggable true so it retains its debug symbols. To
ensure that the debuggable variants of your app project receive the debuggable
variant of a library module, publish non-default versions of your library.

Start debugging

You can start a debugging session as follows:

1. Set breakpoints in your app's code.


2. In the toolbar, select a device to debug your app on from the target device menu.

If you don't have any devices configured, then you need to either connect a device via
USB, connect a device via Wi-Fi, or create an AVD to use the Android Emulator.

3. In the toolbar, click Debug .

If your app is already running on the device, a dialog is displayed asking if you want to
switch from Run to Debug. The device will need to restart in order to begin debugging. To
keep the same instance of the app running, click Cancel Debug and instead attach the
debugger to a running app. Otherwise, Android Studio builds an APK, signs it with a
debug key, installs it on your selected device, and runs it.
If you add C and C++ code to your project, Android Studio also runs the LLDB debugger
in the Debug window to debug your native code.
If the Debug window isn't open, select View > Tool Windows > Debug, or

click Debug in the tool window bar.

Attach the debugger to a running app

If your app is already running on your device, you can start debugging without
restarting your app as follows:

Click Attach debugger to Android process .


In the Choose Process dialog, select the process you want to attach the debugger to.
If you're using an emulator or a rooted device, you can check Show all processes to see all
processes. On a rooted device, this will show all processes running on the device.
However, on an un-rooted device, this will only show debuggable processes.
From the Use Android Debugger Settings from menu, you can select an existing run/debug
configuration. For C and C++ code, this lets you reuse the LLDB startup commands, LLDB
post-attach commands, and symbol directories in an existing configuration.
If you don't have an existing run/debug configuration, select Create New. This selection
enables the Debug Type menu, where you can select a different debug type. By default,
Android Studio uses the Detect Automatically debug type to select the best debugger
option for you based on whether your project includes Java or C/C++ code. Click OK.

The Debug window appears.

The Processes tab in the Device Explorer (View > Tool Windows > Device
Explorer) also has a list of debuggable processes. From there you can select a

process and perform a kill , force-stop , or attach the debugger to a given

process .

The debug window

The debug window is divided into

Execution and navigation toolbar See Work with breakpoints


Thread selector
Evaluation and watch expression entry. See Inspect variables.
Stack display
Variables pane. See Inspect variables.

.Change the debugger type

Because different debugger tools are required to debug Java/Kotlin code and C/C+
+ code, the Android Studio debugger lets you select which debugger type to use. By
default, Android Studio decides which debugger to use based on which languages it
detects in your project using the Detect Automatically debugger type.

To manually select the debugger in the debug configuration, click Run > Edit
Configurations. You can also select the debugger in the dialog that appears
when you click Run > Attach debugger to Android process.
The debug types available include the following:

Detect Automatically

Select this debug type if you want Android Studio to automatically choose the
best option for the code you are debugging. For example, if you have any C or
C++ code in your project, Android Studio automatically uses the Dual debug
type. Otherwise, Android Studio uses the Java-Only debug type.

Java Only

Select this debug type if you want to debug only code written in Java or
Kotlin. The Java-Only debugger ignores any breakpoints or watches you set
in your native code.

Native Only (available only with C/C++ code)

Select this debug type if you want to use only LLDB to debug your code.
When using this debug type, the Java debugger session view is not available.
By default, LLDB inspects only your native code and ignores breakpoints in
your Java code. If you want to also debug your Java code, switch to either the
Detect Automatically or Dual debug type.

Native debugging only works on devices that meet the following requirements:

• The device supports run-as.

To check whether the device supports run-as, run the following command on
the ADB shell that is connected to your device:

run-as your-package-name pwd

Replace your-package-name with your app's package name. If the device


supports run-as, the command should return without any errors.
• The device has ptrace enabled.
To check whether ptrace is enabled, run the following command on the ADB
shell that is connected to your device:

sysctl [Link].ptrace_scope

If ptrace is enabled, the command will print the value 0 or an an unknown


key error. If ptrace is not enabled, it will print a value other than 0.

Select this debug type if you want to switch between debugging both Java
and native code. Android Studio attaches both the Java debugger and LLDB
to your app process so you can inspect breakpoints in both your Java and
native code without restarting your app or changing your debug configuration.

In figure 2, notice the two tabs to the right of the Debug window title. Because
the app has both Java and C++ code, one tab is for debugging the native
code and the other for debugging Java code, as indicated by -java.
Figure 3. Tab for debugging native code and tab for debugging Java code.

Note: While debugging native code that is optimized by the compiler, you may get
the following warning message:
This function was compiled with optimizations enabled. Some
debugger features may not be available.

Use the system log

The system log shows system messages while you debug your app. These
messages include information from apps running on the device. If you want to use
the system log to debug your app, make sure your code writes log messages and
prints the stack trace for exceptions while your app is in the development phase.

Write log messages in your code

The following example shows how you might add log messages to determine
whether previous state information is available when your activity starts:

Java
import [Link];
...
public class MyActivity extends Activity {
private static final String TAG = [Link]();
...
@Override
public void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState != null) {
Log.d(TAG, "onCreate() Restoring previous state");
/* restore state */
} else {
Log.d(TAG, "onCreate() No saved state available");
/* initialize app */
}
...
}
}

During development, your code can also catch exceptions and write the stack trace
to the system log:

Java
void someOtherMethod() {
try {
...
} catch (SomeException e) {
Log.d(TAG, "someOtherMethod()", e);
}
}

View the system log

You can view and filter debug and other system messages in the Logcat window,
as shown in figure 4. For example, you can see messages when garbage collection
occurs or messages that you add to your app with the Log class.

To use Logcat, start debugging and select the Logcat tab.

For a description of Logcat and its filtering options, see Write and view logs with
Logcat.

Work with breakpoints

Android Studio supports breakpoints that trigger different debugging actions.


There are a several types types of breakpoint:

Line breakpoint

The most common type is a line breakpoint that pauses the execution of your
app at a specified line of code. While paused, you can examine variables,
evaluate expressions, and then continue execution line by line to determine
the causes of runtime errors.

Method breakpoint

A method breakpoint pauses the execution of your app when it enters or exits
a specific method. While paused, you can examine variables, evaluate
expressions, and then continue execution line by line to determine the
causes of runtime errors. When you set a breakpoint on a composable
function, the debugger lists the parameters of the composable and their state
to help identify what changes might have caused the recomposition.
Field breakpoint

A field breakpoint pauses the execution of your app when it reads from or
writes to a specific field.

Exception breakpoint

An exception breakpoint pauses the execution of your app when an


exception is thrown.

You can set conditional breakpoints that will only suspend execution if specific
conditions are met. You can also set logging breakpoints that write to Logcat without
suspending execution. This can help avoid littering your code with log statements.

To add a line breakpoint, proceed as follows:

1. Locate the line of code where you want to pause execution.


2. Click the left gutter along that line of code or place the caret on the line
and press Control+F8 (on macOS, Command+F8).

3. If your app is already running, click Attach debugger to Android process .

Otherwise, to start debugging, click Debug .

A red dot appears next to the line when you set a breakpoint, as shown in figure 5.

When your code execution reaches the breakpoint, Android Studio pauses
execution of your app.

To identify the state of the app, use the tools in the Debugger tab:

• To examine the object tree for a variable, expand it in the Variables view. If the

Variables view is not visible, click Layout Settings and


ensure that variables is checked.
• To advance to the next line in the code without entering a method, click Step

Over .

• To advance to the first line inside a method call, click Step Into .

• To advance to the next line outside the current method, click Step Out .

• To continue running the app normally, click Resume Program .


If your project uses any native code, by default the Detect Automatically debug type
attaches both the Java debugger and LLDB to your app as two separate
processes. You can switch between inspecting Java and C/C++ breakpoints
without restarting your app or changing settings.

When Android Studio deploys your app to your target device, the Debug
window opens with a tab or debug session view for each debugger process, as
shown in figure 6.

1. Android Studio switches to the <your-module> tab when LLDB debugger


encounters a breakpoint in your C/C++ code. The Frames, Variables, and
Watches panes are also available and work exactly as they would if you
were debugging Java code.
Although the Threads pane is not available in the LLDB session view, you can
access your app processes using the list in the Frames pane. Learn more
about these panes in the sections about how to debug window frames and inspect
variables.
2. Android Studio switches to the <your-module>-java tab when the Java
debugger encounters a breakpoint in your Java or Kotlin code.
3. While debugging with LLDB, you can use the LLDB terminal in the LLDB
session view to pass command-line options to LLDB. If you have certain
commands that you would like LLDB to execute each time you start debugging
your app, either just before or just after the debugger attaches to your app
process, you can add those commands to your debug configuration.

While debugging C/C++ code, you can also set special types of breakpoints,
called watchpoints, that can suspend your app process when your app interacts
with a particular block of memory. To learn more, read the section about how to add
watchpoints.

View and configure breakpoints


To view all the breakpoints and configure breakpoint settings, click View
Breakpoints in the Debug window. The Breakpoints window appears, as
shown in figure 7.

The Breakpoints window lets you enable or disable each breakpoint from the list in
the pane. If a breakpoint is disabled, Android Studio doesn't pause your app when it
hits that breakpoint.

Select a breakpoint from the list to configure its settings. You can configure a
breakpoint to be disabled at first and have the system enable it after a different
breakpoint is hit. You can also configure whether a breakpoint should be disabled
after it is hit. To set a breakpoint for any exception, select Exception Breakpoints in
the list of breakpoints.

To temporarily disable all breakpoints, click Mute Breakpoints in the Debug


window. Click again to re-enable.

Debug window frames

In the Debugger window, the Frames pane lets you inspect the stack frame that
caused the current breakpoint to be hit. This enables you to navigate and
examine the stack frame and also inspect the list of threads in your Android app.

To select a thread, use the thread selector menu and view its stack frame. Click the
elements in the frame to open the source in the editor. You can also customize the
thread presentation and export the stack frame as discussed in the Examine
Frames guide.

Inspect variables

In the Debugger window, the Variables pane lets you inspect variables when the
system stops your app on a breakpoint and you select a frame from the Frames
pane. The Variables pane also lets you evaluate ad hoc expressions using
static methods and/or variables available within the selected frame.

To add an expression to the object tree (while the application is being debugged):

1. Enter the expression to watch or display


2. Click Add to watches or press Enter to evaluate the expression once.

Alternatively, if the object tree contains the expression you want to watch, you can
drag it to the top of the tree to add it as a watched expression.

Watched expressions will update when breakpoints are hit or you step through
your code.

Evaluated expressions will remain displayed at the top of the object tree until you
manually evaluate another expression or step through your code.

To remove a watched expression from the object tree, right-click the expression and
then click Remove Watch.

Add watchpoints

While debugging C/C++ code, you can set special types of breakpoints,
called watchpoints, that can suspend your app process when your app interacts
with a particular block of memory. For example, if you set two pointers to a block of
memory and assign a watchpoint to it, using either pointer to access that block of
memory triggers the watchpoint.

In Android Studio, you can create a watchpoint during runtime by selecting a


specific variable, but LLDB assigns the watchpoint to only the block of memory the
system allocates to that variable, not the variable itself. This is different from adding
a variable to the Watches pane, which enables you to observe the value of a
variable but doesn’t let you suspend your app process when the system reads or
changes its value in memory.
To set a watchpoint, you must meet the following requirements:

• Your target physical device or emulator uses an x86 or x86_64 CPU. If your device uses an
ARM CPU, then you must align the boundary of your variable's address in memory to either
4 bytes, for 32-bit processors, or 8 bytes, for 64-bit processors. To align a variable in your
native code, specify __attribute__((aligned(num_bytes))) in the variable deceleration, as shown
below:

// For a 64-bit ARM processor


int my_counter __attribute__((aligned(8)));

• You have assigned three or fewer watchpoints already. Android Studio only supports up
to four watchpoints on x86 or x86_64 target devices. Other devices may support fewer
watchpoints.

Note: When debugging your app with 32-bit ARM ABIs, adding a watchpoint or hovering over
variables inside the code to investigate their values may cause a crash. As a workaround, debug
using 64-bit ARM, x86, or x86_64 binaries. This issue will be fixed in an upcoming Android
Studio release.

If you meet the requirements, you can add a watchpoint as follows:

1. While your app is suspended on a breakpoint, navigate to the Variables pane in your LLDB
session view.

2. Right-click a variable that occupies the block of memory you want to track
and select Add Watchpoint.

3. A dialog to configure your watchpoint appears, as shown in figure 9.


Configure your watchpoint with the following options:
• Enabled: Deselect this option if you want to tell Android Studio to ignore the
watchpoint until you change the setting. Android Studio saves your watchpoint
so you can access it later.
• Suspend: By default, the Android system suspends your app process when it
accesses a block of memory you assign to a watchpoint. Deselect this option if
you don’t want this behavior. This reveals additional options you can use to
customize behavior when the system interacts with your watchpoint: Log
message to console and Remove when hit.
• Access Type: Select whether your app should trigger your watchpoint when it tries
to Read or Write to the block of memory the system allocates to the variable. To
trigger your watchpoint on either a read or a write, select Any.
4. Click Done.

To view all your watchpoints and configure watchpoint settings, click View
Breakpoints in the Debug window. The Breakpoints dialog appears, as shown
in figure 10.

After you add your watchpoint, click Resume Program in the Debug window to
resume your app process.

.
EXPERIMENT-9

Aim: Deploying Android Apps


1. Create a signed APK for deployment.
2. Install and run the app on physical devices and emulators.
[Link] the app to the Google Play Store.

Android Studio allows you to create two kinds of APK files.

First are the debug APK files that are generated solely for testing purposes. They
will run on your Android mobile. However, they cannot be uploaded to the Play
Store or made available to the public.

Secondly, you can generate signed APK files. Signed APK files come in handy
when you've tested your application and it is ready to be uploaded on the Play Store
and released to the general [Link] tutorial will show you how to create an
Android app by generating APK files using Android [Link] things first: open up
a project file in Android Studio. If you don’t have a project file yet, simply create
a New Project.

Creating an APK file


Generating a debug APK file is easy and is a matter of just a few clicks.

First, open up your project or application that you want to import into an APK file.
Then, select Build > Build Bundle(s)/APK(s) > Build APK(s) from the toolbar
menu.

Android Studio will take a few moments to generate an APK file.


Once the APK build is complete, you’ll receive a notification on the bottom right
corner of your screen. From that notification, select Locate and you will be led to the
APK file location.

If you miss the notification, you can still locate the APK file in the following path
within your project folder: app/build/outputs/apk/debug. The file is named app-
[Link] by default.

Creating a Signed APK File


To generate a signed APK file, open the Build menu from the toolbar
and select Generate Signed Bundle/APK.
This opens up a screen where you have to select between creating an Android App
Bundle and creating an APK file. Check the APK radio button and proceed to the
next window.

In the next window, you will be shown the module (your application) for which the
APK file is being generated. You’ll be asked about your Key store path, Key store
password, Key alias, and the Key password.

Creating a New Key Store


Assuming that this is the first time you’re creating a Signed APK file, you will have
to create a new key store.

Keys are used by the developer to access their application once it has been
uploaded to the Play Store. The need for the keys usually arises when you have
to update your application. All of the keys are stored in the key store.
Both the key store and the keys are protected by passwords of their own. The
passwords should be at least six characters in length. Also, it is a good practice to
keep multiple copies of your keys since they are your only gateway to your
application. If the key is lost, you will not be able to access your application or update
it.

Creating your own app requires you to create a new key store. To do so,
select Create new. You will find it underneath the input field where you enter the key
store path.

You will then be redirected to a new window.

In the new window, enter the path for your new key store, and then enter a
password to protect it.

In the same window, you will also be setting a new key for your application. Enter an
identity for your key in the key alias field and then enter a password for it.

You can keep the same password as that of your key store, but it's a good practice to
give a new password to each of your keys. The same goes for the key alias.

The next field defines the validity of your application. This is the duration after which
the key to your application will expire, leaving your application inaccessible.
The default validity for a key is 25 years.

For each key that you generate, you’re given a certificate that contains all the
information about you and your company. You don't necessarily have to fill in all
the details—just choose the ones you think should go on your certificate. A key will
still be generated, even without filling in each field of the certificate.

Finishing Up
Once you have filled in the details for the certificate, select OK. You will then
be directed back to the Generate Signed Bundle or APK screen.

Here, all of the fields will now be pre-filled for you. Go through all the details to stay
on the safe side. Then, select Next.

On the last screen, you will now be able to see the destination of your Signed
APK file. Below that, you will see two more options: Debug and [Link]
is used when the application is still in the testing phase. Since your application has
passed the testing phase and is ready for deployment, select Release.

You will be notified by Android Studio once the APK build is finished

You might also like