0% found this document useful (0 votes)
13 views35 pages

Mad Cheet

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 35

The android project contains different types of app modules, source code files,

and resource files. We will explore all the folders and files in the android app.

1. Manifests Folder
2. Java Folder
3. res (Resources) Folder
 Drawable Folder
 Layout Folder
 Mipmap Folder
 Values Folder
4. Gradle Scripts

Manifests Folder
Manifests folder contains AndroidManifest.xml for creating our android
application. This file contains information about our application such as the
Android version, metadata, states package for Kotlin file, and other application
components. It acts as an intermediator between android OS and our
application.

Java folder
The Java folder contains all the java and Kotlin source code (.java) files that we
create during the app development, including other Test files. If we create any
new project using Kotlin, by default the class file MainActivity.kt file will
create automatically under the package name

Resource (res) folder


The resource folder is the most important folder because it contains all the non-
code sources like images, XML layouts, and UI strings for our android
application.

res/drawable folder
It contains the different types of images used for the development of the
application. We need to add all the images in a drawable folder for the
application development.

res/layout folder
The layout folder contains all XML layout files which we used to define the
user interface of our application. It contains the activity_main.xml file.

Gradle Scripts folder


Gradle means automated build system and it contains a number of files that are
used to define a build configuration that can be applied to all modules in our
application. In build.gradle (Project) there are buildscripts and in build.gradle
(Module) plugins and implementations are used to build configurations that can
be applied to all our application modules.
Java Code -:

import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private ImageButton myImageButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

myImageButton = findViewById(R.id.myImageButton);
myImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Perform some action when the image button is clicked
}
});
}
}

30. Explain check box with the help of a program.


32. Develop an android application for picking time and date in android app.

Xml code - :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<TimePicker
android:id="@+id/myTimePicker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" />

</LinearLayout>

Java code -:

import android.os.Bundle;
import android.widget.TimePicker;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

private TimePicker myTimePicker;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

myTimePicker = findViewById(R.id.myTimePicker);

// Set the current time as the default value for the time picker
Calendar calendar = Calendar.getInstance();
myTimePicker.setHour(calendar.get(Calendar.HOUR_OF_DAY));
myTimePicker.setMinute(calendar.get(Calendar.MINUTE));

// Set an onTimeChangedListener to respond to changes in the time picker


myTimePicker.setOnTimeChangedListener(new
TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker timePicker, int hourOfDay, int
minute) {
// Display a toast message with the selected time value
String selectedTime = hourOfDay + ":" + minute;
Toast.makeText(MainActivity.this, "Selected time: " + selectedTime,
Toast.LENGTH_SHORT).show();
}
});
}
}
33. Define intent. Describe its uses.

In Android, an Intent is a messaging object that is used to request an action from


another component of the Android system, such as an activity, service, or
broadcast receiver. Intents can be used to start new activities, pass data between
activities, start services, and broadcast events. Here are some common uses for
Intent in Android:

 Starting a new activity: You can use an Intent to start a new activity in
your application, or even in another application. This is commonly used
to transition between different screens or sections of an app, or to launch
a third-party app for a specific task.

 Passing data between activities: You can use an Intent to pass data
between activities, such as user input or data retrieved from a web
service. This data can be simple values like strings and integers, or more
complex objects like arrays or custom classes.

 Starting a service: You can use an Intent to start a service in your


application. Services run in the background and can perform long-running
operations, such as downloading data or playing music.

 Broadcasting events: You can use an Intent to broadcast an event to other


components of the Android system, such as a notification that a new data
is available or the battery is low.

// Create an Intent object to start a new activity


Intent intent = new Intent(MainActivity.this, SecondActivity.class);
// Add any extra data to the intent, if necessary
intent.putExtra("key", "value");

// Start the new activity


startActivity(intent);

34. Explain the types of intent with individual example.

In Android, there are two types of Intent: explicit and implicit. Here's an
explanation of each type with a program example:

Explicit Intent: An explicit intent is used to start a specific activity within your
own application. The target activity is identified by its class name.
Here's an example of how to use an explicit Intent to start a new activity:
// Create an explicit intent to start the SecondActivity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);

// Start the SecondActivity


startActivity(intent);

Implicit Intent: An implicit intent is used to start an activity outside of your


own application or to start an activity within your application that is not
explicitly defined. The target activity is identified by an action or a set of data.
Here's an example of how to use an implicit Intent to start the browser
application:
// Create an implicit intent to view a webpage
Uri webpage = Uri.parse("http://www.google.com");
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
// Verify that the intent will resolve to an activity
if (intent.resolveActivity(getPackageManager()) != null) {
// Start the activity
startActivity(intent);
}

35. Write a program to create a calculator application and display the result on
second activity using explicit intent.

36. Write a program to demonstrate the use of implicit intent.

Refer question no. 34

37. Explain intent filter with the help of a diagram.

In Android, an IntentFilter is a component that is used to declare the types of


intents that an activity, service, or broadcast receiver can handle. By defining an
IntentFilter, you are telling the Android system which types of intents your
component can respond to.

Here's an example of how to use an IntentFilter in Android:


<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
<data android:scheme="https" />
</intent-filter>
</activity>

38. Explain activity life cycle.

In Android, an activity is referred to as one screen in an application. It is very


similar to a single window of any desktop application. An Android app consists
of one or more screens or activities.
Each activity goes through various stages or a lifecycle and is managed by
activity stacks. So when a new activity starts, the previous one always remains
below it. There are four stages of an activity.
1. If an activity is in the foreground of the screen i.e at the top of the stack, then
it is said to be active or running. This is usually the activity that the user is
currently interacting with.
2. If an activity has lost focus and a non-full-sized or transparent activity has
focused on top of your activity. In such a case either another activity has a
higher position in multi-window mode or the activity itself is not focusable in
the current window mode. Such activity is completely alive.
3. If an activity is completely hidden by another activity, it is stopped or hidden.
It still retains all the information, and as its window is hidden thus it will
often be killed by the system when memory is needed elsewhere.
4. The system can destroy the activity from memory by either asking it to finish
or simply killing its process. When it is displayed again to the user, it must be
completely restarted and restored to its previous state.
For each stage, android provides us with a set of 7 methods that have their own
significance for each stage in the life cycle. The image shows a path of
migration whenever an app switches from one state to another.

1. onCreate()
It is called when the activity is first created. This is where all the static work is
done like creating views, binding data to lists, etc. This method also provides a
Bundle containing its previous frozen state, if there was one.

2. onStart()
It is invoked when the activity is visible to the user. It is followed by
onResume() if the activity is invoked from the background. It is also invoked
after onCreate() when the activity is first started.

3. onRestart()
It is invoked after the activity has been stopped and prior to its starting stage
and thus is always followed by onStart() when any activity is revived from
background to on-screen.

4. onResume()
It is invoked when the activity starts interacting with the user. At this point, the
activity is at the top of the activity stack, with a user interacting with it. Always
followed by onPause() when the activity goes into the background or is closed
by the user.

5. onPause()
It is invoked when an activity is going into the background but has not yet been
killed. It is a counterpart to onResume(). When an activity is launched in front
of another activity, this callback will be invoked on the top activity (currently
on screen). The activity, under the active activity, will not be created until the
active activity’s onPause() returns, so it is recommended that heavy processing
should not be done in this part.

6. onStop()
It is invoked when the activity is not visible to the user. It is followed
by onRestart() when the activity is revoked from the background, followed by
onDestroy() when the activity is closed or finished, and nothing when the
activity remains on the background only. Note that this method may never be
called, in low memory situations where the system does not have enough
memory to keep the activity’s process running after its onPause() method is
called.

7. onDestroy()
The final call received before the activity is destroyed. This can happen either
because the activity is finishing (when finish() is invoked) or because the
system is temporarily destroying this instance of the activity to save space. To
distinguish between these scenarios, check it with isFinishing() method.

39. Explain broadcast with its types.

In Android, a broadcast is a message that is sent by the system or an application


to other applications, notifying them of a certain event or state change.
Broadcasts can be used to trigger actions in other applications or to inform them
of a change in the system state.

There are two types of broadcasts in Android:

System Broadcasts: These are broadcasts that are sent by the system to notify
applications of system-level events, such as the device being restarted or the
battery level changing.
Here are some examples of system broadcasts:

ACTION_BATTERY_CHANGED: This broadcast is sent when the battery


level or charging state changes.
ACTION_BOOT_COMPLETED: This broadcast is sent when the device
finishes booting up.
ACTION_TIMEZONE_CHANGED: This broadcast is sent when the device's
timezone is changed.
Custom Broadcasts: These are broadcasts that are sent by applications to notify
other applications of events that are specific to the application.
// Create an intent to send a custom broadcast
Intent intent = new
Intent("com.example.ACTION_CUSTOM_BROADCAST");
intent.putExtra("message", "Hello, world!");

// Send the broadcast


sendBroadcast(intent);

Other applications can receive this broadcast by registering a BroadcastReceiver


with an IntentFilter that matches the custom action:

// Create a BroadcastReceiver to handle the custom broadcast


private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get the message from the intent
String message = intent.getStringExtra("message");

// Do something with the message


Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
};
// Register the BroadcastReceiver
IntentFilter filter = new
IntentFilter("com.example.ACTION_CUSTOM_BROADCAST");
registerReceiver(receiver, filter);

40. Explain content provider with the help of a diagram.

In Android, Content Providers are a very important component that serves the
purpose of a relational database to store the data of applications. The role of the
content provider in the android system is like a central repository in which data
of the applications are stored, and it facilitates other applications to securely
access and modifies that data based on the user requirements. Android system
allows the content provider to store the application data in several ways. Users
can manage to store the application data like images, audio, videos, and
personal contact information by storing them in SQLite Database , in files, or
even on a network. In order to share the data, content providers have certain
permissions that are used to grant or restrict the rights to other applications to
interfere with the data.

Operations in Content Provider


Four fundamental operations are possible in Content Provider
namely Create, Read, Update, and Delete. These operations are often termed
as CRUD operations.
 Create: Operation to create data in a content provider.
 Read: Used to fetch data from a content provider.
 Update: To modify existing data.
 Delete: To remove existing data from the storage.

Creating a Content Provider


Following are the steps which are essential to follow in order to create a
Content Provider:

 Create a class in the same directory where the that MainActivity file resides
and this class must extend the ContentProvider base class.
 To access the content, define a content provider URI address.
 Create a database to store the application data.
 Implement the six abstract methods of ContentProvider class.
 Register the content provider in AndroidManifest.xml file
using <provider> tag.

41. Develop an application with fragments.

42. Define service. What do you mean by started and bound service.

In Android, a Service is a component that runs in the background to perform


long-running operations or to handle asynchronous tasks. A Service can run
even when the application is not visible to the user, and can continue running
even if the user switches to another application.

Here are some characteristics of a Service in Android:

 A Service does not have a user interface.


 A Service runs in the same process as the application by default, but can
run in a separate process if needed.
 A Service can be started by another component (such as an activity) using
the startService method, or it can be bound to by another component
using the bindService method.
 A Service can communicate with other components using various
mechanisms, such as broadcast intents, callbacks, or Messenger objects.

In Android, there are two types of services:

Started Service: A started service is a service that is started using the


startService() method. A started service runs in the background even if the
component that started it is destroyed, and can continue to run even if the device
is restarted. The service must be explicitly stopped using the stopService()
method or by calling stopSelf() from within the service.

Bound Service: A bound service is a service that is bound to by another


component using the bindService() method. A bound service provides a client-
server interface, allowing other components to interact with it by calling
methods on a binder object that the service returns when it is bound. A bound
service is destroyed when all of its clients unbind from it.

43. Explain service life cycle.


Refer book

44. Explain multimedia framework.

The Multimedia Framework in Android is a set of software components that


allows developers to easily integrate multimedia capabilities into their
applications. This framework includes various APIs for playing and recording
audio and video, working with images and video streams, and more.

The Multimedia Framework in Android consists of the following components:

 Media Player API: This API allows developers to play audio and video
files, as well as streaming media. It provides a range of features, such as
playback speed control, volume control, and support for various media
formats.

 Media Recorder API: This API allows developers to record audio and
video, as well as capture images. It provides a range of features, such as
video resolution and bitrate control, and support for various media
formats.

 Camera API: This API provides access to the device's camera, allowing
developers to capture images and video. It provides a range of features,
such as autofocus, zoom, and flash control.

 OpenGL ES: This API provides a way for developers to create and
manipulate 3D graphics on Android devices. It provides a range of
features, such as texture mapping, lighting, and animation.
 OpenMAX AL: This API provides a low-level interface for accessing
hardware acceleration for multimedia tasks. It provides a range of
features, such as audio and video decoding and encoding, and supports
various media formats.

 Android NDK: This is a native development kit that allows developers to


write code in C and C++ for use in Android applications. It provides
access to various multimedia APIs, such as OpenMAX AL and OpenGL
ES, and allows for more efficient processing of multimedia data.

The Multimedia Framework in Android provides developers with a powerful set


of tools for integrating multimedia capabilities into their applications. With
these tools, developers can create rich multimedia experiences for their users,
including video and audio playback, image and video capture, and 3D graphics.

45. Write a program to create a camera app.

public class MainActivity extends AppCompatActivity {


private static final int REQUEST_IMAGE_CAPTURE = 1;
private ImageView mImageView;
private Button mButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mImageView = findViewById(R.id.image_view);
mButton = findViewById(R.id.button);

mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
}

private void dispatchTakePictureIntent() {


Intent takePictureIntent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent,
REQUEST_IMAGE_CAPTURE);
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode ==
RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
}

46. Write a program to create a sms app.

Xml code -:

<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
>

<TextView
android:layout_gravity="center"
android:textSize="30dp"
android:layout_marginTop="20dp"
android:text="SMS Sending App"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>

<EditText
android:padding="20dp"
android:id="@+id/mobilenumber"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:hint="Enter phone number"
android:layout_width="match_parent"
android:layout_height="wrap_content"></EditText>

<EditText
android:padding="20dp"
android:id="@+id/message"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:hint="Enter your message"
android:layout_width="match_parent"
android:layout_height="wrap_content"></EditText>

<Button
android:layout_margin="20dp"
android:padding="20dp"
android:text="Send SMS"
android:id="@+id/send_btn"
android:textSize="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"></Button>

</LinearLayout>
Java Code -:

package com.example.smsapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

Button send_btn;
EditText send_phonenumber;
EditText send_message;
String phoneno;
String mymessage;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

send_btn = findViewById(R.id.send_btn);
send_message = findViewById(R.id.message);
send_phonenumber = findViewById(R.id.mobilenumber);

send_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
phoneno = send_phonenumber.getText().toString();
mymessage = send_message.getText().toString();
try{
SmsManager smsManager = SmsManager.getDefault();

smsManager.sendTextMessage(phoneno,null,mymessage,null,null);
Toast.makeText(getApplicationContext(),"Message
sent",Toast.LENGTH_LONG).show();
}catch(Exception e){

Toast.makeText(getApplicationContext(),"Failed",Toast.LENGTH_LONG).sho
w();
}
}
});
}
}
Manifest File -:

<uses-permission android:name="android.permission.SEND_SMS"></uses-
permission>

47. Write a simple program to create a simple sql lite database.

public class MyDatabaseHelper extends SQLiteOpenHelper {


private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;

public MyDatabaseHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
// Create the table
String sql = "CREATE TABLE mytable ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT,"
+ "age INTEGER)";

db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Upgrade the table if needed
db.execSQL("DROP TABLE IF EXISTS mytable");
onCreate(db);
}
}

In this program, we have defined a MyDatabaseHelper class that extends


SQLiteOpenHelper. This class provides methods to create and upgrade the
database schema.

public class MainActivity extends AppCompatActivity {


private MyDatabaseHelper mDatabaseHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mDatabaseHelper = new MyDatabaseHelper(this);

// Insert data into the table


SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "John");
values.put("age", 25);
db.insert("mytable", null, values);

// Query the data from the table


Cursor cursor = db.rawQuery("SELECT * FROM mytable", null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
Log.d("MainActivity", "Name: " + name + ", Age: " + age);
} while (cursor.moveToNext());
}
cursor.close();
}
}

48. Write a program to locate user’s current location.

To locate a user's current location in an Android app, we can use the


LocationManager and LocationListener classes provided by the Android
framework. Here is an example program that demonstrates how to do this:

public class MainActivity extends AppCompatActivity implements


LocationListener {
private LocationManager locationManager;
private TextView locationTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationTextView = findViewById(R.id.location_text_view);
}

@Override
protected void onResume() {
super.onResume();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, this);
} else {
ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}

@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}

@Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
locationTextView.setText("Latitude: " + latitude + "\nLongitude: " +
longitude);
}

@Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "GPS disabled", Toast.LENGTH_SHORT).show();
}

@Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "GPS enabled", Toast.LENGTH_SHORT).show();
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}

Manifest code -:

<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />

49. Explain the steps how to publish an android application on google playstore.
50. List sensors in android and explain any one them .

Android devices are equipped with a variety of sensors that enable various
functionalities in apps. Here are some of the common sensors in Android:

 Accelerometer: Measures acceleration force in three dimensions (x, y, z)


and is commonly used to detect changes in orientation or shake events.
 Gyroscope: Measures angular velocity and provides more precise
orientation data than the accelerometer. It can be used in combination
with the accelerometer to detect more complex movements.
 Magnetometer: Measures the strength and direction of the magnetic field
in three dimensions and is commonly used to determine the device's
orientation with respect to the Earth's magnetic field.
 Proximity Sensor: Measures the distance between the device and an
object in front of it and is commonly used to turn off the screen and
disable touch events when the device is held to the ear during a phone
call.
 Ambient Light Sensor: Measures the ambient light level in the
environment and is commonly used to adjust the screen brightness
automatically.
 Barometer: Measures atmospheric pressure and is commonly used to
determine altitude and provide weather data.
 GPS: Uses signals from GPS satellites to determine the device's location.

One of the most commonly used sensors in Android is the GPS sensor. The GPS
sensor uses signals from GPS satellites to determine the device's location. Here
is an example of how to use the GPS sensor in an Android app:
Code -:
public class MainActivity extends AppCompatActivity implements
LocationListener {
private LocationManager locationManager;
private TextView latitudeTextView, longitudeTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);

latitudeTextView = findViewById(R.id.latitude_text_view);
longitudeTextView = findViewById(R.id.longitude_text_view);
}

@Override
protected void onResume() {
super.onResume();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, this);
} else {
ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}

@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull
String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, this);
}
}
}
}
@Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();

latitudeTextView.setText("Latitude: " + latitude);


longitudeTextView.setText("Longitude: " + longitude);
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onProviderDisabled(String provider) {
}
}

51. Describe the need of permission in android. Explain with any example or
program.

Permissions in Android are used to protect user privacy and security by


controlling the access that apps have to sensitive data and system resources on
the device. Android requires apps to request permission before accessing certain
features or data, and users can choose to grant or deny these requests.
For example, an app that needs access to the device's camera or microphone
must request the CAMERA and RECORD_AUDIO permissions, respectively.
Without these permissions, the app cannot use these features.

Here's an example of how to request permission to access the camera in an


Android app:

public class MainActivity extends AppCompatActivity {


private static final int REQUEST_CAMERA_PERMISSION = 1;
private Camera camera;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
} else {
startCamera();
}
}
private void startCamera() {
try {
camera = Camera.open();
CameraPreview preview = new CameraPreview(this, camera);
FrameLayout previewLayout = findViewById(R.id.preview_layout);
previewLayout.addView(preview);
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull
String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
startCamera();
} else {
Toast.makeText(this, "Camera permission denied",
Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onPause() {
super.onPause();
if (camera != null) {
camera.release();
camera = null;
}
}
}

52. State and elaborate the syntax of required class and methods
for Geocoding.

53. Define activity in android. Explain how to create a new activity and switch
from one activity to another.

In Android, an activity is a component that provides a user interface (UI) for an


app. It represents a single screen with a user interface that the user can interact
with. An app may have multiple activities, each representing a different screen
or workflow.

Activities are a fundamental building block of Android apps, and they are
responsible for managing their own lifecycle, including being created, started,
paused, resumed, stopped, and destroyed. They can also be organized into
backstacks to enable users to navigate between different screens and workflows.

54. Develop this registration form UI .. Write only xml code.

You might also like