Android
Android
Introduction:
Android is the world’s most popular mobile operating system(os). Ever
since it was launched in the year 2008.android began as a simple smart
phone and now it is power house for countless no of devices. With an
estimate 1.5 billion android users across the globe that is 1/7 of entire
world population. This is the right time to start exploring this amazing os.
About:
Android is a mobile operating system based on a modified version of the
linux kernel and other open-source software, designed primarily for
touchscreen mobile devices such as smartphones and tablets.
What is the history of Android?
Android began in 2003 as a project of the American technology
company Android Inc., to develop an operating system for digital
cameras. In 2004 the project changed to become an operating system
for smartphones. Android Inc., was bought by the American search
engine company Google Inc., in 2005.
Current version:
In this various versions are passed away now Android 11 is the
eleventh major release and 18th version of Android. The mobile
operating system developed by the Open Handset Alliance led by
Google.
11.0.0_r62
Latest
(RSV1.210329.071) /
release
December 5, 2022
Why Android:
Basically, Android is thought of as a mobile operating system. But it is
not limited to mobile-only. It is currently used in various devices such as
mobiles, tablets, televisions, etc.
Android provides a rich application framework that allows us to build
innovative apps and games for mobile devices in a Java language
environment.
And also.
Features of Android
Android is a powerful operating system competing with Apple 4GS and
supports great features which makes it popular in the world. These are:
Entertainment
Tools
Communication
Productivity
Personalization
Music and Audio
Social
Media and Video
Android (operating system)
Overview:
Android is a mobile operating system based on a modified version of the
Linux kernel and other open-source software, designed primarily for
touchscreen mobile devices such as smartphones and tablets. Android
is developed by a partnership of developers known as the Open
Handset Alliance and commercially sponsored by Google. It was
disclosed in November 2007, with the first commercial Android device,
the HTC Dream, launched in September 2008.
Android – Architecture
1. Linux kernel
2. Libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications
Android (operating system)
Linux kernel:
It is the heart of android architecture that exists at the root of android
architecture. Linux kernel is responsible for device drivers, power
management, memory management, device management and resource
access comes under the responsibility of the Linux Kernel.
The lowest layer is the kernel layer which is basically a hardware layer it
is the layer which is going to interact with the hardware so here we have
drivers for example display driver camera driver flash driver and IPC
binder right so this is going to manage the power so lets say the
phone's battery is low so this kernel layer is gonna detect that status.
The linux kernel is written in C
Libraries:
On top of Linux kernel there is a set of libraries is written in C++
including open-source Web browser engine such as WebKit, OpenGL
(graphical interface), FreeType, SQLite(relational data base),
Media(audio,video and music files), and runtime library (libc) etc.
Android Runtime:
In android runtime, there are core libraries and DVM (Dalvik Virtual
Machine) which is responsible to run android application. DVM is like
JVM (Java Virtual Machine)but it is optimized for mobile devices. It
consumes less memory and provides fast performance.
the runtime of Android based on dalvik virtual machine and the core
libraries from Java itself nothing but JVM.
Android (operating system)
Application Framework:
The Application Framework is written in java.The Application Framework
layer provides many higher-level services to applications in the form of
Java. Application developers are allowed to make use of these services
in their applications.
Android framework includes Android API's such as UI (User Interface),
telephony, resources, locations, Content Providers (data) and package
managers. It provides a lot of classes and interfaces for android
application development.
Applications:
On the top of android framework, there are applications. Applications are
also written in java. All applications such as home, contact, settings,
games, browsers are using android framework that uses android runtime
and libraries. Android runtime and native libraries are using linuxkernal.
Services:
They handle background processing associated with an application.
A service is a component that runs in the background to perform long-
running operations. For example, a service might play music in the
background while the user is in a different application, or it might fetch
data over the network without blocking user interaction with an activity.
A service is implemented as a subclass of Service class as follows −
publicclassMyServiceextendsService
{
}
Broadcast Receivers:
They handle communication between Android OS and applications.
Broadcast Receivers simply respond to broadcast messages from other
applications or from the system. For example, applications can also
initiate broadcasts to let other applications know that some data has
been downloaded to the device and is available for them to use, so this
is broadcast receiver who will intercept this communication and will
initiate appropriate action.
A broadcast receiver is implemented as a subclass
of BroadcastReceiver class and each message is broadcaster as
an Intent object.
publicclassMyReceiverextendsBroadcastReceiver
{
publicvoidonReceive(context,intent){}
}
Content Providers:
They handle data and database management issues.
A content provider component supplies data from one application to
others on request. Such requests are handled by the methods of
the ContentResolver class. The data may be stored in the file system,
the database or somewhere else entirely.
Android (operating system)
Activity:
An activity is a class that represents a single screen. It is like a Frame in
AWT.(Abstract Window Toolkit)
View:
A view is the UI element such as button, label, text field etc. Anything
that you see is a view.
Intent:
Intent is used to invoke components. It is mainly used to:
o Start the service
o Launch an activity
o Display a web page
o Display a list of contacts
o Broadcast a message
o Dial a phone call etc.
Service:
Service is a background process that can run for a long time.
There are two types of services local and remote. Local service is
accessed from within the application whereas remote service is
accessed remotely from other applications running on the same device.
Android (operating system)
Content Provider:
Fragment:
Fragments are like parts of activity. An activity can display one or more
fragments on the screen at the same time.
AndroidManifest.xml:
It contains informations about activities, content providers, permissions
etc. It is like the web.xml file in Java EE.
Android Virtual Device (AVD):
It is used to test the android application without the need for mobile or
tablet etc. It can be created in different configurations to emulate
different types of real devices.
Broadcast Receivers:
They handle communication between Android OS and applications.
Layouts:
View hierarchies that control screen format and appearance of the
views.
Resources:
External elements, such as strings, constants and drawable pictures.
Android Emulator
The Android emulator is an Android Virtual Device (AVD), which
represents a specific Android device. We can use the Android emulator
as a target device to execute and test our Android application on our PC.
The Android emulator provides almost all the functionality of a real
device. We can get the incoming phone calls and text messages. It also
gives the location of the device and simulates different network speeds.
Android emulator simulates rotation and other hardware sensors. It
accesses the Google Play store, and much more
Android (operating system)
Requirements
s for Install the emulator:
The Android emulator takes additional requirements beyond the b
basic
system requirement for Android Studio. These requirements are given
below:
Now an android project has been created. You can explore the android
project and see the simple program, it looks like this:
Android (operating system)
To run the android application, click the run icon on the toolbar or simply
press Shift + F10.
Android - UI Layouts:
The basic building block for user interface is a View object which is
created from the View class and occupies a rectangular area on the
screen and is responsible for drawing and event handling. View is the
base class for widgets, which are used to create interactive UI
components like buttons, text fields, etc.
The ViewGroup is a subclass of View and provides invisible container
that hold other Views or other ViewGroups and define their layout
properties.
At third level we have different layouts which are subclasses of
ViewGroup class and a typical layout defines the visual structure for an
Android user interface and can be created either at run time
using View/ViewGroup objects or you can declare your layout using
simple XML file main_layout.xml which is located in the res/layout
folder of your project.
There are given a lot of android widgets with simplified examples such
as Button, EditText, AutoCompleteTextView, ToggleButton, DatePicker,
TimePicker, ProgressBar etc.
Android widgets are easy to learn. The widely used android widgets with
examples are given below:
Android Button:
Let's learn how to perform event handling on button click.
Android Toast:
Displays information for the short duration of time.
Custom Toast:
ToggleButton:
It has two states ON/OFF.
CheckBox:
Checkboxes allow the user to select one or more options from a
set.
AlertDialog:
Spinner:
Spinner displays the multiple options, but only one can be selected at a
time.
AutoCompleteTextView:
AutoCompleteTextView is a component used to show suggestions
while writing in an editable text field.
Android (operating system)
RatingBar:
RatingBar displays the rating bar.
DatePicker:
Datepicker displays the datepicker dialog that can be used to pick the
date.
TimePicker:
TimePicker displays the timepicker dialog that can be used to pick the
time.
ProgressBar:
ProgressBar displays progress task.
Example:
OnClickListener()
This is called when the user either clicks or touches or focuses
onClick() upon any widget like button, text, image etc. You will use
onClick() event handler to handle such event.
Theme != Style
Both themes and styles use the same <style> syntax but serve very
different purposes. You can think of both as key-value stores where the
keys are attributes and the values are resources. Let’s take a look at
each.
What’s in a style?
A style is a collection of view attribute values. You can think of a style as
a Map<view attribute, resource>. That is the keys are all view attributes
i.e. attributes that a widget declares and you might set in a layout file.
Styles are specific to a single type of widget because different widgets
support different sets of attributes:
Scope
A style applied to a view only applies to that view, not to any of its
children. For example,( textbook) if you have a ViewGroup with three
buttons, setting the InlineAction style on the ViewGroup will not apply that
style to the buttons. The values provided by the style are combined with
those set directly in the layout
What’s a theme?
A theme is a collection of named resources which can be referenced
later by styles, layouts etc. They provide semantic names to Android
resources so you can refer to them later e.g. colorPrimary is a semantic
name for a given color.
A style specifies attributes for a particular type of view. For example, one
style might specify a button's attributes. Every attribute you specify in a
style is an attribute you could set in the layout file. By extracting all the
attributes to a style, it's easy to use and maintain them across multiple
widgets.
Styles and themes are meant to work together. For example, you might
have a style that specifies that one part of a button should
be colorPrimary, and another part should be colorSecondary. The actual
definitions of those colorsis provided in the theme. When the device
goes into night mode, your app can switch from its "light" theme to its
"dark" theme, changing the values for all those resource names. You
don't need to change the styles, since the styles are using the semantic
names and not specific colordefinitions
Android (operating system)
The Drag and Drop framework will include the following functionalities
to support the data movement in android applications
applications.
Generally, the Drag and Drop process starts when users making
gestures recognized as a signal to start dragging data and the
application tells the system that the drag is starting.
In android, the Drag and Drop process contains 4 steps or states, those
are
Android (operating system)
Started
Continuing
Dropped
Ended
Started:
This event will occur when we start dragging an item in layout and our
application will call the startDrag() method to tell the system to start a
drag. The startDrag() method arguments will provide data to be
dragged, metadata for this data and a call-back for drawing the drag
shadow.
The system will respond back to our application to get a drag shadow
and it will display the drag shadow on the device.
Continuing:
When the user continues to drag, the drag shadow intersects with the
bounding box of a View object and the system sends one or more drag
events to the View object's drag event listener (In case if it is registered
to receive events).
Dropped:
The user releases the dragged item within the bounding box of a View.
The system sends the View object's listener a drag event with action
type ACTION_DROP.
Ended:
Just after the action type ACTION_DROP, the system sends out a drag
event with action type ACTION_DRAG_ENDED to indicate that the drag
operation is over.
Android (operating system)
Drag Listeners
The combination of the onDragEvent(DragEvent) method
and View.OnDragListener is analogous to the combination of
the onTouchEvent() and View.OnTouchListener used with touch
events in Android.
Android (operating system)
The following sections of this guide refer to the method that receives
drag events as the drag event listener;
Android – Notifications
In android, Notification is a message which is used to alert the users
about some events that happening in our app.
Android Toast class provides a handy way to show users alerts but
problem is that these alerts are not persistent which means alert flashes
on the screen for a few seconds and then disappears.
When we tell the system to issue a notification, first it will display an icon
in notification bar like as shown below.
To see the details of our android app notification, we need to open the
notification drawer like as shown below.
Android (operating system)
SmsManager API
SmsManagersmsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null,
null);
Built-in SMS application
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
Of course, both need SEND_SMS permission.
<uses-permission android:name="android.permission.SEND_SMS" />
Dialog Description
AlertDialog This dialog is used to display prompt to the user with title, upto
select Date.
Android - Animations
In android, Animations are used to change the appearance and
behavior of the objects over a particular interval of time. The animations
will provide a better look and feel high
high-quality
quality user interface for our
applications.
Generally, the animations are useful when we want to notify users about
the changes happening in our app, such as new content loaded or new
actions available, etc.
<RelativeLayoutxmlns: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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity"/>
</RelativeLayout>
Program2:
Consider a layout res/layout/activity_main.xml with the following definition −
?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextViewandroid:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView"/>
<Buttonandroid:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button"/>
</LinearLayout>
This application code will load this layout for an Activity, in the onCreate() method as
follows −
Android (operating system)
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Program3:
Consider a layout res/layout/activity_main.xml with the following definition −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextViewandroid:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView"/>
<Buttonandroid:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button"/>
</LinearLayout>
This application code will load this layout for an Activity, in the onCreate() method as
follows −
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Program4:
Following is the content of the modified main activity file src/MainActivity.java.
packagecom.example.sairamkrishna.myapplication;
importandroid.app.ProgressDialog;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.view.View;
importandroid.widget.Button;
publicclassMainActivityextendsActivity{
Button b1;
privateProgressDialogprogressBar;
privateintprogressBarStatus=0;
Android (operating system)
privateHandlerprogressBarbHandler=newHandler();
privatelongfileSize=0;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(View v){
progressBar=newProgressDialog(v.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("File downloading ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
progressBarStatus=0;
fileSize=0;
newThread(newRunnable(){
publicvoidrun(){
while(progressBarStatus<100){
progressBarStatus=downloadFile();
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
progressBarbHandler.post(newRunnable(){
publicvoidrun(){
progressBar.setProgress(progressBarStatus);
}
});
}
if(progressBarStatus>=100){
try{
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
progressBar.dismiss();
}
}
}).start();
Android (operating system)
}
});
}
publicintdownloadFile(){
while(fileSize<=1000000){
fileSize++;
if(fileSize==100000){
return10;
}elseif(fileSize==200000){
return20;
}elseif(fileSize==300000){
return30;
}elseif(fileSize==400000){
return40;
}elseif(fileSize==500000){
return50;
}elseif(fileSize==700000){
return70;
}elseif(fileSize==800000){
return80;
}
}
return100;
}
}
Program5:
Following is the content of the modified MainActivity.java.
packagecom.example.sairamkrishna.myapplication;
importandroid.app.Activity;
importandroid.hardware.SensorManager;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.view.Menu;
importandroid.view.MenuItem;
importandroid.view.View;
importandroid.widget.TextView;
importjava.util.List;
importandroid.hardware.Sensor;
importandroid.hardware.SensorManager;
publicclassMainActivityextendsActivity{
Android (operating system)
TextView tv1=null;
privateSensorManagermSensorManager;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 =(TextView)findViewById(R.id.textView2);
tv1.setVisibility(View.GONE);
mSensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
List<Sensor>mList=mSensorManager.getSensorList(Sensor.TYPE_ALL);
for(inti=1;i<mList.size();i++){
tv1.setVisibility(View.VISIBLE);
tv1.append("\n"+mList.get(i).getName()+"\n"+mList.get(i).getVendor()+"\n"+mList.get(i).
getVersion());
}
}
@Override
publicbooleanonCreateOptionsMenu(Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
returntrue;
}
@Override
publicbooleanonOptionsItemSelected(MenuItem item){
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id =item.getItemId();
//noinspectionSimplifiableIfStatement
if(id ==R.id.action_settings){
returntrue;
}
returnsuper.onOptionsItemSelected(item);
}
}
Program6:
Following is the content of the modified main activity
file src/com.example.helloworld/MainActivity.java. This file includes each of the
fundamental life cycle methods. The Log.d() method has been used to generate log messages
−
Android (operating system)
packagecom.example.helloworld;
importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.util.Log;
publicclassMainActivityextendsActivity{
Stringmsg="Android : ";
}
}
importjava.io.IOException;
importandroid.annotation.SuppressLint;
importandroid.app.Activity;
importandroid.graphics.SurfaceTexture;
importandroid.hardware.Camera;
importandroid.os.Bundle;
importandroid.view.Gravity;
importandroid.view.Menu;
importandroid.view.TextureView;
importandroid.view.TextureView.SurfaceTextureListener;
importandroid.view.View;
importandroid.widget.FrameLayout;
publicclassMainActivityextendsActivityimplementsSurfaceTextureListener{
privateTextureViewmyTexture;
privateCameramCamera;
@SuppressLint("NewApi")
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTexture=newTextureView(this);
myTexture.setSurfaceTextureListener(this);
setContentView(myTexture);
}
@Override
publicbooleanonCreateOptionsMenu(Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
returntrue;
}
@SuppressLint("NewApi")
@Override
publicvoidonSurfaceTextureAvailable(SurfaceTexture arg0,int arg1,int arg2){
Android (operating system)
mCamera=Camera.open();
Camera.SizepreviewSize=mCamera.getParameters().getPreviewSize();
myTexture.setLayoutParams(newFrameLayout.LayoutParams(
previewSize.width,previewSize.height,Gravity.CENTER));
try{
mCamera.setPreviewTexture(arg0);
}catch(IOException t){
}
mCamera.startPreview();
myTexture.setAlpha(1.0f);
myTexture.setRotation(90.0f);
}
@Override
publicbooleanonSurfaceTextureDestroyed(SurfaceTexture arg0){
mCamera.stopPreview();
mCamera.release();
returntrue;
}
@Override
publicvoidonSurfaceTextureSizeChanged(SurfaceTexture arg0,int arg1,
int arg2){
// TODO Auto-generated method stub
}
@Override
publicvoidonSurfaceTextureUpdated(SurfaceTexture arg0){
// TODO Auto-generated method stub
}
}
Here is the content of activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns: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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextureView
android:id="@+id/textureView1"
android:layout_width="wrap_content"
Android (operating system)
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Here is the default content of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.textureview">
<uses-permissionandroid:name="android.permission.CAMERA"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.example.textureview.MainActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Program8:
The below example is a complete example of connecting your android application with
MYSQL database via PHP page. It creates a basic application that allows you to login using
GET and POST method.
PHP - MYSQL part
In this example a database with the name of temp has been created at 000webhost.com. In
that database, a table has been created with the name of table1. This table has three fields.
(Username, Password, Role). The table has only one record which is
("admin","admin","administrator").
<?php
$con=mysqli_connect("mysql10.000webhost.com","username","password","db_name");
if(mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
Android (operating system)
$username = $_POST['username'];
$password = $_POST['password'];
$result =mysqli_query($con,"SELECT Role FROM table1 where
Username='$username' and Password='$password'");
$row =mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
importandroid.app.Activity;
importandroid.hardware.SensorManager;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.view.Menu;
importandroid.view.MenuItem;
importandroid.view.View;
importandroid.widget.TextView;
importjava.util.List;
importandroid.hardware.Sensor;
importandroid.hardware.SensorManager;
publicclassMainActivityextendsActivity{
TextView tv1=null;
privateSensorManagermSensorManager;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 =(TextView)findViewById(R.id.textView2);
tv1.setVisibility(View.GONE);
mSensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
Android (operating system)
List<Sensor>mList=mSensorManager.getSensorList(Sensor.TYPE_ALL);
for(inti=1;i<mList.size();i++){
tv1.setVisibility(View.VISIBLE);
tv1.append("\n"+mList.get(i).getName()+"\n"+mList.get(i).getVendor()+"\n"+mList.get(i).
getVersion());
}
}
@Override
publicbooleanonCreateOptionsMenu(Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
returntrue;
}
@Override
publicbooleanonOptionsItemSelected(MenuItem item){
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id =item.getItemId();
//noinspectionSimplifiableIfStatement
if(id ==R.id.action_settings){
returntrue;
}
returnsuper.onOptionsItemSelected(item);
}
}
Following is the modified content of the xml activity_main.xml.
In the below code abc indicates about the logo of tutorialspoint.com
<RelativeLayoutxmlns: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:paddingLeft="@dimen/activity_horizontal_
margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true">
<TextViewandroid:text="Sensor "android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
Android (operating system)
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView2"
android:layout_below="@+id/imageView"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
Following is the content of the res/values/string.xml.
<resources>
<stringname="app_name">My Application</string>
<stringname="hello_world">Hello world!</string>
<stringname="action_settings">Settings</string>
</resources>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
Android (operating system)
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Program10:
Here is an example demonstrating the use of GoogleMap class. It creates a basic M
application that allows you to navigate through the map.
To experiment with this example , you can run this on an actual device or in an emulator.
Create a project with google maps activity as shown b
package com.example.tutorialspoint7.myapplication;
import android.support.v4.app.FragmentActivity;
importandroid.os.Bundle;
importcom.google.android.gms.maps.CameraUpdateFactory;
importcom.google.android.gms.maps.GoogleMap;
importcom.google.android.gms.maps.OnMapReadyCallback;
importcom.google.android.gms.maps.SupportMapFragment;
importcom.google.android.gms.maps.model.LatLng;
Android (operating system)
importcom.google.android.gms.maps.model.MarkerOptions;
publicclassMapsActivityextendsFragmentActivityimplementsOnMapReadyCallback{
privateGoogleMapmMap;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragmentmapFragment=(SupportMapFragment)getSupportFragmentManager
()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera.
* In this case, we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device.
* This method will only be triggered once the user has installed
Google Play services and returned to the app.
*/
@Override
publicvoidonMapReady(GoogleMapgoogleMap){
mMap=googleMap;
// Add a marker in Sydney and move the camera
LatLngTutorialsPoint=newLatLng(21,57);
mMap.addMarker(new
MarkerOptions().position(TutorialsPoint).title("Tutorialspoint.com"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(TutorialsPoint));
}
}
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/>
Android (operating system)
<uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permissionandroid:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key
that is used to sign the APK for publishing.
You can define the keys for the debug and
release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAXhBdyKxUo_cb-EkSgWJQTdqR0QjLcqes"/>
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>