Advance Mobile Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 73

Advance Mobile Programming Practicals

UNIVERSITY OF MUMBAI

Reference Manual
Subject: Advanced Mobile Programming
Practical

with effect from the academic year


2018 – 2019
PRACTICAL 1
Q. Introduction to Android, Introduction to Android Studio IDE, Application
Fundamentals: Creating a Project, Android Components, Activities, Services, Content
Providers, Broadcast Receivers, Interface overview, Creating Android Virtual device,
USB debugging mode, Android Application Overview. Simple “Hello World”
program.
Solution:
Creating a project:
2 | Page
3 | Page
MainActivity.Kt

package com.practical.hello

import android.os.Bundle
import android.support.v7.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState) setContentView (R.layout.activity_main)
}
}

activity_main.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

4 | Page
Create and manage virtual devices:
To open the AVD Manager, do one of the following:
• Select Tools > AVD Manager.
• Click AVD Manager AVD Manager icon in the toolbar.

5 | Page
6 | Page
Output:

7 | Page
PRACTICAL 2
Programming Resources
Q. Insert the new contents in the following resources and demonstrate their uses in
the android application
Android Resources: (Color, Theme, String, Drawable, Dimension, Image)
Solution:
Color:

color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>

8 | Page
Theme:
style.xml

<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.MyApplication"
parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor"
tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>

String:

9 | Page
string.xml:

<resources>
<string name="app_name">My Application</string>
<string name="numbers">
<item>1</item>
<item>2</item>
<item>3</item>
</string>

</resources>

Drawable:
1. Right click on drawable folder

2. Copy the image if you want to create image drawable


3. Paste that image file inside the drawable folder

10 | P a g e
Note: to create drawable resource, right click on drawable folder and select drawableresource file

11 | P a g e
MainActivity.Kt

package com.practical2.drwable

import android.os.Bundle
import android.support.v7.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) setContentView (R.layout.activity_main)
}
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />

</androidx.constraintlayout.widget.ConstraintLayout>

Output:

12 | P a g e
PRACTICAL 3
Programming Activities and fragments
Activity Life Cycle, Activity methods, Multiple Activities, Life Cycle of fragments and
multiple fragments.

Activity Lifecycle:

onCreate(): Called by the OS when the activity is first created. This is where you
initialize any UI elements or data objects. You also have the savedInstanceState of the
activity that contains its previously saved state, and you can use it to recreate that state.\

onStart(): Just before presenting the user with an activity, this method is called. It’s
always followed by onResume(). In here, you generally should start UI animations, audio
based content or anything else that requires the activity’s contents to be on screen.

13 | P a g e
onResume(): As an activity enters the foreground, this method is called. Here you have agood
place to restart animations, update UI elements, restart camera previews, resume audio/video
playback or initialize any components that you release during onPause().

onPause(): This method is called before sliding into the background. Here you should stop any
visuals or audio associated with the activity such as UI animations, music playback or the camera.
This method is followed by onResume() if the activity returns tothe foreground or by onStop() if it
becomes hidden.

onStop(): This method is called right after onPause(), when the activity is no longer visible to the
user, and it’s a good place to save data that you want to commit to the disk.It’s followed by either
onRestart(), if this activity is coming back to the foreground, or onDestroy() if it’s being released
from memory.

onRestart(): Called after stopping an activity, but just before starting it again. It’s alwaysfollowed
by onStart().

onDestroy(): This is the final callback you’ll receive from the OS before the activity is destroyed.
You can trigger an activity’s desctruction by calling finish(), or it can be triggered by the system
when the system needs to recoup memory. If your activity includes any background threads or
other long-running resources, destruction could lead to a memory leak if they’re not released, so
you need to remember to stop these processeshere as well.

14 | P a g e
MainActivity.kt

package com.example.activitylifecycle

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Toast.makeText(this, "On Create Activity", Toast.LENGTH_LONG).show()
Log.d("Main Activity", "On Create Activity")
}

override fun onStart() {


super.onStart()
Toast.makeText(this, "On Start Activity", Toast.LENGTH_LONG).show()
Log.d("Main Activity", "On Start Activity")
}

override fun onPause() {


super.onPause()
Toast.makeText(this, "On Pause Activity", Toast.LENGTH_LONG).show()
Log.d("Main Activity", "On Pause Activity")
}

override fun onResume() {


super.onResume()
Toast.makeText(this, "On Resume Activity", Toast.LENGTH_LONG).show()
Log.d("Main Activity", "On Resume Activity")
}

override fun onStop() {


super.onStop()
Toast.makeText(this, "On Stop Activity", Toast.LENGTH_LONG).show()
Log.d("Main Activity", "On Stop Activity")
}

override fun onRestart() {


super.onRestart()
Toast.makeText(this, "On Restart Activity", Toast.LENGTH_LONG).show()
Log.d("Main Activity", "On Restart Activity")
}

override fun onDestroy() {


super.onDestroy()
Toast.makeText(this, "On Destroy Activity", Toast.LENGTH_LONG).show()
Log.d("Main Activity", "On Destroy Activity")
}
}

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" 15 | P a g e
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"
activity_main.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity LifeCycle"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Output:

16 | P a g e
Q. Create an android application with two Fragments and load them on the click
of Button’s. Display two Button’s and a FrameLayout in our Activity and perform
setOnClickListener event on both Button’s. On the click of First Button replace
the First Fragment and on click of Second Button we replace the Second Fragment
with the layout(FrameLayout).

FragmentOne.xml

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools">

<TextView
android:text="Fragment One"
android:layout_width="wrap_content"
android:layout_marginTop="230dp"
android:layout_marginLeft="145dp"
android:layout_height="wrap_content"
android:id="@+id/textView2"
android:textColor="#000000"
android:textStyle="bold"
tools:text="Fragment One"
android:textSize="18sp"
android:visibility="visible"
android:background="@color/purple_200"/>
<ImageView
android:layout_width="197dp"
android:layout_height="328dp"
android:src="@drawable/aa"
android:layout_marginTop="200dp"
android:layout_marginLeft="95dp"
android:id="@+id/imageView2"
android:visibility="visible"/>

</RelativeLayout>

17 | P a g e
FragmentTwo.xml

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:text="Fragment Two"
android:layout_width="wrap_content"
android:layout_marginTop="230dp"
android:layout_marginLeft="145dp"
android:textColor="#000000"
android:layout_height="wrap_content"
android:id="@+id/textView2"
android:textSize="18sp"
android:visibility="visible"
android:textStyle="bold"/>
<ImageView
android:layout_width="209dp"
android:layout_height="296dp"
android:layout_marginTop="200dp"
android:layout_marginLeft="95dp"
android:src="@drawable/bb"
android:id="@+id/imageView"/>

</RelativeLayout>

FragmentOne.kt

18 | P a g e
package com.example.fragments

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

class FragmentOne : Fragment(){


val TAG = "FragmentOne"

override fun onCreate(savedInstanceState: Bundle?) {


Log.d(TAG,"onCreate")
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?, savedInstanceState: Bundle?):
View? {
Log.d(TAG,"onCreateView")
return inflater!!.inflate(R.layout.fragment_one,container,false)
}
override fun onActivityCreated(savedInstanceState:
Bundle?) {
Log.d(TAG,"onActivityCreated")
super.onActivityCreated(savedInstanceState)
}
override fun onStart() {
Log.d(TAG,"onStart")
super.onStart()
}
override fun onResume() {
Log.d(TAG,"onResume")
super.onResume()
}
override fun onPause() {
Log.d(TAG,"onPause")
super.onPause()
}
override fun onStop() {
Log.d(TAG,"onStop")
super.onStop()
}
override fun onDestroyView() {
Log.d(TAG,"onDestroyView")
super.onDestroyView()
}
override fun onDestroy() {
Log.d(TAG,"onDestroy")
super.onDestroy()
}

override fun onDetach() {


Log.d(TAG,"onDetach")
super.onDetach()
}
}

19 | P a g e
FragmentTwo.kt

package com.example.fragments

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment

class FragmentTwo : Fragment(){


val TAG = "FragmentTwo"

override fun onCreate(savedInstanceState: Bundle?) {


Log.d(TAG, "onCreate")
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?, savedInstanceState: Bundle?):
View? {
Log.d(TAG, "onCreateView")
return inflater!!.inflate(R.layout.fragment_two,container,false)
}
override fun onActivityCreated(savedInstanceState:
Bundle?) {
Log.d(TAG, "onActivityCreated")
super.onActivityCreated(savedInstanceState)
}
}

20 | P a g e
activity_main.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/btn_change"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Change Fragment"
android:textAllCaps="false"/>
<FrameLayout
android:id="@+id/fragment_holder"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

21 | P a g e
MainActivity.kt

package com.example.fragments

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {


var isFragmentOneLoaded = true
val manager = supportFragmentManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val Change = findViewById<Button>(R.id.btn_change)
ShowFragmentOne()
Change.setOnClickListener({
if (isFragmentOneLoaded) {
showFragmentTwo()
} else {
showFragmentOne()
}
})
}

fun showFragmentOne() {
val transaction = manager.beginTransaction()
val fragment = FragmentOne()
transaction.replace(R.id.fragment_holder, fragment)
transaction.addToBackStack(null)
transaction.commit()
isFragmentOneLoaded = true
}

fun showFragmentTwo() {
val transaction = manager.beginTransaction()
val fragment = FragmentTwo()
transaction.replace(R.id.fragment_holder, fragment)
transaction.addToBackStack(null)
transaction.commit()
isFragmentOneLoaded = false
}
}

22 | P a g e
PRACTICAL 4
Programs related to different Layouts
Q. Create an android application using linear layout and insert 10 games in the list view and
display the selected game in the text view.

activity_main.xml

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


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

<TextView
android:text="List View"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:id="@+id/textView5"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/myList"/>

</LinearLayout>

23 | P a g e
MainActivity.kt
package com.example.listview

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val subjects=
arrayOf<String>("chess", "cricket", "hockey", "football", "carrom",
"ludo", "volleyball", "archery", "kho-kho", "kabaddi")
val myListView=findViewById<ListView>(R.id.myList)
val myDispLabel
=findViewById<TextView>(R.id.textView5)

myListView.adapter= ArrayAdapter<String>(this,android.R.layout.
simple_list_item_1,subjects)
myListView.setOnItemClickListener { parent, view,
position, id ->

Toast.makeText(this,"Clicked:\n"+subjects[position],
Toast.LENGTH_SHORT).show()
myDispLabel.text = subjects[position]
}

}
}

Q. Create an android application using grid view layout and insert 6 images of different
animals as the items and toast the animal name by clicking the image.

activity_main.xml

24 | P a g e
<?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"
android:columnCount="3"
tools:context=".MainActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="194dp"
tools:srcCompat="@drawable/img1"
android:id="@+id/imageView1"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_margin="2dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="194dp"
tools:srcCompat="@drawable/img2"
android:id="@+id/imageView2"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_margin="2dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="194dp"
tools:srcCompat="@drawable/img3"
android:id="@+id/imageView3"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_margin="2dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="194dp"
tools:srcCompat="@drawable/img4"
android:id="@+id/imageView4"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_margin="2dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="194dp"
tools:srcCompat="@drawable/img5"
android:id="@+id/imageView5"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_margin="2dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="194dp"
tools:srcCompat="@drawable/img6"
android:id="@+id/imageView6"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_margin="2dp"/>

</GridLayout>

25 | P a g e
Q. Create the standard calculator application in android
<?xml version="1.0" encoding="utf-8"?>
<TableLayout 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">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="DEL" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="C" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="%" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="+" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="/" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">

[…] 26 | P a g e

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
activity_main.xml
package com.example.tablelayout

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}

Output

27 | P a g e
PRACTICAL 5
Programing UI Elements
1. Create an android application with customised appbar. Insert search and file
buttons in it and toast the appropriate message on clicking the buttons (add new
color in color.xml and use that color for appbar).

Create menu folder and menu file in res

28 | P a g e
menu.xml

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


<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/search"
android:orderInCategory="100"
android:title="Search"
android:icon="@drawable/ic_action_name"
app:showAsAction="always"
app:actionViewClass="android.widget.SearchView" />
<item
android:id="@+id/file"
android:orderInCategory="100"
android:title="File"
android:icon="@drawable/file"
app:showAsAction="always"
app:actionViewClass="android.widget.SearchView" />
</menu>

activity_main.xml

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


<RelativeLayout

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:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Menus"
android:textSize="30sp"
android:textStyle="bold" />
</RelativeLayout>

29 | P a g e
MainActivity.kt

package com.example.appbar

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}

override fun onCreateOptionsMenu(menu: Menu?): Boolean {


menuInflater.inflate(R.menu.menu, menu)
return super.onCreateOptionsMenu(menu)
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {


val id = item?.itemId
if (id == R.id.search) {
Toast.makeText(this, "Search", Toast.LENGTH_SHORT).show()
}
if (id == R.id.file) {
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show()
}
return super.onOptionsItemSelected(item)
}
}

Output

30 | P a g e
PRACTICAL 6
Programming menus, dialog, dialog fragments

Q. Create an android application for the following menu items, the approriate toast should appear by
clicking on the item : Also create sub-menu
• Settings
• Search
• Compose Email
• FeedBack
Make compose email disabled

menu.xml

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


<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/settings"
android:icon="@drawable/settings"
android:orderInCategory="2"
android:title="Settings"
app:showAsAction="always" />
<item
android:id="@+id/search"
android:icon="@drawable/ic_action_name"
android:orderInCategory="2"
android:title="Search"
app:showAsAction="always" />
<item
android:id="@+id/contact"
android:enabled="false"
android:orderInCategory="3"
android:title="Search Contact" />
<item
android:id="@+id/actions"
android:title="Actions">
<menu>
<item
android:id="@+id/composeEmail"
android:enabled="false"
android:title="Compose Email" />
<item
android:id="@+id/feedback"
android:title="Compose Email" />
</menu>
</item>
</menu>

31 | P a g e
activity_main.xml

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


<RelativeLayout

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:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Menus"
android:textSize="30sp"
android:textStyle="bold" />
</RelativeLayout>

32 | P a g e
MainActivity.kt
package com.example.appbar

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}

override fun onCreateOptionsMenu(menu: Menu?): Boolean {


menuInflater.inflate(R.menu.menu, menu)
return super.onCreateOptionsMenu(menu)
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {


val id = item?.itemId
if (id == R.id.search) {
Toast.makeText(this, "Search", Toast.LENGTH_SHORT).show()
} else if (id == R.id.composeEmail) {
Toast.makeText(this, "Compose Email", Toast.LENGTH_SHORT).show()
} else if (id == R.id.feedback) {
Toast.makeText(this, "Feedback", Toast.LENGTH_SHORT).show()
} else if (id == R.id.settings) {
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show()
}
return super.onOptionsItemSelected(item)
}

33 | P a g e
Output

Q. Create an android application to display Alert Dialog on pressing the Back button .

activity_main.xml

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


<RelativeLayout

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:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Press the back button of your phone"
android:textSize="30sp"
android:textStyle="bold" />
</RelativeLayout>

34 | P a g e
MainActivity.kt

Output
package com.example.alertdialog

import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}

// Declare the onBackPressed method when the back button is pressed this
method will call
override fun onBackPressed() {
// Create the object of AlertDialog Builder class
val builder = AlertDialog.Builder(this)
// Set the message show for the Alert time
builder.setMessage("Do you want to exit ?")
// Set Alert Title
builder.setTitle("Alert !")
// Set Cancelable false for when the user clicks on the outside the
Dialog Box then it will remain show
builder.setCancelable(false)
// Set the positive button with yes name Lambda OnClickListener method
is use of DialogInterface interface.
builder.setPositiveButton("Yes") {
// When the user click yes button then app will close
dialog, which ->
finish()
}

// Set the Negative button with No name Lambda OnClickListener method


is use of DialogInterface interface.
builder.setNegativeButton("No") {
// If user click no then dialog box is canceled.
dialog, which ->
dialog.cancel()

// Create the Alert dialog


val alertDialog = builder.create()
// Show the Alert Dialog box
alertDialog.show()
}
}

35 | P a g e
36 | P a g e
PRACTICAL 7
Programs on Intents, Events Listeners and Adapters
Q. Create an android application to pass the data from current application to another
application using intent.

Create 2 activities

37 | P a g e
38 | P a g e
activity_main.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Multiple Activities"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.14" />

<Button
android:id="@+id/activity1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="172dp"
android:text="Activity 1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.528"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

<Button
android:id="@+id/activity2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Activity 2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/activity1" />

</androidx.constraintlayout.widget.ConstraintLayout>

39 | P a g e
MainActivity.kt

package com.example.multipleactivities

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val activity1 = findViewById<Button>(R.id.activity1)


activity1.setOnClickListener{
val intent = Intent(this, MainActivity2::class.java)
startActivity(intent)
}

val activity2 = findViewById<Button>(R.id.activity2)


activity2.setOnClickListener{
val intent = Intent(this, MainActivity3::class.java)
startActivity(intent)
}
}
}

activity_main2.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity2">

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

40 | P a g e
MainActivity2.kt

package com.example.multipleactivities

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast

class MainActivity2 : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
Toast.makeText(this, "Activity 2", Toast.LENGTH_LONG).show()
}
}

activity_main3.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity3">

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

41 | P a g e
MainActivity3.kt

package com.example.multipleactivities

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast

class MainActivity3 : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main3)
Toast.makeText(this, "Activity 3", Toast.LENGTH_LONG).show()
}
}

42 | P a g e
Practical 8
Programs on Services, notification and broadcast
receivers
Q. Create an android application which automatically notify the user when
Aeroplane mode is turned on or off using broadcast receiver.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_name"
android:textSize="80dp"
android:textColor="@color/purple_200"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

43 | P a g e
AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcastreceiver">

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


<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/Theme.BroadcastReceiver">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

44 | P a g e
MainActivity.kt

package com.example.broadcastreceiver

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.net.ConnectivityManager
import android.widget.Toast

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val c =
applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as
ConnectivityManager

val networkInfo = c.activeNetworkInfo


if (networkInfo != null && networkInfo.isConnected) {
if (networkInfo.type ==
ConnectivityManager.TYPE_MOBILE
) {
Toast.makeText(
applicationContext, "Mobile",
Toast.LENGTH_LONG
).show()
} else if (networkInfo.type ==
ConnectivityManager.TYPE_WIFI
) {
Toast.makeText(
applicationContext, "Wifi",
Toast.LENGTH_LONG
).show()
}
} else {
Toast.makeText(applicationContext, "You're offline",
Toast.LENGTH_SHORT).show()
}
}
}

45 | P a g e
Output

Q. Create the background service android application to play the ringtone/music

Create a folder raw inside drawable and add a sound file.


Create a file BackgroundService.java

activity_main.xml

46 | P a g e
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp">
<Button
android:id="@+id/playSound"
android:onClick="PlayBackgroundSound"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Run background Sound"/>
<TextView
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold"
android:text="Playing Music in Background"/>
</LinearLayout>

47 | P a g e
BackgrounService.java

package com.example.backgroundservice;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class BackgroundSoundService extends Service {


MediaPlayer mediaPlayer;

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.sound);
mediaPlayer.setLooping(true); // Set looping
mediaPlayer.setVolume(100, 100);
}

public int onStartCommand(Intent intent, int flags, int startId) {


mediaPlayer.start();
Toast.makeText(getApplicationContext(), "Playing Bohemian Rashpody in the
Background", Toast.LENGTH_SHORT).show();
return startId;
}

@Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
}

@Override
public void onLowMemory() {
}
}

48 | P a g e
MainActivity.kt

package com.example.backgroundservice

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

var playSound = findViewById<Button>(R.id.playSound)


playSound.setOnClickListener(){
val intent = Intent(this@MainActivity,
BackgroundService::class.java)
startService(intent)
}
}
}

AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.backgroundservice">

<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/Theme.BroadcastReceiver">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>
<service android:name=".BackgroundService" />
</manifest>

49 | P a g e
Q. Create an android application to generate notification

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Notification"
android:id="@+id/btn_notify"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Output

50 | P a g e
PRACTICAL 9
Database Programming with SQLite
Q. Create an android application using sqlite database to manage the students data
by using insert, update and delete operations and display the data in scroll view.
Allow user to insert Name and Age of the student.

User.kt

package com.example.database

class User {
var id : Int = 0
var name : String = ""
var age : Int = 0

constructor(name:String,age:Int){
this.name = name
this.age = age
}

constructor(){
}

51 | P a g e
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40dp"
android:text="Name"/>
<EditText
android:id="@+id/etvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:padding="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40dp"
android:text="Age"/>
<EditText
android:id="@+id/etvAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:inputType="number"
android:padding="10dp" />
<Button
android:id="@+id/btn_insert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:padding="10dp"
android:background="@color/purple_200"
android:text="Insert" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="3">
<Button
android:id="@+id/btn_read"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@color/purple_200"
android:layout_margin="4dp"
android:text="Read"/>
<Button
android:id="@+id/btn_update"
android:layout_width="match_parent" 52 | P a g e
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="4dp"
android:background="@color/purple_200"
MainActivity.kt
package com.example.database

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val context = this
var btn_insert = findViewById<Button>(R.id.btn_insert)
var etvName = findViewById<TextView>(R.id.etvName)
var etvAge = findViewById<TextView>(R.id.etvAge)
var tvResult = findViewById<TextView>(R.id.tvResult)
var btn_read = findViewById<Button>(R.id.btn_read)
var btn_update = findViewById<Button>(R.id.btn_update)
var btn_delete = findViewById<Button>(R.id.btn_delete)
var db = DataBaseHandler(context)
btn_insert.setOnClickListener({
if (etvName.text.toString().length > 0 &&
etvAge.text.toString().length > 0
) {
var user = User(etvName.text.toString(),
etvAge.text.toString().toInt())
db.insertData(user)
} else {
Toast.makeText(context, "Please Fill All Data's",
Toast.LENGTH_SHORT).show()
}
})

btn_read.setOnClickListener({
var data = db.readData()
tvResult.text = ""
for (i in 0..(data.size - 1)) {
tvResult.append(
data.get(i).id.toString() + " " + data.get(i).name + " " +
data.get(
i
).age + "\n"
)
}
})

btn_update.setOnClickListener({
db.updateData()
btn_read.performClick()
})

btn_delete.setOnClickListener({
db.deleteData()
btn_read.performClick()
})
}

53 | P a g e
DatabaseHandler.kt
package com.example.database

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.widget.Toast

val DATABASE_NAME = "MyDB"


val TABLE_NAME = "Users"
val COL_NAME = "name"
val COL_AGE = "age"
val COL_ID = "id"

class DataBaseHandler(var context: Context) : SQLiteOpenHelper(context, DATABASE_NAME,


null, 1) {
override fun onCreate(db: SQLiteDatabase?) {

val createTable = "CREATE TABLE " + TABLE_NAME + " (" +


COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COL_NAME + " VARCHAR(256)," +
COL_AGE + " INTEGER)"
db?.execSQL(createTable)
}

override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {


}

fun insertData(user: User) {


val db = this.writableDatabase
var cv = ContentValues()
cv.put(COL_NAME, user.name)
cv.put(COL_AGE, user.age)
var result = db.insert(TABLE_NAME, null, cv)
if (result == -1.toLong()) {
Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show()
}
}

@SuppressLint("Range")
fun readData(): MutableList<User> {
var list: MutableList<User> = ArrayList()

val db = this.readableDatabase
val query = "Select * from " + TABLE_NAME
val result = db.rawQuery(query, null)
if (result.moveToFirst()) {
do {
var user = User()
user.id = result.getString(result.getColumnIndex(COL_ID)).toInt()
user.name = result.getString(result.getColumnIndex(COL_NAME))
user.age = result.getString(result.getColumnIndex(COL_AGE)).toInt()
list.add(user)
} while (result.moveToNext())
}
result.close()
db.close()
return list 54 | P a g e
}

fun deleteData() {
val db = this.writableDatabase
Output

55 | P a g e
PRACTICAL 10
Programming threads, handles and asynchronized
programs
Q. Create an android application to generate any random number with some time

delay using thread.

activity_main.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

56 | P a g e
MainActivity.kt

package com.example.thread

import android.os.Bundle
import android.os.Handler
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.util.*

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var textChanger = findViewById<TextView>(R.id.text)
val myRandom = Random()
var handler = Handler()
handler.postDelayed(
Runnable {
textChanger.setText((myRandom.nextInt(100)));
},
5000
)
}
}

57 | P a g e
Output

58 | P a g e
PRACTICAL 11
Programming Media API and Telephone API
Q. Create a media API in android to play an audio/video file

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp">
<Button
android:id="@+id/playSound"
android:onClick="PlayBackgroundSound"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Run background Sound"/>
<TextView
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold"
android:text="Playing Music in Background"/>
</LinearLayout>

59 | P a g e
BackgroundService.java

package com.example.backgroundservice;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class BackgroundSoundService extends Service {


MediaPlayer mediaPlayer;

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.sound);
mediaPlayer.setLooping(true); // Set looping
mediaPlayer.setVolume(100, 100);
}

public int onStartCommand(Intent intent, int flags, int startId) {


mediaPlayer.start();
Toast.makeText(getApplicationContext(), "Playing Bohemian Rashpody in the
Background", Toast.LENGTH_SHORT).show();
return startId;
}

@Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
}

@Override
public void onLowMemory() {
}
}

60 | P a g e
MainActivity.kt

package com.example.backgroundservice

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

var playSound = findViewById<Button>(R.id.playSound)


playSound.setOnClickListener(){
val intent = Intent(this@MainActivity,
BackgroundService::class.java)
startService(intent)
}
}
}

AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.backgroundservice">

<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/Theme.BroadcastReceiver">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>
<service android:name=".BackgroundService" />
</manifest>

61 | P a g e
Output

62 | P a g e
PRACTICAL 12
Programming Security and permissions
Q. Create an android application with two buttons and each will request the permission to
access the device data such as user’s file, camera.

activity_main.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="140dp"
android:text="Ask permission for Camera"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/storage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ask permission for storage"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/camera" />

</androidx.constraintlayout.widget.ConstraintLayout>

63 | P a g e
package com.example.permisions

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import android.Manifest

private const val PERMISSION_REQUEST = 10

class MainActivity : AppCompatActivity() {

companion object {
private const val CAMERA_PERMISSION_CODE = 100
private const val STORAGE_PERMISSION_CODE = 101
}

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Defining Buttons
val storage: Button? = findViewById(R.id.storage)
val camera: Button? = findViewById(R.id.camera)

// Set Buttons on Click Listeners


storage?.setOnClickListener {
checkPermission(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
STORAGE_PERMISSION_CODE
)
}
camera?.setOnClickListener {
checkPermission(
Manifest.permission.CAMERA,
CAMERA_PERMISSION_CODE
)
}
}

// Function to check and request permission.


private fun checkPermission(permission: String, requestCode: Int) {
if (ContextCompat.checkSelfPermission(
this@MainActivity,
permission
) == PackageManager.PERMISSION_DENIED
) {

// Requesting the permission


ActivityCompat.requestPermissions(this@MainActivity, arrayOf(permission),
requestCode)
} else {
Toast.makeText(this@MainActivity, "Permission already granted",
Toast.LENGTH_SHORT)
.show() 64 | P a g e
}
}

// This function is called when the user accepts or decline the permission.
AndroidManifext.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.permisions">

<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<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/Theme.Permisions">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

65 | P a g e
PRACTICAL 13
Programming Network Communications and
Services (JSON)
Handling connectivity errors in Android apps with Kotlin:
Open your build.gradle file and add the following dependencies:

implementation
'com.android.support:design:27.1.1'
implementation
'com.squareup.retrofit2:retrofit:2.3.0'
implementation
'com.squareup.retrofit2:converter-
scalars:2.3.0'

Open your AndroidManifest.xml file and add the permissions like so:

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.permisions">

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

[…]
</manifest>

When there is a network connection, we will fetch data from an API. Let’s set up an interface to
hold the endpoints we will access. Create a new Kotlin file named ApiService and paste this:
import retrofit2.Call import retrofit2.http.GET

interface ApiService { @GET(".")


fun getFeeds(): Call<String>
}

66 | P a g e
For this demo, we are only going to access one endpoint, which is equivalent to our base URL. It’s
for this reason we used a dot instead of the usual /some-url in the @GET annotation.

When these items are fetched, we will display the items in a list. We, therefore, need a
RecyclerView in the layout and a matching adapter. Create a new Kotlin file named
RecyclerAdapter and paste this:

import android.support.v7.widget.RecyclerView import android.view.LayoutInflater


import android.view.View import android.view.ViewGroup import android.widget.TextView

class RecyclerAdapter : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() { private


var list = ArrayList<String>()
fun setItems(newList: ArrayList<String>){
this.list = newList this.notifyDataSetChanged()
}

override fun getItemCount() = list.size

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val


view = LayoutInflater.from(parent.context)
.inflate(android.R.layout.simple_list_item_1, parent, false)

return ViewHolder(view)
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {


holder.textView.text = list[position]
}

inner class ViewHolder(itemView: View?): RecyclerView.ViewHolder(itemView) { var


textView: TextView = itemView!!.findViewById(android.R.id.text1)
}

67 | P a g e
the adapter handles the display of items on a list. It has some overridden methods like:

• getItemCount – to tell the size of the list to be populated.


• onCreateViewHolder – used to choose a layout for a list row.
• onBindViewHolder – to bind data to each row depending on the
position, etc.
Next, we will update the layout of our MainActivity‘s activity_main.xml file like so:
<?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">

<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/no_internet_connection" />

</android.support.constraint.ConstraintLayout>

The layout contains a RecyclerView for our list items and an ImageView to show an error
message.

68 | P a g e
We also need an error message image. Once you have an image, rename the file to
no_internet_connection and save it to your drawable folder:
NameOfProject/app/src/main/res/drawable.
For us to monitor when the connectivity changes, we need broadcast receivers. Broadcast
receivers are components that allow you to register and listen to Android system and application
events. Usually, the Android system sends broadcast events when various system events occur
and your app needs to register to get these events.
Let’s register a listener to be triggered when the internet connection is online or offline.
Open your MainActivity file and paste the following code:

import android.content.BroadcastReceiver import android.content.Context


import android.content.Intent import android.content.IntentFilter
import android.net.ConnectivityManager
import android.support.v7.app.AppCompatActivity import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager import android.util.Log
import android.view.View
import kotlinx.android.synthetic.main.activity_main.* import okhttp3.OkHttpClient
import org.json.JSONObject import retrofit2.Call import retrofit2.Callback import
retrofit2.Response import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory

class MainActivity : AppCompatActivity() {

private val arrayList = ArrayList<String>() private val adapter =


RecyclerAdapter() private val retrofit = Retrofit.Builder()
.baseUrl("https://api.reddit.com/")
.addConverterFactory(ScalarsConverterFactory.create())
.client(OkHttpClient.Builder().build())
.build()

private var broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {


override fun onReceive(context: Context, intent: Intent) {
val notConnected = intent.getBooleanExtra(ConnectivityManager
.EXTRA_NO_CONNECTIVITY, false)
if (notConnected) { disconnected()
} else {
connected()
}
}
}

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)
setupRecyclerView()
}

69 | P a g e
Above, we initialized some variables:

• arrayList – we will add fetched items


to this list.
• adapter – this is the instance of the
adapter class. retrofit – a Retrofit
instance.
• broadcastReciever – this instance
implements the onRecieve callback.
This callback method is called when
the system has notified us of a change
in the network connection. In the
callback, we then check to know the
connectivity status thereby calling
either a private connected or
disconnected function.

After creating the broadcast receiver, we have to register it to get updates and unregister if
there are no more activities. To do this, add the following functions to the code above in the

MainActivity.kt:

override fun onStart() { super.onStart()


registerReceiver(broadcastReceiver,
IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
}

override fun onStop() { super.onStop()


unregisterReceiver(broadcastReceiver)
}

70 | P a g e
In the onCreate function, we set up our RecyclerView by calling the setupRecyclerView.
Create a private function in the MainActivity class and set it up like this:

private fun setupRecyclerView(){


with(recyclerView){
layoutManager = LinearLayoutManager(this@MainActivity)
adapter = [email protected]
}
}

Remember we mentioned the connected and disconnected functions earlier in this post. We
will now add them to the class. Add them to the MainActivity file like so:

private fun setupRecyclerView(){


with(recyclerView){
layoutManager = LinearLayoutManager(this@MainActivity)
adapter = [email protected]
}
}

The disconnected function is called when there is no network connection. It hides the
RecyclerView and shows the ImageView. The connected function is called when there is an
active internet connection. It shows the RecyclerView, hides the ImageView, and finally calls
the fetchFeeds function.
Next, in the same file, paste the following code:

private fun fetchFeeds() {


retrofit.create(ApiService::class.java)
}

71 | P a g e
getFeeds()
.enqueue(object : Callback<String> {
override fun onFailure(call: Call<String>, t: Throwable) {
Log.e("MainActivityTag", t.message)
}

override fun onResponse(call: Call<String>?, response: Response<String>) {


addTitleToList(response.body()!!)
}

})

This function calls the API to get data. When the call is successful, we have
another function that helps us add the title of the posts gotten from the endpoint
to our list and then to our adapter. Create a function named addTitleToList and
set it up like so:

private fun addTitleToList(response: String) {


val jsonObject = JSONObject(response).getJSONObject("data") val children =
jsonObject.getJSONArray("children")

for (i in 0..(children.length()-1)) {
val item =
children.getJSONObject(i).getJSONObject("data").getString("title")
arrayList.add(item)
adapter.setItems(arrayList)
}
}

72 | P a g e

You might also like