Practical Exam of MAD
Practical Exam of MAD
LinearLayout:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ECDCC9"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"
android:textColor="#6F686D"
android:text="Name: Jovita Manoj Reejhsinghani"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#6F686D"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"
android:text="Age: 18"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#6F686D"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"
android:text="Mobile Number: 9766697331"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#6F686D"
android:layout_marginLeft="15dp"
android:layout_marginBottom="15dp"
android:text="Program by Jovita Reejhsinghani, Roll No 10"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
MainActivity.java
package com.vesp.exp5_1;
import android.os.Bundle;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
AbsoluteLayout:
activity_main.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="100dp"
android:layout_marginBottom="10dp"
android:layout_x="107dp"
android:layout_y="259dp"
android:text="Name: Jovita Manoj Reejhsinghani"
android:textColor="#6F686D"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"
android:layout_x="170dp"
android:layout_y="298dp"
android:text="Age: 18"
android:textColor="#6F686D"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"
android:layout_x="113dp"
android:layout_y="336dp"
android:text="Mobile Number: 9766697331"
android:textColor="#6F686D"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginBottom="15dp"
android:layout_x="69dp"
android:layout_y="393dp"
android:text="Program by Jovita Reejhsinghani, Roll No 10"
android:textColor="#6F686D"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</AbsoluteLayout>
MainActivity.java
package com.vesp.exp5_2;
import android.os.Bundle;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets)
-> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right,
systemBars.bottom);
return insets;
});
}
}
b) List and explain any two layers of Android architecture
Android operating system is a stack of software components which is roughly divided into
five sections and four main layers as covered in the diagram above.
It includes operating systems, middleware and important applications.
Each layer in the architecture provides different services.
1. Application
2. Application Framework
3. Libraries
4. Android Runtime.
5. Linux Kernel.
1. Application:
All applications in the application layer are written in Java Language. The various core
applications that an android device provides include
● Maps
● Browser
● Contacts
3.Linux Kernel:
At the bottom of the layers is the Linux Kernel. This provides a level of abstraction between the
device hardware and it contains all the essential hardware drivers like camera, keypad, display
etc. Also, the kernel handles all the things such as networking and a vast array of device drivers.
Following are the drivers: Display, Camera, Bluetooth, Flash Memory Driver, USB, WiFi,
Keypad driver, Audio Driver, Power Management Driver.
Q2.
a) Develop a program to implement FrameLayout, TableLayout, and RelativeLayout
FrameLayout:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/main"
android:layout_height="match_parent"
android:background="#F4CAE0"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|left"
android:text="Boolean"
android:textSize="20dp"
android:textColor="#291720"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|center"
android:text="Integer"
android:textColor="#291720"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|right"
android:textColor="#291720"
android:text="Character"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|left"
android:textColor="#291720"
android:text="Long"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#291720"
android:text="Double"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|right"
android:textColor="#291720"
android:text="Float"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|left"
android:text="Short Integer"
android:textColor="#291720"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:text="Long Integer"
android:textColor="#291720"
android:textSize="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:textColor="#291720"
android:text="Byte"
android:textSize="20dp"
/>
<TextView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#291720"
android:layout_marginTop="70dp"
android:text="Program By Jovita Reejhsinghani, Roll No. 10”
android:textSize="20dp"
/>
</FrameLayout>
MainActivity.java
package com.vesp.exp6_2;
import android.os.Bundle;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets)
-> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right,
systemBars.bottom);
return insets;
});
}
}
TableLayout:
activity_main.xml
MainActivity.java
package com.vesp.exp6_1;
import android.os.Bundle;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets)
-> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right,
systemBars.bottom);
return insets;
});
}
RelativeLayout:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username:"
android:textSize="18sp" />
<EditText
android:id="@+id/username"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_toEndOf="@id/label"
android:layout_marginStart="10dp"
<Button
android:id="@+id/loginBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:layout_below="@id/username"
android:layout_alignStart="@id/username"
android:layout_marginTop="20dp" />
</RelativeLayout>
MainActivity.java
package com.example.relativelayoutdemo;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
EditText username;
Button loginBtn;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = findViewById(R.id.username);
loginBtn = findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(v -> {
});
}
b) What is OHA and list its members
OHA was formed in Nov 2007.The OHA has approximately 80 member companies, including HTC,
Dell, Intel, Motorola, Qualcomm and Google. The OHA's main product is the Android platform - the
world's most popular smartphone platform.
Q3.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/nameEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Name"
android:layout_marginTop="50dp"
android:padding="12dp"
android:textSize="16sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<EditText
android:id="@+id/ageEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Age"
android:layout_marginTop="20dp"
android:padding="12dp"
android:textSize="16sp"
app:layout_constraintTop_toBottomOf="@id/nameEditText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<EditText
android:id="@+id/phoneEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Phone Number"
android:layout_marginTop="20dp"
android:padding="12dp"
android:textSize="16sp"
app:layout_constraintTop_toBottomOf="@id/ageEditText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<EditText
android:id="@+id/addressEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Address"
android:layout_marginTop="20dp"
android:padding="12dp"
android:textSize="16sp"
app:layout_constraintTop_toBottomOf="@id/phoneEditText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/submitButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Submit"
android:textSize="18sp"
app:layout_constraintTop_toBottomOf="@id/addressEditText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="30dp" />
<TextView
android:id="@+id/nameAgeTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name and Age will be displayed here"
android:textSize="16sp"
android:layout_marginTop="20dp"
app:layout_constraintTop_toBottomOf="@id/submitButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<TextView
android:id="@+id/phoneAddressTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone and Address will be displayed here"
android:textSize="16sp"
android:layout_marginTop="10dp"
app:layout_constraintTop_toBottomOf="@id/nameAgeTextView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.vesp.exp7_2;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameEditText = findViewById(R.id.nameEditText);
ageEditText = findViewById(R.id.ageEditText);
phoneEditText = findViewById(R.id.phoneEditText);
addressEditText = findViewById(R.id.addressEditText);
submitButton = findViewById(R.id.submitButton);
nameAgeTextView = findViewById(R.id.nameAgeTextView);
phoneAddressTextView = findViewById(R.id.phoneAddressTextView);
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = nameEditText.getText().toString();
String age = ageEditText.getText().toString();
String phone = phoneEditText.getText().toString();
String address = addressEditText.getText().toString();
b) What is the need of Android?
Android is an open-source mobile operating system that allows developers to build powerful and
user-friendly applications. It provides a flexible development environment, supports multiple
devices, and ensures wide app distribution through the Play Store.
Q4.
activity_main.xml
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher_foreground"
android:contentDescription="Image Button" />
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="ON"
android:textOff="OFF" />
</LinearLayout>
MainActivity.java
package com.example.myapp;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity;
Button button1;
ImageButton imageButton1;
ToggleButton toggleButton1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
imageButton1 = findViewById(R.id.imageButton1);
toggleButton1 = findViewById(R.id.toggleButton1);
button1.setOnClickListener(v ->
Toast.makeText(this, "Button Clicked", Toast.LENGTH_SHORT).show());
imageButton1.setOnClickListener(v ->
Toast.makeText(this, "ImageButton Clicked", Toast.LENGTH_SHORT).show());
Android Studio – The official IDE for building Android apps, offering powerful code editing,
debugging, and UI design tools.
ADB (Android Debug Bridge) – A command-line tool that allows communication between your
development machine and Android devices.
SDK Manager – Helps download and manage different versions of Android SDK packages.
AVD Manager – Used to create and manage virtual devices (emulators) for testing apps.
Gradle – A build automation system that compiles your code and packages it into an APK.
Lint – Analyzes your code for bugs, performance issues, and coding standard violations.
ProGuard – Optimizes and obfuscates your code to reduce APK size and protect it from
reverse engineering.
Q5.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Login Window"
android:textSize="24sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/username"
android:hint="Enter Username"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/password"
android:hint="Enter Password"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/loginBtn"
android:text="Login"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
package com.vesp.pr_5;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
loginBtn = findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(v -> {
String user = username.getText().toString();
String pass = password.getText().toString();
ToggleButton:
● You can set android:textOn and android:textOff for the two states.
● Commonly used to control settings like Wi-Fi or visibility (e.g., show/hide password).
Q6.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Horizontal"
android:max="100"
android:progress="0" />
<Button
android:id="@+id/startBtn"
android:text="Start Progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" />
</LinearLayout>
MainAcitvity.java
package com.vesp.pr_6;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ProgressBar;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.progressBar);
startBtn = findViewById(R.id.startBtn);
startBtn.setOnClickListener(v -> {
new Thread(() -> {
for (int i = 0; i <= 100; i++) {
int finalI = i;
runOnUiThread(() -> progressBar.setProgress(finalI));
try {
Thread.sleep(50); // delay to simulate progress
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
});
}
}
b) Enlist the steps to publish the Android application
Android application publishing is a process that makes your Android applications available to
users. Publishing is the last phase of the Android application development process.
1. Open that application project in Android studio and select Build → Generate Signed APK
from your Android studio.
2. Enter your key store path,key store password,key alias and key password to protect your
application.
3. Go to Google Play Console and login with existing google ID if you have any, otherwise you
can create a new Google ID and then register.
4. Accept the Developer agreement (Terms and Conditions)
5. Complete the registration fee process by making a one time payment of $25.
6. Complete Account and application details
7. After registration, upload the release-ready APK of your application.
Q7.
activity_main.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="200dp"/>
<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:numColumns="4"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"/>
<ImageView
android:id="@+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/ic_launcher_foreground"
android:layout_gravity="center"/>
</LinearLayout>
</ScrollView>
MainActivity.java
package com.vesp.pr_7;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize ImageView (you can use your own image resource here)
ImageView imageView = findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.ic_launcher_foreground); // Update with your
image resource
}
}
b) Define Service lifecycle in Android
A Service in Android runs in the background to perform long-running operations. The lifecycle
of a Service involves the following key methods:
2. onStartCommand()
3. onBind()
4. onUnbind()
5. onDestroy()
Q8.
a) Develop a program to implement new activity using Explicit Intent and Implicit Intent
Here’s a simple Android program that demonstrates both Explicit Intent and Implicit Intent by
launching a new activity and opening a website.
MainActivity.java – Uses both intents:
package com.example.intentsdemo;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnExplicit = findViewById(R.id.btnExplicit);
btnImplicit = findViewById(R.id.btnImplicit);
// Explicit Intent
btnExplicit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent explicitIntent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(explicitIntent);
}
});
// Implicit Intent
btnImplicit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent implicitIntent = new Intent(Intent.ACTION_VIEW);
implicitIntent.setData(Uri.parse("https://www.google.com"));
startActivity(implicitIntent);
}
});
}
}
SecondActivity.java
package com.example.intentsdemo;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">
<Button
android:id="@+id/btnExplicit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Explicit Intent" />
<Button
android:id="@+id/btnImplicit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Implicit Intent"
android:layout_marginTop="16dp"/>
</LinearLayout>
activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to Second Activity!"
android:textSize="20sp" />
</LinearLayout>
<activity android:name=".SecondActivity"></activity>
b) Give the syntax of the following components:
● Activities
● Services
● ContentProviders
● BroadcastReceiver
1. Activities
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
2. Services
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Service logic here
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null; // For unbound services
}
}
3. ContentProviders
public class MyContentProvider extends ContentProvider {
@Override
public boolean onCreate() {
return true;
}
@Override
public Cursor query(...) { ... }
@Override
public Uri insert(...) { ... }
@Override
public int delete(...) { ... }
@Override
public int update(...) { ... }
@Override
public String getType(Uri uri) { ... }
}
BroadcastReceiver
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Handle broadcast message
}
}
Q9.
a) Develop a program to implement Sensors
[ACCELEROMETER]
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
android:gravity="center">
<TextView
android:id="@+id/sensorData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Accelerometer Data"
android:textSize="18sp" />
</LinearLayout>
MainActivity.Java
package com.vesp.pr_9;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorData = findViewById(R.id.sensorData);
@Override
protected void onResume() {
super.onResume();
// Register Listener
if (accelerometer != null) {
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
@Override
protected void onPause() {
super.onPause();
// Unregister Listener
sensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Not used in this example
}
}
b) Differentiate between JVM and DVM
Q10.
AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" android:required="true" />
<application
android:requestLegacyExternalStorage="true"
... >
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
res/xml/file_paths.xml
Activity_main.xml
<ImageView
android:id="@+id/imageView"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_marginTop="20dp"
android:scaleType="centerCrop"
android:contentDescription="Captured Image" />
</LinearLayout>
MainActivity.java
package com.example.cameraapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
Button btnCapture;
ImageView imageView;
String currentPhotoPath;
btnCapture = findViewById(R.id.btnCapture);
imageView = findViewById(R.id.imageView);
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
getPackageName() + ".fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
currentPhotoPath = image.getAbsolutePath();
return image;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
b) List and explain different types of Android layouts
Android provides various layout types to arrange UI components (views) in an activity. These
layouts define the structure and positioning of child views.
1. LinearLayout
2. RelativeLayout (Deprecated)
● Allows flexibility like placing a view below, beside, or aligned with another view.
3. ConstraintLayout
4. FrameLayout
5. TableLayout
6. GridLayout
● You can specify row and column number for each view.
Conclusion:
Each layout has its own advantages. For simple UIs, LinearLayout is useful. For complex and
performance-optimized layouts, ConstraintLayout is preferred.
Q11.
AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">
<Button
android:id="@+id/btnEnableBluetooth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enable Bluetooth" />
<Button
android:id="@+id/btnPairedDevices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Paired Devices"
android:layout_marginTop="10dp" />
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp" />
</LinearLayout>
MainActivity.java
package com.example.bluetoothapp;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
BluetoothAdapter bluetoothAdapter;
Button btnEnableBluetooth, btnPairedDevices;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnEnableBluetooth = findViewById(R.id.btnEnableBluetooth);
btnPairedDevices = findViewById(R.id.btnPairedDevices);
listView = findViewById(R.id.listView);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth not supported", Toast.LENGTH_SHORT).show();
finish();
}
btnEnableBluetooth.setOnClickListener(v -> {
if (!bluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
} else {
Toast.makeText(this, "Bluetooth is already enabled", Toast.LENGTH_SHORT).show();
}
});
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
deviceList.add(device.getName() + "\n" + device.getAddress());
}
} else {
deviceList.add("No paired devices found");
}
b) Explain View, ViewGroups, and Activities
In Android development, View, ViewGroup, and Activity are the basic building blocks of the
user interface (UI) and app lifecycle.
1. View
● It represents a widget or control that the user can see and interact with.
Example:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
2. ViewGroup
● It defines how child views are arranged and displayed on the screen.
Common ViewGroups:
● LinearLayout
● RelativeLayout
● ConstraintLayout
● FrameLayout
Example:
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
3. Activity
● It contains the UI layout (views and view groups) and handles user interactions.
● Each activity has its own lifecycle (onCreate, onStart, onResume, etc.)
Example:
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Q12.
MyDatabaseHelper.java
package com.example.sqliteasync;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.ContentValues;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.AsyncTask;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
EditText editText;
Button btnInsert;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editTextName);
btnInsert = findViewById(R.id.btnInsert);
btnInsert.setOnClickListener(v -> {
String name = editText.getText().toString().trim();
if (!name.isEmpty()) {
new InsertStudentTask(MainActivity.this).execute(name);
} else {
Toast.makeText(MainActivity.this, "Enter a name", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected Void doInBackground(String... names) {
dbHelper.insertStudent(names[0]);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(context, "Data inserted", Toast.LENGTH_SHORT).show();
}
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name" />
<Button
android:id="@+id/btnInsert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Insert Name"
android:layout_marginTop="10dp" />
</LinearLayout>
b) Describe importance of strings.xml file
In Android development, the strings.xml file is used to store all the text (string) resources
that appear in the user interface. It is located inside the res/values/ directory.
All the user-visible strings are defined in one place. This makes it easier to manage and update
the text content of the app.
2. Supports Localization:
The strings.xml file allows translation of the app into different languages by creating
separate files like values-hi/strings.xml for Hindi, values-fr/strings.xml for
French, etc.
Instead of hardcoding strings directly in Java or XML layouts, we use references like
@string/app_name. This keeps the code clean and easy to understand.
4. Avoids Duplication:
If a string is used in multiple places, we can define it once in strings.xml and reuse it, which
avoids repetition.
5. Required for App Configuration:
Important values like the application name are stored here, which are used automatically by the
system.
Example:
<resources>
<string name="submit">Submit</string>
</resources>
Conclusion:
The strings.xml file is very important in Android as it helps in managing strings efficiently,
supports multiple languages, and keeps the code organized and reusable.
Q13.
● Check username/password
MainActivity.java
package com.example.loginapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editUsername = findViewById(R.id.editUsername);
editPassword = findViewById(R.id.editPassword);
btnLogin = findViewById(R.id.btnLogin);
textResult = findViewById(R.id.textResult);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String user = editUsername.getText().toString();
String pass = editPassword.getText().toString();
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<EditText
android:id="@+id/editUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username" />
<EditText
android:id="@+id/editPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"
android:layout_marginTop="10dp" />
<Button
android:id="@+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_marginTop="15dp" />
<TextView
android:id="@+id/textResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="18sp"
android:layout_marginTop="20dp" />
</LinearLayout>
Q14.
a) Create login application where Login button is disabled until username and password are
validated
MainActivity.java
package com.example.loginapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editUsername = findViewById(R.id.editUsername);
editPassword = findViewById(R.id.editPassword);
btnLogin = findViewById(R.id.btnLogin);
textResult = findViewById(R.id.textResult);
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count)
{
validateInput();
}
@Override
public void afterTextChanged(Editable editable) {}
});
editPassword.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int
after) {}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count)
{
validateInput();
}
@Override
public void afterTextChanged(Editable editable) {}
});
Activity_main.xml
<EditText
android:id="@+id/editPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"
android:layout_marginTop="10dp" />
<Button
android:id="@+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_marginTop="15dp"
android:enabled="false" /> <!-- Initially disabled -->
<TextView
android:id="@+id/textResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="18sp"
android:layout_marginTop="20dp" />
</LinearLayout>
Q15.
● Send SMS
● Receive SMS
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.smsapp">
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.DayNight">
<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>
MainActivity.java
package com.example.smsapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phoneNumberEditText = findViewById(R.id.phoneNumberEditText);
messageEditText = findViewById(R.id.messageEditText);
sendButton = findViewById(R.id.sendButton);
sendButton.setOnClickListener(v -> {
String phoneNumber = phoneNumberEditText.getText().toString();
String message = messageEditText.getText().toString();
package com.example.smsapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.widget.Toast;
@Override
public void onReceive(Context context, Intent intent) {
// Get the SMS message from the Intent
Bundle bundle = intent.getExtras();
SmsMessage[] messages = null;
String strMessage = "";
if (bundle != null) {
// Retrieve the SMS messages
Object[] pdus = (Object[]) bundle.get("pdus");
messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
strMessage += "From: " + messages[i].getOriginatingAddress() + "\n";
strMessage += "Message: " + messages[i].getMessageBody() + "\n\n";
}
// Display the received message as a Toast
Toast.makeText(context, "Received SMS: " + strMessage,
Toast.LENGTH_LONG).show();
}
}
}
Activity_main.xml
<EditText
android:id="@+id/phoneNumberEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Phone Number"
android:inputType="phone"/>
<EditText
android:id="@+id/messageEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Message"
android:inputType="textMultiLine"
android:layout_marginTop="10dp"/>
<Button
android:id="@+id/sendButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send SMS"
android:layout_marginTop="15dp"/>
</LinearLayout>
Q16.
dependencies {
implementation 'com.sun.mail:android-mail:1.6.0'
implementation 'com.sun.mail:android-activation:1.6.0'
MainActivity.java
package com.example.sms;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditTextTo = findViewById(R.id.edit_text_to);
mEditTextSubject = findViewById(R.id.edit_text_subject);
mEditTextMessage = findViewById(R.id.edit_text_message);
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="To:"
android:textAppearance="@style/TextAppearance.AppCompat.Large" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edit_text_to"
android:inputType="textEmailAddress" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subject:"
android:textAppearance="@style/TextAppearance.AppCompat.Large" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edit_text_subject"
android:inputType="textEmailSubject" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Message:"
android:textAppearance="@style/TextAppearance.AppCompat.Large" />
<EditText
android:id="@+id/edit_text_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="start|top"
android:lines="10" />
<Button
android:id="@+id/button_send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send" />
</LinearLayout>
Q17.
Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/google_map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Strings.xml
<resources>
<string name="app_name">MapApp</string>
<string name="map_key"
translatable="false">AIzaSyB_qsP8AOP_P0MdlPz-48TDaJYjTP3vbjo</string>
</resources>
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.map">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:label="Map App"
android:theme="@android:style/Theme.DeviceDefault">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/map_key" />
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
build.gradle.kts(:app)
plugins {
id("com.android.application")
}
android {
namespace = "com.example.map"
compileSdk = 33
defaultConfig {
applicationId = "com.example.map"
minSdk = 21
targetSdk = 33
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
}
dependencies {
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.9.0")
implementation("com.google.android.gms:play-services-maps:18.1.0")
implementation("com.google.android.gms:play-services-location:21.0.1")
}
MainActivity.java
package com.example.map;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
FusedLocationProviderClient fusedLocationProviderClient;
Location currentLocation;
private static final int REQUEST_CODE = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fetchLastLocation();
}
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE);
return;
}
@Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("I am here");
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
googleMap.addMarker(markerOptions);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE && grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
fetchLastLocation();
}
}
}