AY 23-24 TYIT AMP Practical Manual
AY 23-24 TYIT AMP Practical Manual
)|2023-24
PRACTICAL NO 1
Android Components:
Sr.No Components & Description
Activities
1
They dictate the UI and handle the user interaction to the smart phone screen.
Services
2
They handle background processing associated with an application.
BroadcastReceivers
3
They handle communication between Android OS and applications.
Content Providers
4
They handle data and database management issues.
Activities
An activity represents a single screen with a user interface; in-short Activity performs actions on
the screen.
For example, an email application might have one activity that shows a list of new emails, another
activity to compose an email, and another activity for reading emails.
If an application has more than one activity, then one of them should be marked as the activity
that is presented when the application is launched.
An activity is implemented as a subclass of Activity class as follows −
publicclassMainActivityextendsActivity{
}
Services
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{
}
1
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Broadcast Receivers
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{
publicvoid onReceive(context,intent){}
}
Content Providers
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.
A content provider is implemented as a subclass of ContentProvider class and must implement a
standard set of APIs that enable other applications to perform transactions.
publicclassMyContentProviderextendsContentProvider{
publicvoid onCreate(){}
}
Additional Components
There are additional components which will be used in the construction of above mentioned
entities, their logic, and wiring between them. These components are –
Sr.No Components & Description
Fragments
1
Represents a portion of user interface in an Activity.
Views
2
UI elements that are drawn on-screen including buttons, lists forms etc.
Layouts
3
View hierarchies that control screen format and appearance of the views.
Intents
4
Messages wiring components together.
Resources
5
External elements, such as strings, constants and drawable pictures.
Manifest
6
Configuration file for the application.
2
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Android Studio will also automatically open the Debug tool. You can turn it on manually by
clicking Debug! at the bottom of Android Studio.
Another way to start debugging without having to restart your app is by clicking on “Attach
Logcat
At STRV we use the Logcat utility, which handles if-statement among other things. Check it
out here.
In build.gradle we have build config property LOGS, which can be set to true in the debug build
type and to false in the release type. Logcat always check the LOGS property before logging
any message. Then you don’t have to worry about wrapping it in any if-statement.
Simply call the method:
Logcat.d(“Your message here”);
You can also set other parameters in this class. The message can include “Code location”.
This means that it displays the name of the method, the line of code and also the thread where
Logcat is called. Another cool thing about Logcat is that you can log formatted messages. So
instead of:
Logcat.d(“Message with index: ” + someInteger)
we use:
Logcat.d(“Message with index: %d”, someInteger)
Breakpoints
When you are at the point where you can’t fix a bug just by looking at your code, it’s time to
use breakpoints. Breakpoints allow you to pause the execution of your app at a particular line of
code.
Setting up breakpoints
Just go to the file that you want to debug, find a line of code where you want to start and
click on the sidebar to the left of this line. You will see a red dot there. Then run your app
in the debug mode or attach a debugger (see above).
3
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Step 2:Virtual Device Configuration window will appear
In Phone Tab Select Name of Device and Click on Next.
4
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
HELLO WORLD PROGRAM:
Step 1: Create new Android Project and give Application name as hello
Step2: Check Phone and Tablet and select API Android 4.0.3[IceCreamSandwitch]
Click on Next.
5
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Step 4: Click on finish
MainActivity.kt
package com.example.user1.hello
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">
<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
6
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
OUTPUT:
7
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
PRACTICAL NO 2
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
//Add new colors here
<color name="ColorRed">#FF0000</color>
<color name="ColorBlue">#0000FF</color>
</resources>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns: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"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Practical No. 2!"
android:id="@+id/textview"
android:background="@color/ColorRed"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alpha"
8
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
android:id="@+id/textview1"
android:background="@color/ColorBlue"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="India"
android:id="@+id/textview2"
android:background="#00FF00"/>
</LinearLayout>
MainActivity.kt
package com.example.user1.ampract2
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
OUTPUT:
9
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Android Resource: Theme
1. Defining new theme properties in styles.xml
2. Create a new project and go to: ProjectName>App>src>main>res>values>styles.xml
styles.xml
<resources> <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item> //Add new color to the background
<item name="android:background">#00F0EF</item>
<item name="android:textColor">#000000</item>
</style></resources>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns: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" android:orientation="vertical"
tools:context=".MainActivity">
OUTPUT:
10
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Android Resource: Strings
1. Defining paragraph and header property in strings.xml
2. Create a new project and go to: ProjectName>App>src>main>res>values>strings.xml
strings.xml
<resources>
<string name="app_name">ampract2</string>
<string name="ParaHead">Programming Resources</string>
<string name="Description">The Android multimedia framework includes support for playing
variety of common media types.</string>
</resources>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns: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"
android:orientation="vertical" tools:context=".MainActivity">
OUTPUT:
11
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Android Resource: Dimension, Image
1. Adding Images to Application created
2. For adding a new image files, do the following:
ProjectName>App>src>main>res>drawable>Right-click and paste the images that are copied
3. For adding new dimension file, do the following:
ProjectName-->App-->src-->main-->res-->values-->Right-click and new-->values resource
file
4. Select Dimension and click on OK
12
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
5. Add a new dimens.xml file and write the following code in dimens.xml
dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimenname="textview_height">35dp</dimen>
<dimenname="textview_width">150dp</dimen>
<dimenname="font_size">26sp</dimen>
</resources>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns: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"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Modified"
android:textSize="@dimen/font_size"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/img1"
android:src="@drawable/maple"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/img2"
13
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
android:src="@drawable/penguin"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/img3"
android:src="@drawable/twitter"/>
</LinearLayout>
OUTPUT:
14
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
PRACTICAL NO 3
Activity Lifecycle
15
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
activity_main.xml
<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
MainActivity.kt
package com.example.user1.ampract3
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log;
16
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
override fun onStart() {
super.onStart()
print("onStart")
}
OUTPUT:
17
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
18
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
PRACTICAL NO 4
Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There are few
common attributes among all the layouts and their are other attributes which are specific to that
layout. Following are common attributes and will be applied to all the layouts:
Sr.No Attribute & Description
android:id
1
This is the ID which uniquely identifies the view.
android:layout_width
2
This is the width of the layout.
android:layout_height
3
This is the height of the layout
android:layout_marginTop
4
This is the extra space on the top side of the layout.
android:layout_marginBottom
5
This is the extra space on the bottom side of the layout.
19
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
android:layout_marginLeft
6
This is the extra space on the left side of the layout.
android:layout_marginRight
7
This is the extra space on the right side of the layout.
android:layout_gravity
8
This specifies how child Views are positioned.
android:layout_weight
9
This specifies how much of the extra space in the layout should be allocated to the View.
android:layout_x
10
This specifies the x-coordinate of the layout.
android:layout_y
11
This specifies the y-coordinate of the layout.
android:layout_width
12
This is the width of the layout.
android:layout_width
13
This is the width of the layout.
android:paddingLeft
14
This is the left padding filled for the layout.
android:paddingRight
15
This is the right padding filled for the layout.
android:paddingTop
16
This is the top padding filled for the layout.
android:paddingBottom
17
This is the bottom padding filled for the layout.
1. Linear Layout
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical" >
MainActivity.kt
package com.example.user1.frame_layout
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
20
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
OUTPUT:
2. Relative Layout
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:paddingLeft="16dp" android:paddingRight="16dp" >
MainActivity.kt
package com.example.user1.frame_layout
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
21
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
OUTPUT:
3. Frame Layout
MainActivity.kt
package com.example.user1.frame_layout
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
22
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
class MainActivity : AppCompatActivity() {
activity_main.xml
<FrameLayout 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"
tools:context=".MainActivity">
<ImageView android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/one"
android:scaleType="centerCrop"/>
<TextView android:textSize="100dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:gravity="center"
android:textColor="@color/colorAccent"
android:layout_marginTop="220dp" />
</FrameLayout>
OUTPUT:
23
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
4. ListView
MainActivity.kt
package com.example.user1.listview
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
listview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Each List Item is displayed as TextView defined below -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/label" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:padding="10dip" android:textSize="16dip"
24
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
android:textStyle="bold" >
</TextView>
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
tools:context=".MainActivity">
OUTPUT:
25
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Grid View:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridLayout 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:rowCount="3" android:columnCount="3"
android:padding="20dp">
MainActivity.kt
package com.example.user1.gridview
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
OUTPUT:
26
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
27
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
PRACTICAL NO 5
Android EditText
In android, EditText is a user interface control which is used to allow the user to enter or modify
the text.
Android AutoCompleteTextView
In android, AutoCompleteTextView is an editable text view which is used to show the list of
suggestions based on the user typing text. The list of suggestions will be shown as a dropdown
menu from which the user can choose an item to replace the content of textbox.
Android Button
In android, Button is a user interface control which is used to perform an action when the user click
or tap on it.
Android CheckBox
In android, Checkbox is a two states button that can be either checked or unchecked.
28
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
In android, Radio Group is used to group one or more radio buttons into separate groups based on
our requirements.
In case if we group radio buttons using radio group, at a time only one item can be selected from
the group of radio buttons.
Android ProgressBar
In android, ProgressBar is a user interface control which is used to indicate the progress of an
operation.
Android Spinner
In android, Spinner is a drop-down list which allows a user to select one value from the list.
Android TimePicker
In android, TimePicker is a widget for selecting the time of day, either in 24-hour or AM/PM mode.
Android DatePicker
In android, DatePicker is a widget for selecting a date.
Android Toolbar or App bar: is a part of the application, where its provide UI experience on top of
the app for easy navigation and quick access to other items. A Toolbar is a generalization of Android
action bar.
Toolbar (App bar) is supporting a more focused feature set than ActionBar. From start to end, a
toolbar may contain a combination of the following optional elements:
Navigation button: Up arrow or navigation menu toggle icon in starting of Toolbar. You override
default home function and perform any action goto parent activity or open/close navigation menu
toggle,
Branded logo image: Its use for when you want to show logo in-app top bar. This may extend to
the height of the bar and can be wider.
Title and subtitle: If an app uses a logo image it should strongly recommend neglecting a title and
subtitle. It shows the name of the brand or Activity or user landing page information.
An action menu: The menu of actions will pin to the end of the Toolbar offering a few main
operations to the user like setting, print, save, profile etc. Or maybe some time you needed the same
menu for every activity, then you can use the same toolbar in multiple places.
29
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
<include layout="@layout/toolbar_layout"/>
</android.support.constraint.ConstraintLayout>
MainActivity.kt
package com.example.user1.appbar
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.Toolbar;
}
}
Go to app->layout->New->XML file
toolbar_layout.xml
30
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<app:android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:id="@+id/toolBar">
</app:android.support.v7.widget.Toolbar>
</LinearLayout>
OUTPUT:
31
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
For adding Menus to appbar, go to,
1. ProjectName> App >Src> Main > Res > New > Resource File > Give a filename
(app_bar_menu.xml) and select menu in resource type.
2. Now go to app_bar_menu.xml and add two menu items, and make the following changes to the
code file,
app_bar_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
32
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
package com.example.user1.appbar
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.Toast
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.app_bar_menu,menu)
return super.onCreateOptionsMenu(menu)
}
// actions on click menu items
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_search-> {
// User chose the "Print" item
Toast.makeText(this,"Search action",Toast.LENGTH_LONG).show()
true
}
R.id.action_about-> {
// User chose the "Print" item
Toast.makeText(this,"About action",Toast.LENGTH_LONG).show()
true
}
android.R.id.home->{
Toast.makeText(this,"Home action",Toast.LENGTH_LONG).show()
true
}
else ->
{
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
super.onOptionsItemSelected(item)
}
OUTPUT:
33
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
34
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
PRACTICAL NO 6
Context menu and contextual action mode : A context menu is appears when the user performs
a long-click on an element. That provides actions that affect the selected content or context frame.
Like in Gmail app you have to long press any email then Context menu appear with option Delete
,Archived etc. Context menu allows the user to select multiple items.
Popup menu : A popup menu displays a list of items in a vertical list that’s anchored to the view
that invoked the menu
35
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
<group> This is an optional, invisible container for <item> elements. It allows you to categorize
menu items so they share properties such as active state and visibility.
Creating Menus
1. Create a new project and go to,
Project > App >src>res(Right-click on res and select) > New > Android Resource File >
Filename(mymenu) and Resource Type Menu
36
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
2. Now go to, mymenu.xml file and make the following changes to code file,
mymenu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
android:layout_width="wrap_content" android:layout_height="wrap_content"
<item android:id="@+id/newb" android:title="Bookmarks" />
</menu>
MainActivity.kt
package com.example.user1.menu
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
Toast.makeText(this,"New selected",Toast.LENGTH_LONG).show()
true
}
R.id.Share-> {
37
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
}
R.id.delete-> {
// User chose the "Print" item
Toast.makeText(this,"Delete selected",Toast.LENGTH_LONG).show()
true
}
R.id.save-> {
// User chose the "Print" item
Toast.makeText(this,"Save selected",Toast.LENGTH_LONG).show()
true
}
R.id.search-> {
// User chose the "Print" item
Toast.makeText(this,"Search selected",Toast.LENGTH_LONG).show()
true
}
R.id.Exit-> {
android.R.id.home->{
Toast.makeText(this,"Home action",Toast.LENGTH_LONG).show()
true
}
else -> {
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
super.onOptionsItemSelected(item)
}
}
}
activity_main.xml
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/ap
k/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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
38
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
OUTPUT:
39
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
PRACTICAL NO 7
A broadcast receiver (receiver) is an Android component which allows you to register for system or
application events. All registered receivers for an event are notified by the Android runtime once this
event happens.
For example, applications can register for the ACTION_BOOT_COMPLETED system event which is
fired once the Android system has completed the boot process.
Implementation
A receiver can be registered via the AndroidManifest.xml file.
Alternatively to this static registration, you can also register a receiver dynamically via
theContext.registerReceiver() method.
The implementing class for a receiver extends the BroadcastReceiver class.
If the event for which the broadcast receiver has registered happens, the onReceive() method of the
receiver is called by the Android system.
Asynchronous processing
Before API level 11, you could not perform any asynchronous operation in the onReceive()method,
because once the onReceive() method had been finished, the Android system was allowed to recycle
that component. If you have potentially long running operations, you should trigger a service instead.
Since Android API 11 you can call the goAsync() method. This method returns an object of
thePendingResult type. The Android system considers the receiver as alive until you call
thePendingResult.finish() on this object. With this option you can trigger asynchronous processing
in a receiver. As soon as that thread has completed, its task calls finish() to indicate to the Android
system that this component can be recycled.
System broadcasts
Several system events are defined as final static fields in the Intent class. Other Android system classes
also define events, e.g., the TelephonyManager defines events for the change of the phone state.
The following table lists a few important system events.
Table 1. System Events
Event Description
Intent.ACTION_BOOT_COMPLETED Boot completed. Requires
the android.permission.RECEIVE_BOOT_COMPLE
TED permission
Intent.ACTION_POWER_CONNECTED Power got connected to the device.
Intent.ACTION_POWER_DISCONNECTED Power got disconnected to the device.
Intent.ACTION_BATTERY_LOW Triggered on low battery. Typically used to reduce
activities in your app which consume power.
Intent.ACTION_BATTERY_OKAY Battery status good again.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/and
roid"
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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flight Mode"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/imageView"
app:layout_constraintTop_toTopOf="@+id/imageView"/>
<ImageView
android:id="@+id/imageView"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="8dp"
android:layout_marginTop="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/flightmode" />
</android.support.constraint.ConstraintLayout>
MainActivity.kt
package com.example.user1.broadcast
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
41
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user1.broadcast">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
MyReceiver.kt
package com.example.user1.broadcast
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Toast.makeText(context, "Broadcast : Flight mode changed.",
Toast.LENGTH_LONG).show()
}
}
OUTPUT:
42
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
43
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
PRACTICAL NO 8
UserModel.kt
package com.example.user1.sqlitetutorial
DBContract.kt
package com.example.user1.sqlitetutorial
import android.provider.BaseColumns
object DBContract {
UserDBHelper.kt
package com.example.user1.sqlitetutorial
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteConstraintException
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteException
import android.database.sqlite.SQLiteOpenHelper
@Throws(SQLiteConstraintException::class)
fun insertUser(user: UserModel): Boolean {
// Gets the data repository in write mode
valdb = writableDatabase
// Create a new map of values, where column names are the keys
valvalues = ContentValues()
values.put(DBContract.UserEntry.COLUMN_USER_ID, user.userid)
values.put(DBContract.UserEntry.COLUMN_NAME, user.name)
45
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
values.put(DBContract.UserEntry.COLUMN_AGE, user.age)
// Insert the new row, returning the primary key value of the new row
valnewRowId = db.insert(DBContract.UserEntry.TABLE_NAME, null, values)
return true
}
@Throws(SQLiteConstraintException::class)
fun deleteUser(userid: String): Boolean {
// Gets the data repository in write mode
valdb = writableDatabase// Define 'where' part of query.
valselection = DBContract.UserEntry.COLUMN_USER_ID+ " LIKE ?"
// Specify arguments in placeholder order.
valselectionArgs = arrayOf(userid)
// Issue SQL statement.
db.delete(DBContract.UserEntry.TABLE_NAME, selection, selectionArgs)
return true
}
varname: String
varage: String
if (cursor!!.moveToFirst()) {
while (cursor.isAfterLast== false) {
name =
cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_NAME))
age = cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_AGE))
users.add(UserModel(userid, name, age))
cursor.moveToNext()
}
}
return users
}
varuserid: String
varname: String
varage: String
46
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
if (cursor!!.moveToFirst()) {
while (cursor.isAfterLast== false) {
userid = cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_USER_ID))
name =
cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_NAME))
age = cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_AGE))
users.add(UserModel(userid, name, age))
cursor.moveToNext()
}
}
return users
}
companion object {
// If you change the database schema, you must increment the database version.
valDATABASE_VERSION = 1
valDATABASE_NAME = "FeedReader.db"
private valSQL_CREATE_ENTRIES =
"CREATE TABLE " + DBContract.UserEntry.TABLE_NAME+ " (" +
DBContract.UserEntry.COLUMN_USER_ID+ " TEXT PRIMARY KEY," +
DBContract.UserEntry.COLUMN_NAME+ " TEXT," +
DBContract.UserEntry.COLUMN_AGE+ " TEXT)"
private valSQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " +
DBContract.UserEntry.TABLE_NAME
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns: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"
android:orientation="vertical" android:gravity="center"
tools:context=".MainActivity">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
47
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
android:orientation="horizontal">
<Button
android:id="@+id/button_add_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="addUser"
android:text="Add" />
<Button
android:id="@+id/button_show_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="showAllUsers"
android:text="Show All" />
</LinearLayout>
<TextView
android:id="@+id/textview_result"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="@+id/ll_entries"
android:padding="15dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
MainActivity.kt
package com.example.user1.sqlitetutorial
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
fun addUser(v:View){
varuserid = this.edittext_userid.text.toString()
varname = this.edittext_name.text.toString()
varage = this.edittext_age.text.toString()
varresult = usersDBHelper.insertUser(UserModel(userid = userid,name = name,age = age))
fun showAllUsers(v:View){
varusers = usersDBHelper.readAllUsers()
this.ll_entries.removeAllViews()
users.forEach{
vartv_user = TextView(this)
tv_user.textSize= 30F
tv_user.text= it.name.toString() + " - " + it.age.toString()
this.ll_entries.addView(tv_user)
}
this.textview_result.text= "Fetched " + users.size+ " users"
}
}
OUTPUT:
49
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
PRACTICAL NO 9
MainActivity.kt
package com.example.user1.permissionappdemo
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.Manifest
import android.content.Context
import android.os.Build
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
50
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.SEND_SMS,
Manifest.permission.READ_CALENDAR
)
// Initialize a new instance of ManagePermissions class
managePermissions=
ManagePermissions(this,list,PermissionsRequestCode)
An app must publicize the permissions it requires by including <uses-permission>tags in the app
manifest.
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
52
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
import android.app.Activity
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
varcounter = 0;
for (permission in list) {
counter += ContextCompat.checkSelfPermission(activity,
permission) }
return counter
}
53
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
return ""
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://sc
hemas.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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
54
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Request Permission at Runtime"
android:visibility="visible"
tools:layout_editor_absoluteX="28dp"
tools:layout_editor_absoluteY="0dp" />
</android.support.constraint.ConstraintLayout>
OUTPUT:
55
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
56
ICLES’ MOTILAL JHUNJHUNWALA College|Advanced Mobile Programming|T.Y.B.Sc.(I.T.)|2023-24
57