Sunteți pe pagina 1din 58

Notes By: Prof. Nikita M.

Chaudhari Advanced Mobile Programming


S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

Practical
1:
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.

Creating a
Project:

Step 1: Create New Project in Android


Studio

Open Android Studio and go to the file menu>>new>>new


project

Step 2: Configure Your New


Project

Add your application details over here and hit "Next"


button.

i.e.Application name , Company domain, Package name , Project location


And check Include Kotlin support
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.
Step 3: Target Android
Devices

Select the form factors your app will be run on. Here, you can select device type
for your android application. And at the same time, you select Minimum SDK
which will be supported by your android application.

When you select Minimum SDK, Android studio will give you some active
android devices percentage that will support your android application.
Otherwise, you can also click on "Help me choose" button for more information
about android platform versions.
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.
Hit "Next" button once you are
done.

Step 4: Add
activity

This screen suggests you add any activity at first. If you don’t want to add any
activity at starting, you can select Add no activity option. If you have selected
Phone and Tablet in option in the last screen then it will display the only phone
related suggestions. Select Activity as per your project requirements.

For example, select Google Maps Activity for google map project, Blank
Activity for blank project etc.
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.
If you are done with it, click "Next"
button.

Step 5: Customize the


Activity

Here, you can customize your selected activity. You can change your Activity
name from here. And also you can change Layout name (that will be attached to
your activity), Title (Title of the activity), Menu Resource Name (Menu’s resource
file name).If you want to add fragment to your activity then select Use a fragment
option given below.
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

Step 6:
Finish

Finish the
process.

Activity_Main.Kt

package
com.example.nikita.broadcast

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

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"?>


<android.support.constraint.ConstraintLa
yout
xmlns:android="http://schemas.android.com/apk/res/an
droid" xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextVie
w
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="par
ent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

</android.support.constraint.ConstraintLay
out>

Apk in
avd:

Android
Components:
Components of an Android
Application

There are some necessary building blocks that an Android application consists
of. These loosely coupled components are bound by the application manifest file
which contains description of each component and how they interact. The
manifest file also contains the app’s metadata, its hardware configuration and
platform requirements, external libraries and required permissions.
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

There are the following main components of an android


app:-

Activities
-

Activities are said to be the presentation layer of our applications. The UI of our
application is build around one or more extensions of the Activity class. By using
Fragments and Views, activities set the layout and display the output and also
respond to the users actions. An activity is implemented as a subclass of class
Activity.

public class MainActivity extends


Activity {

Service

s-

These are like invisible workers of our app. These components run at backend,
updating your data sources and Activities, triggering Notification and also
broadcast Intents. They also perform some tasks when applications are not
active. A service can be used as a subclass of class Service:
public class ServiceName extends
Service {

} ​Content

Providers-

It is used to manage and persist the application data also typically


interact with SQL database. They are also responsible for sharing the
data beyond the application boundaries. The Content Providers of a
particular application can be configured to allow access from other
applications, and the Content Providers exposed by other applications
can also be configured. A content provider should be a sub class of the
class ContentProvider.

public class contentProviderName extends


ContentProvider {

public void
onCreate(){}

Broadcast
Receivers-

They are known to be intent listeners as they enable your application to listen
the Intents that satisfy the matching criteria specified by us. Broadcast Receivers
make our application to react to any received Intent thereby making them perfect
for creating event driven applications.

Create and manage virtual


devices
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

To open the AVD Manager, do one of the


following:
Select Tools > AVD
Manager.

Click AVD Manager in the toolbar.

Enable the USB


Debugging

Enable the USB Debugging option under Settings > Developer


options.

For Android 4.2 and newer, Developer options is hidden by default; use the
following steps:

On the device, go to Settings > About


<device>.

Tap the Build number seven times to make Settings > Developer options
available.

Then enable the USB Debugging


option.

Tip: You might also want to enable the Stay awake option, to prevent your
Android device from sleeping while plugged into the USB port.

________________________________________________________________
________

BroadCast
Receiver
mainActivity.k
t

MainActivity code, no needs to do


anything
package
com.example.nikita.broadcast

import
android.support.v7.app.AppCompatActivity

import
android.os.Bundle

class MainActivity : AppCompatActivity()


{

override fun onCreate(savedInstanceState:


Bundle?) {

super.onCreate(savedInstanceS
tate)

setContentView(R.layout.activity_ma
in)

}
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

Activity_main.xm

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


<​android.support.constraint.ConstraintLa
yout
xmlns:​android​=​"http://schemas.android.com/apk/res/an
droid" ​xmlns:​tools​=​"http://schemas.android.com/tools"
xmlns:​app​=​"http://schemas.android.com/apk/res-auto"
android​:layout_width=​"match_parent"
android​:layout_height=​"match_parent"
tools​:context=​".MainActivity"​>

<​TextVie
w
android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content"
android​:text=​"Hello World!"
app​:layout_constraintBottom_toBottomOf=​"par
ent"
app​:layout_constraintLeft_toLeftOf=​"parent"
app​:layout_constraintRight_toRightOf=​"parent"
app​:layout_constraintTop_toTopOf=​"parent"​/>

</​android.support.constraint.ConstraintLay
out​>

MyReceiver.
kt

package
com.example.nikita.broadcast

import ​android.content.BroadcastReceiver
import ​android.content.Context ​import
android.content.Intent ​import
android.support.v7.app.AppCompatActivity
import ​android.os.Bundle ​import
android.widget.Toast

class ​MyReceiver :
BroadcastReceiver() {
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

override fun ​onReceive(context: Context, intent:


Intent) {
​ ODO: This method is called when the BroadcastReceiver is
// T
receiving /​ / an Intent broadcast. T
​ oast.makeText(context,
"Broadcast : Flight mode changed."​,
Toast.​LENGTH_LONG​).show()

} } ​AndroidManifest.xml

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


​ ​manifest
xmlns:​android​=​"http://schemas.android.com/apk/res/android"
package=​"com.example.nikita.broadca
st"​>

<​applicatio
n
android​:allowBackup=​"true"
android​:icon=​"@mipmap/ic_launcher"
android​:label=​"@string/app_name"
android​:roundIcon=​"@mipmap/ic_launcher_roun
d" ​android​:supportsRtl=​"true"
android​:theme=​"@style/AppTheme"​> <​activity
android​:name=​".MainActivity"​>
<​intent-filter
>
<​action
android​:name=​"android.intent.action.MAIN"​/>

<​category ​android​:name=​"android.intent.category.LAUNCHER"​/>
</​intent-filter​> </​activity​> <​receiver
android​:name=​".MyReceiver"
android​:enabled=​"true"
android​:exported=​"true"​>
<​intent-filter​>
<​action ​android​:name=​"android.intent.action.AIRPLANE_MODE"​/>
</​intent-filter​> </​receiver​> </​application​>

</​manifest
>
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

Practical
2:

Programming
Resources

Android Resources: (Color, Theme, String, Drawable, Dimension,


Image)

Resources are used for anything from defining colors, images,


layouts, menus, and string values.

colo
r/

XML files that define a state list of colors. They are saved in res/color/ and
accessed from the R.color class.

The value always begins with a pound (#) character and then followed by the
Alpha-Red- Green-Blue information in one of the following formats:

#​RG
B

#​ARG
B
#​RRGGB
B

#​AARRGGB
B

Drawable
s

A ​drawable i​ s a graphic that can be drawn to the screen. You retrieve


drawables using APIs such as getDrawable(int) , and you apply a drawable to
an XML resource using attributes such as android:drawable and android:icon.

Image files like .png, .jpg, .gif or XML files that are compiled into bitmaps,
state lists, shapes, animation drawable. They are saved in res/drawable/ and
accessed from the R.drawable class.

Dimensio
n

A dimension value defined in XML. A dimension is specified with a number


followed by a unit of measure. For example: 10px, 2in, 5sp. The following units of
measure are supported by Android:

d
p
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

Density-independent Pixels - An abstract unit that is based on the physical


density of the screen. These units are relative to a 160 dpi (dots per inch)
screen, on which 1dp is roughly equal to 1px. Using dp units (instead of px units)
is a simple solution to making the view dimensions in your layout resize properly
for different screen densities. In other words, it provides consistency for the
real-world sizes of your UI elements across different devices.
sp ​Scale-independent Pixels - This is like the dp unit, but it is also scaled by the

user's font size


​ preference. It is recommend you use this unit when specifying
font sizes, so they will be adjusted for both the screen density and the user's
preference.

pt ​Points - 1/72 of an inch based on the physical size of the screen, assuming a

72dpi density screen.


px ​Pixels - Corresponds to actual pixels on the screen. This unit of measure is

not recommended
​ because the actual representation can vary across devices;
each devices may have a different number of pixels per inch and may have
more or fewer total pixels available on the screen.

mm ​Millimeters - Based on the physical size of

the screen.

in ​Inches - Based on the physical size of the

screen.

String
resources

A string resource provides text strings for your application with optional text
styling and formatting. There are three types of resources that can provide your
application with strings:

Strin
g

XML resource that provides a single


string.

String
Array

XML resource that provides an array of


strings.
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

THEME

To set a theme for an Activity or set of Activities, you need to modify


the AndroidManifest.xml file.

In this task, you will add the "night mode" theme to your app, which will allow
the users to use a low contrast version of your app that is easier on the eyes at
night time, as well as make a few polishing touches to the User Interface.

MainAcivity.kt
package ​com.example.nikita.practical2_res

import ​android.support.v7.app.AppCompatActivity ​import


android.os.Bundle

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"​?>
<​android.support.constraint.ConstraintLayout
xmlns:​android​=​"http://schemas.android.com/apk/res/android"
xmlns:​tools​=​"http://schemas.android.com/tools"
xmlns:​app​=​"http://schemas.android.com/apk/res-auto"
android​:layout_width=​"match_parent" ​android​:layout_height=​"match_parent"
tools​:context=​".MainActivity" ​android​:background=​"@drawable/download"​>
<​TextView
android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content"

app​:layout_constraintBottom_toBottomOf=​"parent"
app​:layout_constraintLeft_toLeftOf=​"parent"
app​:layout_constraintRight_toRightOf=​"parent"
app​:layout_constraintTop_toTopOf=​"parent"
android​:text=​"@string/hello"
android​:textColor=​"@color/red"
style=​"@style/custom"​/>

</​android.support.constraint.ConstraintLayout​>

Styles.x
ml
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

<​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​> </​style​> <​style ​name=​"custom"​>
<​item ​name=​"android:textSize"​>100dp</​item​> <​item
name=​"android:textColor"​>#008</​item​> </​style​>

</​resources​>

Colors.x
ml
<?​xml version=​"1.0" ​encoding=​"utf-8"​?>
<​resources​>
<​color ​name=​"colorPrimary"​>#168500</​color​> <​color
name=​"colorPrimaryDark"​>#00574B</​color​> <​color
name=​"colorAccent"​>#D81B60</​color​> <​color
name=​"red"​>#8adcd1</​color​> </​resources​>

Strings.x
ml
<​resources​>
<​string ​name=​"app_name"​>practical2_res</​string​> <​string
name=​"hello"​>Hello!###</​string​>
</​resources​>

Output
:
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

Method Description

onCreate called when activity is first created.

onStart called when activity is becoming visible to the user.

onResume called when activity will start interacting with the user.

onPause called when activity is not visible to the user.

onStop called when activity is no longer visible to the user.

onRestart called after your activity is stopped, prior to start.

onDestroy called before the activity is destroyed.

Android Activity
Lifecycle

Android Activity Lifecycle ​is controlled by 7 methods of


android.app.Activity class. The android Activity is the subclass of
ContextThemeWrapper class.

An activity is the single screen in android. It is like window or frame of


Java.

By the help of activity, you can place all your UI components or widgets in a
single screen.

The 7 lifecycle method of Activity describes how activity will behave at different
states.

Android Activity Lifecycle


methods

Let's see the 7 lifecycle methods of android


activity.
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.
MainActivity.kt
package ​com.example.nikita.practical3_lifecycle

import ​android.support.v7.app.AppCompatActivity ​import


android.os.Bundle ​import ​android.util.Log

class ​MainActivity : AppCompatActivity() {

override fun ​onCreate(savedInstanceState: Bundle?) {


super​.onCreate(savedInstanceState)
setContentView(R.layout.​activity_main)​
print(​"onCreate"​);
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

} ​override fun ​onStart() {


super​.onStart() print(​"onStart"​) }

override fun ​onResume() {


super​.onResume()
print(​"onResume"​) } ​override fun

onPause() { super​
​ .onPause()

print(​"onPause"​) } ​override fun

onStop() { ​super​.onStop()
print(​"onStop"​) } ​override fun

onRestart() { super​
​ .onRestart()

print(​"onRestart"​) } ​override fun

onDestroy() { ​super​.onDestroy()
print(​"onDestroy"​) } ​fun

print(msg: String){

Log.d(​"Activity State "​,msg) } } ​Output:

B) ​Multiple

Activities:
MainActivity.k
t
package ​com.example.nikita.multipleactivity
import ​android.content.Intent ​import
android.support.v7.app.AppCompatActivity ​import
android.os.Bundle ​import ​android.view.View ​import
android.widget.Button

class ​MainActivity : AppCompatActivity() {


Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

override fun ​onCreate(savedInstanceState: Bundle?) {


super​.onCreate(savedInstanceState)
setContentView(R.layout.​activity_main)​ ​//initialize ​val ​mButton =
findViewById<View>(R.id.​button​) ​as ​Button ​//handle onClick

mButton.setOnClickListener ​{
//intent to start NewActivity ​startActivity(Intent(​this​@MainActivity​, NewActivity::​class​.​java​)) ​} ​} }

activity_main.xml

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


<​LinearLayout
xmlns:​android​=​"http://schemas.android.com/apk/res/android"
xmlns:​tools​=​"http://schemas.android.com/tools"
xmlns:​app​=​"http://schemas.android.com/apk/res-auto"
android​:orientation=​"vertical" ​android​:gravity=​"center"
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"​/> <​Button
android​:id=​"@+id/button"
android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content" ​android​:text=​"Open
New Activity" ​/> </​LinearLayout​>

Create a new Activity ” NewActivity.kt” .Add following


code:

NewActivity.
kt
package ​com.example.nikita.multipleactivity

import ​android.support.v7.app.AppCompatActivity ​import


android.os.Bundle

class ​NewActivity : AppCompatActivity() {

override fun ​onCreate(savedInstanceState: Bundle?) {


super​.onCreate(savedInstanceState)
setContentView(R.layout.​activity_new)​ } }
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

activity_new.x
ml
<?​xml version=​"1.0" ​encoding=​"utf-8"​?>
<​LinearLayout
xmlns:​android​=​"http://schemas.android.com/apk/res/android"
xmlns:​tools​=​"http://schemas.android.com/tools"
xmlns:​app​=​"http://schemas.android.com/apk/res-auto"
android​:layout_width=​"match_parent"
android​:layout_height=​"match_parent"

tools​:context=​".NewActivity"​>

<​TextView
android​:text=​"Welcome on 2nd Activity" ​android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content" ​tools​:layout_editor_absoluteY=​"137dp"
tools​:layout_editor_absoluteX=​"163dp" ​android​:id=​"@+id/textView"​/> </​LinearLayout​>

Android Manifest.xml ​<?x​ ml version=​"1.0" ​encoding=​"utf-8"​?> <​ ​manifest


xmlns:​android​=​"http://schemas.android.com/apk/res/android"
package=​"com.example.nikita.multipleactivity"​>

<​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"​/>
<​category ​android​:name=​"android.intent.category.LAUNCHER"​/> </​intent-filter​>
</​activity​> <​activity ​android​:name=​".NewActivity"​> </​activity​> </​application​>

</​manifest​>
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

PRACTICAL 4

Programs related to different Layouts


Coordinate, Linear, Relative, Table, Absolute,
Frame, List View, Grid View.

LinearLayo
ut

Android LinearLayout ​is used for application UI. Its a view group that aligns and
contain nested widget or layout in a single direction , ​Vertically ​or ​horizontally​.

You have to specify the layout orientation with the ​android:orientation ​attribute. If you
don’t add orientation then default ​Horizontal ​will works.

Activity_main.xm
l
<?​xml version=​"1.0" ​encoding=​"utf-8"​?>
<​LinearLayout
xmlns:​android​=​"http://schemas.android.com/apk/res/android"
xmlns:​tools​=​"http://schemas.android.com/tools"
xmlns:​app​=​"http://schemas.android.com/apk/res-auto"
android​:layout_width=​"match_parent" ​android​:layout_height=​"match_parent"

android:orientation="vertical"​/” ​horizontal​”
tools​:context=​".MainActivity"​>

<​Button ​android​:id=​"@+id/btnStartService" ​LinearLayout ​Output:


android​:layout_width=​"270dp"
android​:layout_height=​"wrap_content"
android​:text=​"start_service"​/>

<​Button ​android​:id=​"@+id/btnPauseService"
android​:layout_width=​"270dp"
android​:layout_height=​"wrap_content"
android​:text=​"pause_service"​/>

<​Button ​android​:id=​"@+id/btnStopService"
android​:layout_width=​"270dp"
android​:layout_height=​"wrap_content"
android​:text=​"stop_service"​/>

</​LinearLayout​>

MainActivity.kt(No need to change) ​package


com.example.nikita.diffactivity

import ​android.support.v7.app.AppCompatActivity ​import


android.os.Bundle
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

class ​MainActivity : AppCompatActivity() {

override fun ​onCreate(savedInstanceState: Bundle?) {


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

RelativeLayout:
Android RelativeLayout ​is provide flexibility to arrange a child views relatively to each
others. Means you can align child view left, right , below and above to relative another
views or parent layout. ​RelativeLayout ​is a very important component in term of design
user interface in android app. Because it can eliminate nested views and groups. Its
Keep Layout Hierarchy flat, which help to improve performance of android app.

Relative.xml: (​for this create new xml file. Give Root tag as
”RelativeLayout” )

<?​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
RelativeLayout ​Output:
android​:id=​"@+id/tv_label"
android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content"
android​:layout_alignParentTop=​"true"
android​:layout_centerHorizontal=​"true"
android​:text=​"Login" ​android​:textSize=​"18sp"
android​:layout_margin=​"8dp"​/>

<​EditText
android​:id=​"@+id/et_id"
android​:layout_width=​"match_parent"
android​:layout_height=​"wrap_content"
android​:layout_margin=​"8dp"
android​:layout_below=​"@+id/tv_label"
android​:ems=​"10" ​android​:hint=​"Enter Id"
android​:inputType=​"textEmailAddress" ​/>

<​EditText
android​:id=​"@+id/et_pass"
android​:layout_width=​"match_parent"
android​:layout_height=​"wrap_content"
android​:layout_below=​"@+id/et_id"
android​:layout_margin=​"8dp"
android​:ems=​"10" ​android​:hint=​"Enter
password"
android​:inputType=​"textPassword" ​/>

<​Button
android​:id=​"@+id/btn_login"
android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content"
android​:layout_below=​"@+id/et_pass"
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

android​:layout_margin=​"18dp"
android​:text=​"Login" ​/>

<​Button
android​:id=​"@+id/btn_reg"
android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content"
android​:layout_below=​"@+id/et_pass"
android​:layout_margin=​"18dp"
android​:layout_toRightOf=​"@+id/btn_login"
android​:text=​"Register" ​/>

</​RelativeLayout​>
MainActivity.kt(No need to change) ​package
com.example.nikita.diffactivity

import ​android.support.v7.app.AppCompatActivity ​import


android.os.Bundle

class ​MainActivity : AppCompatActivity() {

override fun ​onCreate(savedInstanceState: Bundle?) {


super​.onCreate(savedInstanceState)
setContentView(R.layout.​activity_main)​ } }
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming

S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T. ​ Table Layout :


In Android, Table Layout is used to arrange the group of views into rows and
columns. Table Layout containers do not display a border line for their columns,
rows or cells. A Table will have as many columns as the row with the most cells.
tablelayout.xml:
<?​xml version=​"1.0" ​encoding=​"utf-8"​?> ​<​TableLayout
xmlns:​android​=​"http://schemas.android.com/apk/res/android"
android​:layout_width=​"match_parent"
android​:layout_height=​"500dp"​> <​TableRow​>
<​Button
android​:id=​"@+id/btn1" ​android​:text=​"1"
android​:layout_gravity=​"center" ​/> <​Button
android​:id=​"@+id/btn2" ​android​:text=​"2"
android​:layout_gravity=​"center" ​/> <​Button
android​:id=​"@+id/btn3" ​android​:text=​"3"
android​:layout_gravity=​"center" ​/> </​TableRow​>
<​TableRow​>
<​Button
android​:id=​"@+id/btn4" ​android​:text=​"4"
android​:layout_gravity=​"center" ​/> <​Button
android​:id=​"@+id/btn5" ​android​:text=​"5"
android​:layout_gravity=​"center" ​/><​Button
android​:id=​"@+id/btn6" ​android​:text=​"6"
android​:layout_gravity=​"center" ​/> </​TableRow​>
<​TableRow​>
<​Button
android​:id=​"@+id/btn7" ​android​:text=​"7"
android​:layout_gravity=​"center" ​/> <​Button
android​:id=​"@+id/btn8" ​android​:text=​"8"
android​:layout_gravity=​"center" ​/><​Button
android​:id=​"@+id/btn9" ​android​:text=​"9"
android​:layout_gravity=​"center" ​/>
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

</​TableRow​>
<​TableRow ​>
<​Button
android​:text=​"Button" ​android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content" ​android​:id=​"@+id/button2"​/> <​Button
android​:text=​"Button" ​android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content" ​android​:id=​"@+id/button3"​/> <​Button
android​:text=​"Button" ​android​:layout_width=​"wrap_content" ​android​:layout_height=​"wrap_content"
android​:id=​"@+id/button4"​/> </​TableRow​> </​TableLayout​> ​MainActivity.kt

package ​com.example.nikita.diffactivity

import ​android.support.v7.app.AppCompatActivity ​import


android.os.Bundle ​import ​android.widget.Toast ​import
kotlinx.android.synthetic.main.tablelayout.*

class ​MainActivity : AppCompatActivity() {

override fun ​onCreate(savedInstanceState: Bundle?) {


super​.onCreate(savedInstanceState)
setContentView(R.layout.​tablelayout​)
btn1.setOnClickListener ​{
Toast.makeText(​this​,​"1"​,Toast.​LENGTH_LONG)​ .show(); ​}

btn2.setOnClickListener ​{
Toast.makeText(​this​,​"2"​,Toast.​LENGTH_LONG)​ .show(); ​}

btn3.setOnClickListener ​{

Toast.makeText(​this​,​"3"​,Toast.​LENGTH_LONG)​ .show(); ​} ​} } ​
Output:
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

Android FrameLayout
Android FrameLayout ​is one of the useful layouts provided by android system, which
allows User Interface widgets to be overlapped with each other. It’s used in cases such
as placing a TextView over an ImageView. This becomes quite difficult to implement
using LinearLayout or RelativeLayout since they place widgets adjacent to each other.
FrameLayout ​is designed to display a single item at a time. We can have multiple
elements within a framelayout but each element will be positioned based on the top left
of the screen. In ​FrameLayout,​ all the child views added are placed like ​stack​. The
most recent added are shown on top.

Activity_main.xm
l:

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


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

<​ImageView
android​:id=​"@+id/imageView"
android​:layout_width=​"match_parent"
android​:layout_height=​"495dp"
android​:scaleType=​"fitXY"
app​:srcCompat=​"@drawable/download" ​/>

<​TextView
android​:id=​"@+id/textview1"
android​:layout_width=​"match_parent"
android​:layout_height=​"match_parent"
android​:layout_margin=​"10dp"
android​:gravity=​"center_horizontal"
android​:text=​"Hello World!"
android​:textColor=​"@color/black"
android​:textSize=​"40sp" ​/>

<​Button
android​:id=​"@+id/button"
android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content"
android​:layout_gravity=​"center_horizontal"
android​:layout_marginTop=​"80dp" ​android​:text=​"Go
Book" ​/>

</​FrameLayout​>
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

ActivityMain.kt(no need to
change)
package ​com.example.nikita.frame

import ​android.support.v7.app.AppCompatActivity ​import


android.os.Bundle

class ​MainActivity : AppCompatActivity() {

override fun ​onCreate(savedInstanceState: Bundle?) {


super​.onCreate(savedInstanceState)
setContentView(R.layout.​activity_main)​ } }
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

ListView
:

ListView ​is a view group that displays a list of scrollable items. The list
items are automatically inserted to the list using an ​Adapter ​that pulls
content from a source such as an array or database query and converts
each item result into a view that's placed into the list.

Activity_main.xml: ​<?x​ ml 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"
xmlns:​app​=​"http://schemas.android.com/apk/res-auto"
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​:id=​"@+id/btn" ​android​:text=​"Click
me to view list"
android​:layout_marginTop=​"200dp"
android​:layout_marginLeft=​"90dp"​/>

</​android.support.constraint.ConstraintLayout​>

String.xml:
<​resources​>
<​string ​name=​"app_name"​>Listview</​string​> <​array
name=​"insert_list"​>
<​item​>one</​item​>
<​item​>two</​item​>
<​item​>three</​item​>
<​item​>four</​item​>
<​item​>five</​item​>
<​item​>six</​item​>
<​item​>seven</​item​>
<​item​>eight</​item​>
<​item​>nine</​item​>
<​item​>ten</​item​> </​array​>

</​resources​>

MainActivity.kt
:

package ​com.example.nikita.listview

import ​android.content.Intent ​import


android.support.v7.app.AppCompatActivity ​import ​android.os.Bundle
import ​kotlinx.android.synthetic.main.activity_main.* ​class ​MainActivity
: AppCompatActivity() {

override fun ​onCreate(savedInstanceState: Bundle?) {


Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

super​.onCreate(savedInstanceState)
setContentView(R.layout.​activity_main)​
btn.setOnClickListener ​{
val ​intent = Intent(​this​, List_view::​class​.​java​) startActivity(intent)

} ​} } ​
​ ​xml
activity_list_view.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"
xmlns:​app​=​"http://schemas.android.com/apk/res-auto"
android​:layout_width=​"match_parent"
android​:layout_height=​"match_parent" ​tools​:context=​".List_view"​>

<​ListView
android​:layout_width=​"368dp"
android​:layout_height=​"495dp"
tools​:layout_editor_absoluteY=​"8dp"
tools​:layout_editor_absoluteX=​"8dp"

tools​:context=​".list_view"
android​:entries=​"@array/insert_list"
tools​:ignore=​"MissingConstraints"​/>
</​android.support.constraint.ConstraintLayout​>

List_view.kt:

package ​com.example.nikita.listview

import ​android.support.v7.app.AppCompatActivity ​import


android.os.Bundle

class ​List_view : AppCompatActivity() {

override fun ​onCreate(savedInstanceState: Bundle?) {


super​.onCreate(savedInstanceState)

setContentView(R.layout.​activity_list_view)​ } } ​
Output of

ListView:
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.
Grid Layout: ​Android GridView shows items in two-dimensional scrolling
grid (rows & columns)

Grid.xm
l
<?​xml version=​"1.0" ​encoding=​"utf-8"​?> ​<​GridLayout
xmlns:​android​=​"http://schemas.android.com/apk/res/android"
android​:layout_width=​"match_parent"
android​:layout_height=​"match_parent"
android​:rowCount=​"3" ​android​:columnCount=​"3"
android​:padding=​"20dp" ​>
<​Button
android​:layout_width=​"110dp"
android​:layout_height=​"100dp"
android​:text=​"1"​/>

<​Button
android​:layout_width=​"110dp"
android​:layout_height=​"100dp"
android​:text=​"2"​/> <​Button
android​:layout_width=​"110dp"
android​:layout_height=​"100dp"
android​:text=​"3"​/> <​Button
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

android​:layout_width=​"110dp"
android​:layout_height=​"100dp"
android​:text=​"4"​/>

<​Button
android​:layout_width=​"110dp"
android​:layout_height=​"100dp"
android​:text=​"5"​/> <​Button
android​:layout_width=​"110dp"
android​:layout_height=​"100dp"
android​:text=​"6"​/> <​Button
android​:layout_width=​"110dp"
android​:layout_height=​"100dp"
android​:text=​"7"​/>

<​Button
android​:layout_width=​"110dp"
android​:layout_height=​"100dp"
android​:text=​"8"​/> <​Button
android​:layout_width=​"110dp"
android​:layout_height=​"100dp"
android​:text=​"9"​/>

</​GridLayout​> ​No
need to change in
MainActivity.kt

Output
:
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

PRACTICAL 7 Programs on
Intents, Events Listeners and Adapters
Note: Refer Table layout (practical 4)code
for Events Listeners and for Intent
GUI(Practical 5)code
PRACTICAL 8

Programs on Services, notification and


broadcast receivers

Note: Refer Broadcast receivers code


(Practical 1 i.e. flight mode on/off).
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

PRACTICAL 9

Database Programming with


SQLite
SQLite database in Android is used for a store a structure relational or simple offline data in the
android device. Where in other simply SQLite is a relational database management, In android
application development use of manage private database. SQLite database API
android.database.sqlite package​.

• ​Constructor ​: This takes the Context (e.g., an Activity), the name of the database, an
optional cursor factory (we’ll discuss this later), and an integer representing the version of
the database schema you are using (typically starting from 1 and increment later).
• ​onCreate(SQLiteDatabase db) ​: It’s called when there is no database and the app
needs one. It passes us a SQLiteDatabase object, pointing to a newly-created database,
that we can populate with tables and initial data.
• ​onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) ​: It’s called when
the schema version we need does not match the schema version of the database, It
passes us a ​SQLiteDatabase ​object and the old and new version numbers. Hence we
can figure out the best way to convert the database from the old schema to the new one.

Activity_main.xml ​<?x​ ml 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"
xmlns:​app​=​"http://schemas.android.com/apk/res-auto"
android​:layout_width=​"match_parent"
android​:layout_height=​"match_parent" ​tools​:context=​".MainActivity"​>

<​EditText
android​:id=​"@+id/editText_firstName"
android​:layout_width=​"match_parent"
android​:layout_height=​"wrap_content"
android​:layout_marginEnd=​"8dp"
android​:layout_marginStart=​"8dp"
android​:layout_marginTop=​"8dp" ​android​:ems=​"10"
android​:inputType=​"textPersonName"
android​:hint=​"f_name"
app​:layout_constraintEnd_toEndOf=​"parent"
app​:layout_constraintStart_toStartOf=​"parent"
app​:layout_constraintTop_toTopOf=​"parent" ​/>

<​EditText
android​:id=​"@+id/editText_lastName"
android​:layout_width=​"match_parent"
android​:layout_height=​"wrap_content"
android​:layout_marginEnd=​"8dp"
android​:layout_marginStart=​"8dp"
android​:layout_marginTop=​"8dp"
android​:ems=​"10"
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

android​:inputType=​"textPersonName" ​android​:hint=​"l_name"
app​:layout_constraintEnd_toEndOf=​"parent"
app​:layout_constraintStart_toStartOf=​"parent"
app​:layout_constraintTop_toBottomOf=​"@+id/editText_firstName" ​/>

<​Button
android​:id=​"@+id/button_save" ​android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content" ​android​:layout_marginStart=​"16dp"
android​:layout_marginLeft=​"16dp" ​android​:layout_marginTop=​"32dp"
android​:text=​"save" ​app​:layout_constraintStart_toStartOf=​"parent"
app​:layout_constraintTop_toBottomOf=​"@+id/editText_lastName" ​/>

<​Button
android​:id=​"@+id/button_show" ​android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content" ​android​:layout_marginEnd=​"16dp"
android​:layout_marginRight=​"16dp" ​android​:layout_marginTop=​"32dp"
android​:text=​"show" ​app​:layout_constraintEnd_toEndOf=​"parent"
app​:layout_constraintTop_toBottomOf=​"@+id/editText_lastName" ​/>

<​TextView
android​:id=​"@+id/textView_show" ​android​:layout_width=​"match_parent"
android​:layout_height=​"wrap_content" ​android​:layout_marginEnd=​"8dp"
android​:layout_marginStart=​"8dp" ​android​:layout_marginTop=​"136dp"
android​:text=​"empty" ​app​:layout_constraintEnd_toEndOf=​"parent"
app​:layout_constraintStart_toStartOf=​"parent"
app​:layout_constraintTop_toBottomOf=​"@+id/editText_lastName" ​/>

</​android.support.constraint.ConstraintLayout​>

Users.
kt

package ​com.example.student.prac9sqlite ​class


Users {
var ​id​: Int = ​0​; ​var ​firstName​: String = ​""​;
var ​lastName​: String = ​""​; }

DatabaseHandler.kt
package ​com.example.student.prac9sqlite

import ​android.content.ContentValues ​import


android.content.Context ​import
android.database.sqlite.SQLiteDatabase ​import
android.database.sqlite.SQLiteOpenHelper ​import
android.util.Log
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

class ​DatabaseHandler (context: Context) :


SQLiteOpenHelper(context, ​DB_NAME​, ​null​, ​DB_VERSIOM​) {

override fun ​onCreate(db: SQLiteDatabase?) {


val ​CREATE_TABLE = ​"CREATE TABLE ​$​TABLE_NAME ​" ​+
"(​$​ID ​Integer PRIMARY KEY, ​$​FIRST_NAME ​TEXT, ​$​LAST_NAME ​TEXT)"
db?.execSQL(CREATE_TABLE) } ​override fun ​onUpgrade(db: SQLiteDatabase?, oldVersion: Int,
newVersion: Int) {

// Called when the database needs to be upgraded ​} ​//Inserting

(Creating) data ​fun ​addUser(user: Users): Boolean {


//Create and/or open a database that will be used for reading and writing. v​ al ​db = ​this​.​writableDatabase
val ​values = ContentValues() values.put(​FIRST_NAME​, user.​firstName​) values.put(​LAST_NAME​,
user.​lastName​) ​val ​_success = db.insert(​TABLE_NAME​, ​null​, values) db.close() Log.v(​"InsertedID"​,
"​$​_success​"​) ​return ​(Integer.parseInt(​"​$​_success​"​) != -​1​) } ​//get all users fun
​ ​getAllUsers(): String {
var ​allUser: String = ​""​; ​val ​db = ​readableDatabase ​val
selectALLQuery = ​"SELECT * FROM ​$​TABLE_NAME​" ​val
cursor = db.rawQuery(selectALLQuery, ​null​) ​if ​(cursor != ​null​) {
if ​(cursor.moveToFirst()) {

do ​{ ​var ​id = cursor.getString(cursor.getColumnIndex(​ID​))


var ​firstName =
cursor.getString(cursor.getColumnIndex(​FIRST_NAME​))
var ​lastName = cursor.getString(cursor.getColumnIndex(​LAST_NAME​))

allUser = ​"​$​allUser​\n$​id ​$​firstName ​$​lastName​" ​} ​while ​(cursor.moveToNext()) } }


cursor.close() db.close() ​return ​allUser } ​companion object ​{ private
​ val ​DB_NAME ​=
"UsersDB" ​private val ​DB_VERSIOM ​= ​1​; ​private val ​TABLE_NAME ​= ​"users"
private val ​ID ​= ​"id" ​private val ​FIRST_NAME ​= ​"FirstName" ​private val

LAST_NAME ​= ​"LastName" ​} ​} ​MainActivity.kt

package ​com.example.student.prac9sqlite
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

import ​android.support.v7.app.AppCompatActivity ​import


android.os.Bundle ​import ​android.view.View ​import
android.widget.Toast ​import
kotlinx.android.synthetic.main.activity_main.*

class ​MainActivity : AppCompatActivity() { ​var


dbHandler​: DatabaseHandler? = ​null

override fun ​onCreate(savedInstanceState: Bundle?) {


super​.onCreate(savedInstanceState)
setContentView(R.layout.​activity_main)​ ​dbHandler
= DatabaseHandler(​this​)

//on Click Save button


button_save.setOnClickListener(View.OnClickListener ​{
// checking input text should not be null i​ f ​(validation()){
val ​user: Users = Users() ​var ​success: Boolean = ​false
user.​firstName ​= editText_firstName.​text​.toString() user.​lastName ​=
editText_lastName.​text.​ toString()
success = ​dbHandler​!!.addUser(user)

if ​(success){
val ​toast = Toast.makeText(​this​,​"Saved Successfully"​,
Toast.​LENGTH_LONG)​ .show()
}}

}​) ​//on Click show button


button_show.setOnClickListener(View.OnClickListener ​{
var ​user = ​dbHandler​!!.getAllUsers()
textView_show.setText(user) ​}​)

} ​fun ​validation(): Boolean{


var ​validate = ​false

if ​(!editText_firstName.​text​.toString().equals(​""​) &&
!editText_lastName.​text​.toString().equals(​""​)){ validate = ​true ​}​else​{
validate = ​false val ​toast = Toast.makeText(​this​,​"Fill all details"​,
Toast.​LENGTH_LONG)​ .show()

} ​return ​validate }​ }

Output:

Conclusion: hence we successfully Implement SQLite Database


Programming.
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

PRACTICAL 10

Programming threads, handles and asynchronized


programs

Android AsyncTask going to do background operation on background thread and update on


main

thread. In android we cant directly touch background thread to main thread in android
development.

asynctask help us to make communication between background thread to main


thread.

Synta
x:

abstract class AsyncTask<Params : Any!, Progress : Any!,


Result : Any!>

Methods of
AsyncTask

• ​onPreExecute() ​− Before doing background operation we should show something on


screen like progressbar or any animation to user. we can directly comminicate
background operation using on doInBackground() but for the best practice, we should
call all asyncTask methods .
• ​doInBackground(Params) ​ In this method we have to do background operation on

background thread. Operations in this method should not touch on any mainthread
activities or fragments.
• ​onProgressUpdate(Progress...) ​− While doing background operation, if you want to
update some information on UI, we can use this method.
• ​onPostExecute(Result) ​− In this method we can update ui of background operation
result.

Generic Types in Async


Task

• ​TypeOfVarArgParams ​− It contains information about what type of params


used for execution.
• ​ProgressValue​ It contains information about progress units. While doing

background operation we can update information on ui using onProgressUpdate().

• ​ResultValue ​−It contains information about result


type.
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

Activity_main.x
ml
<?​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"​>

<​ImageView
android​:id=​"@+id/image"
android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content"
android​:layout_centerHorizontal=​"true"
android​:layout_centerVertical=​"true" ​>
</​ImageView​>

<​Button
android​:id=​"@+id/button"
android​:layout_width=​"110dp"
android​:layout_height=​"wrap_content"
android​:layout_below=​"@+id/image"
android​:layout_centerHorizontal=​"true"
android​:layout_centerVertical=​"true"
android​:text=​"Download image"
android​:background=​"@color/colorAccent"​/>

</​RelativeLayout​>

MainActivity.
kt
package ​com.example.nikita.asyncimage

import ​android.support.v7.app.AppCompatActivity ​import


android.os.Bundle

import ​android.os.AsyncTask

import ​android.app.ProgressDialog ​import


android.graphics.Bitmap ​import
android.graphics.BitmapFactory ​import
android.view.View

import ​android.widget.Button
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

import ​android.widget.ImageView

class ​MainActivity : AppCompatActivity() {


// Set your Image URL into a string i​ nternal var ​URL ​=
"https://www.android.com/static/2016/img/share/andy-lg.png"
internal lateinit var ​image​: ImageView ​internal lateinit var ​button​:
Button ​internal lateinit var ​mProgressDialog​: ProgressDialog

override fun ​onCreate(savedInstanceState: Bundle?) {


super​.onCreate(savedInstanceState)
setContentView(R.layout.​activity_main​) ​// Locate the ImageView in
activity_main.xml i​ mage ​= findViewById<View>(R.id.​image​) ​as
ImageView

​ utton ​=
// Locate the Button in activity_main.xml b
findViewById<View>(R.id.​button​) ​as ​Button

// Capture button click


button​.setOnClickListener ​{

// Execute DownloadImage AsyncTask ​DownloadImage().execute(​URL​) ​} ​} //


DownloadImage AsyncTask private


​ inner class ​DownloadImage :
AsyncTask<String, Void, Bitmap>() {

override fun ​onPreExecute() {


​ ProgressDialog
super​.onPreExecute() ​// Create a progressdialog m
= ProgressDialog(​this​@MainActivity​)

​ ProgressDialog​.setTitle(​"Download Image "​) ​//


// Set progressdialog title m
Set progressdialog message ​mProgressDialog​.setMessage(​"Loading..."​)
mProgressDialog​.​isIndeterminate ​= ​false ​// Show progressdialog

mProgressDialog​.show() } ​override fun ​doInBackground(​vararg ​URL:

String): Bitmap? {

val ​imageURL = URL[​0​]

var ​bitmap: Bitmap? = ​null try ​{ ​//

Download Image from URL


Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

val ​input = java.net.URL(imageURL).openStream() ​// Decode Bitmap


bitmap = BitmapFactory.decodeStream(input) } ​catch ​(e: Exception)
{

e.printStackTrace() } ​return ​bitmap }​ override


​ fun

onPostExecute(result: Bitmap) {
// Set the bitmap into ImageView
image​.setImageBitmap(result) ​// Close progressdialog
mProgressDialog​.dismiss() } } }

AndroidManifest.xml

Add Following
Permission:
<​uses-permission ​android​:name=​"android.permission.INTERNET"​/>

Output
:
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.
Conclusio
n:

Hence we successfully download image using asyncTask


methods.
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming S.N.College,Bhayandar(E).
T.Y B.Sc. I.T.
PRACTICAL 11
Programming Media API and Telephone API
Media API:
MediaPlayer ​is a class that is used to control the playback of audio/video files and
streams.
The ​android.media.MediaPlayer ​class is used to control the audio or video files. It
accesses the built-in media player services such as playing audio, video, etc. To use
the ​MediaPlayer ​class, we have to call the create the instance of it by calling the
create() ​method of this class.
Methods of MediaPlayer class
There are several methods of MediaPlayer class available. Some of them are as
follows:
Method Description
public void setDataSource(String path) It sets the data source (file path or http url)
to use. public void prepare() It prepares the player for playback
synchronously. public void start() It starts or resumes the playback. public void stop() It
stops the playback. public void pause() It pauses the playback. public boolean
isPlaying() It checks if the media player is playing. public void seekTo(int millis) It seeks
to specified time in milliseconds. public void setLooping(boolean looping) It sets the
player for looping or non-
looping. public boolean isLooping() It checks if the player is looping or non-
looping. public void selectTrack(int index) It selects a track for the specified index. public
int getCurrentPosition() It returns the current playback position. public int getDuration() It
returns duration of the file. public void setVolume(float leftVolume,float rightVolume)
It sets the volume on this player.
Activity_main.xml
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

<?​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"
xmlns:​app​=​"http://schemas.android.com/apk/res-auto"
android​:layout_width=​"match_parent"
android​:layout_height=​"match_parent" ​tools​:context=​".MainActivity"​>

<​Button
android​:id=​"@+id/pauseBtn"
android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content"
android​:layout_marginBottom=​"8dp"
android​:layout_marginEnd=​"8dp"
android​:layout_marginStart=​"8dp"
android​:layout_marginTop=​"8dp" ​android​:enabled=​"false"
android​:text=​"Pause"
app​:layout_constraintBottom_toBottomOf=​"parent"
app​:layout_constraintEnd_toStartOf=​"@+id/playBtn"
app​:layout_constraintStart_toStartOf=​"parent"
app​:layout_constraintTop_toTopOf=​"parent" ​/>
<​Button
android​:id=​"@+id/playBtn" ​android​:layout_width=​"88dp"
android​:layout_height=​"wrap_content"
android​:layout_marginBottom=​"8dp"
android​:layout_marginEnd=​"8dp"
android​:layout_marginStart=​"8dp"
android​:layout_marginTop=​"8dp" ​android​:text=​"Play"
app​:layout_constraintBottom_toBottomOf=​"parent"
app​:layout_constraintEnd_toStartOf=​"@+id/stopBtn"
app​:layout_constraintStart_toEndOf=​"@+id/pauseBtn"
app​:layout_constraintTop_toTopOf=​"parent" ​/>

<​Button
android​:id=​"@+id/stopBtn"
android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content"
android​:layout_marginBottom=​"8dp"
android​:layout_marginEnd=​"24dp"
android​:layout_marginRight=​"24dp"
android​:layout_marginTop=​"8dp" ​android​:enabled=​"false"
android​:text=​"Stop"
app​:layout_constraintBottom_toBottomOf=​"parent"
app​:layout_constraintEnd_toEndOf=​"parent"
app​:layout_constraintTop_toTopOf=​"parent" ​/>

<​RelativeLayout
android​:layout_width=​"368dp"
android​:layout_height=​"wrap_content"
android​:layout_marginEnd=​"8dp"
android​:layout_marginStart=​"8dp"
android​:layout_marginTop=​"76dp"
app​:layout_constraintEnd_toEndOf=​"parent"
app​:layout_constraintHorizontal_bias=​"1.0"
app​:layout_constraintStart_toStartOf=​"parent"
app​:layout_constraintTop_toTopOf=​"parent"​>
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

<​TextView
android​:id=​"@+id/tv_pass"
android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content" ​/>

<​TextView
android​:id=​"@+id/tv_due"
android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content"
android​:layout_alignParentEnd=​"true"
android​:layout_alignParentRight=​"true" ​/>
<​SeekBar
android​:id=​"@+id/seek_bar"
android​:layout_width=​"match_parent"
android​:layout_height=​"wrap_content"
android​:layout_below=​"@id/tv_pass"
android​:saveEnabled=​"false" ​/> </​RelativeLayout​>

</​android.support.constraint.ConstraintLayout​>

MainActivity.k
t
package ​com.example.nikita.media

import ​android.media.MediaPlayer ​import


android.support.v7.app.AppCompatActivity ​import ​android.os.Bundle
import ​android.os.Handler ​import ​android.widget.SeekBar ​import
android.widget.Toast ​import
kotlinx.android.synthetic.main.activity_main.*

class ​MainActivity : AppCompatActivity() {


private lateinit var ​mediaPlayer​: MediaPlayer ​private
lateinit var ​runnable​:Runnable ​private var ​handler​:
Handler = Handler() ​private var ​pause​:Boolean = ​false

override fun ​onCreate(savedInstanceState: Bundle?) {


super​.onCreate(savedInstanceState)
setContentView(R.layout.​activity_main)​ ​// Start the
media player p ​ layBtn.setOnClickListener​{
if​(​pause​){
mediaPlayer​.seekTo(​mediaPlayer​.​currentPosition)​ ​mediaPlayer​.start() ​pause ​= ​false
Toast.makeText(​this​,​"media playing"​,Toast.​LENGTH_SHORT​).show() }​else​{ ​mediaPlayer

= MediaPlayer.create(​applicationContext,​ R.raw.​iphone​)
mediaPlayer​.start() Toast.makeText(​this​,​"media
playing"​,Toast.​LENGTH_SHORT)​ .show()

} initializeSeekBar()
playBtn.​isEnabled ​= ​false
pauseBtn.​isEnabled = ​ ​true
stopBtn.​isEnabled ​= ​true
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

mediaPlayer​.setOnCompletionListener ​{
playBtn.​isEnabled ​= ​true ​pauseBtn.​isEnabled ​= ​false ​stopBtn.​isEnabled =
​ ​false
Toast.makeText(​this​,​"end"​,Toast.​LENGTH_SHORT​).show() ​} } ​// Pause the

media player pauseBtn.setOnClickListener


​ ​{
if​(​mediaPlayer​.​isPlaying​){
mediaPlayer​.pause() ​pause ​= ​true ​playBtn.​isEnabled = ​ ​true ​pauseBtn.​isEnabled =
​ ​false
stopBtn.​isEnabled ​= ​true ​Toast.makeText(​this​,​"media
pause"​,Toast.​LENGTH_SHORT​).show() } ​} ​// Stop the media player
stopBtn.setOnClickListener​{
if​(​mediaPlayer​.​isPlaying ​|| ​pause​.equals(​true​)){
pause ​= ​false ​seek_bar.setProgress(​0​)
mediaPlayer​.stop() ​mediaPlayer​.reset()
mediaPlayer​.release()
handler​.removeCallbacks(​runnable​)

playBtn.​isEnabled ​= ​true ​pauseBtn.​isEnabled ​= ​false ​stopBtn.​isEnabled =


​ ​false ​tv_pass.​text ​= ​""
​ ​"" ​Toast.makeText(​this​,​"media stop"​,Toast.​LENGTH_SHORT​).show() } ​} ​// Seek bar
tv_due.​text =

change listener ​seek_bar.setOnSeekBarChangeListener(​object ​: SeekBar.OnSeekBarChangeListener {


override fun ​onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
if ​(b) {

mediaPlayer​.seekTo(i * ​1000​) } } ​override fun ​onStartTrackingTouch(seekBar:

SeekBar) { }​ ​override fun ​onStopTrackingTouch(seekBar: SeekBar) { }​ }) } ​//

Method to initialize seek bar and audio stats ​private fun ​initializeSeekBar() {
seek_bar.​max ​= ​mediaPlayer​.​seconds

runnable ​= ​Runnable ​{
seek_bar.​progress = ​ ​mediaPlayer​.​currentSeconds

tv_pass.​text ​= ​"​${​mediaPlayer​.​currentSeconds​} ​sec" ​val ​diff =


mediaPlayer​.​seconds ​- ​mediaPlayer​.​currentSeconds t​ v_due.​text ​= ​"​$​diff ​sec"
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

handler​.postDelayed(​runnable​,​1000​) ​}
handler​.postDelayed(​runnable​, ​1000​) }

} ​// Creating an extension property to get the media player time duration in seconds ​val
MediaPlayer.​seconds:​ Int
get​() {
return this​.​duration /​ ​1000 ​} ​// Creating an extension property to get media player current position in
seconds v​ al ​MediaPlayer.​currentSeconds​:Int
get​() {
return this​.​currentPosition​/​1000 ​}

output
:
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

Telephone
API:
The ​android.telephony.TelephonyManager ​class provides information about the
telephony services such as subscriber id, sim serial number, phone network type etc.
Moreover, you can determine the phone state etc.

activityMain.x
ml
<?​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/textView1"
android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content"
android​:layout_alignParentLeft=​"true"
android​:layout_alignParentTop=​"true"
android​:layout_marginLeft=​"38dp"
android​:layout_marginTop=​"30dp"
android​:text=​"Phone Details:" ​/>

</​RelativeLayout​>

MainActivity.k
t
package ​com.example.nikita.phone

import ​android.content.Context ​import


android.support.v7.app.AppCompatActivity ​import
android.os.Bundle ​import
android.telephony.TelephonyManager ​import
android.view.View ​import ​android.widget.TextView
class ​MainActivity : AppCompatActivity() {
internal lateinit var ​textView1​: TextView

override fun ​onCreate(savedInstanceState: Bundle?) {


super​.onCreate(savedInstanceState) setContentView(R.layout.​activity_main)​
textView1 ​= findViewById<View>(R.id.​textView1​) ​as ​TextView

//Get the instance of TelephonyManager ​val ​tm =


getSystemService(Context.​TELEPHONY_SERVICE)​ ​as ​TelephonyManager

val ​IMEINumber = tm.​deviceId ​val ​subscriberID = tm.​deviceId


val ​SIMSerialNumber = tm.​simSerialNumber v ​ al
networkCountryISO = tm.​networkCountryIso ​val
SIMCountryISO = tm.​simCountryIso v ​ al ​softwareVersion =
tm.​deviceSoftwareVersion
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

val ​voiceMailNumber = tm.​voiceMailNumber

//Get the phone type ​var


strphoneType = ​""

val ​phoneType = tm.​phoneType

when ​(phoneType) {
TelephonyManager.​PHONE_TYPE_CDMA -​ > strphoneType = ​"CDMA"
TelephonyManager.​PHONE_TYPE_GSM ​-> strphoneType = ​"GSM"
TelephonyManager.​PHONE_TYPE_NONE -​ > strphoneType = ​"NONE" ​} ​//getting

information if phone is in roaming val


​ ​isRoaming = tm.​isNetworkRoaming

var ​info = ​"Phone Details:​\n​" ​info += ​"​\n ​IMEI


Number:​$​IMEINumber​" ​info += ​"​\n ​SubscriberID:​$​subscriberID​"
info += ​"​\n ​Sim Serial Number:​$​SIMSerialNumber​" ​info += ​"​\n
Network Country ISO:​$​networkCountryISO​" ​info += ​"​\n ​SIM
Country ISO:​$​SIMCountryISO​" ​info += ​"​\n ​Software
Version:​$​softwareVersion​" ​info += ​"​\n ​Voice Mail
Number:​$​voiceMailNumber​" ​info += ​"​\n ​Phone Network
Type:​$​strphoneType​" ​info += ​"​\n ​In Roaming? :​$​isRoaming​"

textView1​.​text ​= info​//displaying the information in the textView

}}​
add permission in

androidmanifest.xml
<​uses-permission ​android:name​="​ android.permission.READ_PHONE_STATE"​/>

Output:
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

PRACTICAL 12

Programming Security And


Permission
Every Android app runs in a limited-access sandbox. If an app needs to use resources or
information outside of its own sandbox, the app has to request the appropriate ​permission. ​You
declare that your app needs a permission by listing the permission in the app manifest and then
requesting that the user approve each permission at runtime (on Android 6.0 and higher).

Add permissions to the


manifest

On all versions of Android, to declare that your app needs a permission, put a ​<uses-
​ manifest> e
permission>​element in your app manifest, as a child of the top-level < ​ lement.

Activity_main.x
ml

<?​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"
xmlns:​app​=​"http://schemas.android.com/apk/res-auto"
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"​/> <​Button
android​:text=​"Button" ​android​:layout_width=​"wrap_content"
android​:layout_height=​"wrap_content" ​tools​:layout_editor_absoluteY=​"182dp"
tools​:layout_editor_absoluteX=​"141dp" ​android​:id=​"@+id/button"​/>

</​android.support.constraint.ConstraintLayout​>
Android Manifest.xml ​<?x​ ml version=​"1.0" ​encoding=​"utf-8"​?> <
​ ​manifest
xmlns:​android​=​"http://schemas.android.com/apk/res/android"
package=​"com.example.nikita.pract12permission"​> <​uses-permission
android​:name=​"android.permission.INTERNET" ​/> <​uses-permission
android​:name=​"android.permission.CAMERA"​/> <​uses-permission
android​:name=​"android.permission.READ_CONTACTS"​/> <​uses-permission
android​:name=​"android.permission.READ_EXTERNAL_STORAGE"​/>
<​uses-permission ​android​:name=​"android.permission.SEND_SMS"​/>
<​uses-permission ​android​:name=​"android.permission.READ_CALENDAR"​/>
<​application
android​:allowBackup=​"true"
android​:icon=​"@mipmap/ic_launcher"
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

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"​/>

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


</​activity​> </​application​>

</​manifest​>
ManagePermissions
.kt

package ​com.example.nikita.pract12permission

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

class ​ManagePermissions (​val ​activity​: Activity,​val ​list​: List<String>,​val ​code​:Int) {

// Check permissions at runtime f​ un


checkPermissions() {
if ​(isPermissionsGranted() != PackageManager.​PERMISSION_GRANTED)​ {
showAlert() } ​else ​{
activity​.​toast(​ ​"Permissions already granted."​) } } ​// Check permissions

status ​private fun ​isPermissionsGranted(): Int {


// PERMISSION_GRANTED : Constant Value: 0 //
PERMISSION_DENIED : Constant Value: -1 v ​ ar
counter = ​0​; ​for ​(permission ​in ​list​) {

counter += ContextCompat.checkSelfPermission(​activity​, permission) } ​return ​counter }​ ​// Find the

first denied permission ​private fun ​deniedPermission(): String {


for ​(permission ​in ​list​) {
if ​(ContextCompat.checkSelfPermission(​activity​, permission)

== PackageManager.​PERMISSION_DENIED​) ​return ​permission } ​return ​"" }​ ​//

Show alert dialog to request permissions ​private fun ​showAlert() {


Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

val ​builder = AlertDialog.Builder(​activity​) builder.setTitle(​"Need permission(s)"​)


builder.setMessage(​"Some permissions are required to do the task."​) builder.setPositiveButton(​"OK"​,
{ ​dialog, which ​-> ​requestPermissions() ​}​) builder.setNeutralButton(​"Cancel"​, ​null​) ​val ​dialog =
builder.create() dialog.show() } ​// Request the permissions at run time private
​ fun ​requestPermissions() {
val ​permission = deniedPermission() ​if ​(ActivityCompat.shouldShowRequestPermissionRationale(​activity​,
permission)) {
// Show an explanation asynchronously ​activity​.​toast​(​"Should
show an explanation."​) } ​else ​{

ActivityCompat.requestPermissions(​activity​, ​list​.​toTypedArray(​ ), ​code​) } } ​// Process permissions result


fun ​processPermissionsResult(requestCode: Int, permissions: Array<String>,
grantResults: IntArray): Boolean { ​var ​result = ​0 ​if
(grantResults.​isNotEmpty(​ )) { ​for ​(item ​in ​grantResults) {

result += item } } ​if ​(result == PackageManager.​PERMISSION_GRANTED​) ​return

true return
​ false ​} } ​MainActivity.kt

package ​com.example.nikita.pract12permission

import ​android.content.Context ​import ​android.os.Build ​import


android.support.v7.app.AppCompatActivity ​import ​android.os.Bundle
import ​android.widget.Toast ​import
kotlinx.android.synthetic.main.activity_main.* ​import
java.util.jar.Manifest

class ​MainActivity : AppCompatActivity() {


private val ​PermissionsRequestCode ​= ​123 ​private lateinit var
managePermissions​: ManagePermissions

override fun ​onCreate(savedInstanceState: Bundle?) {


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

// Initialize a list of required permissions to request runtime ​val ​list= ​listOf<


​ String>​(
android.Manifest.permission.​CAMERA​,
android.Manifest.permission.​READ_CONTACTS,​
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

android.Manifest.permission.​READ_EXTERNAL_STORAGE​,
android.Manifest.permission.​SEND_SMS,​
android.Manifest.permission.​READ_CALENDAR

) ​// Initialize a new instance of ManagePermissions class


managePermissions ​= ManagePermissions(​this​,list,​PermissionsRequestCode​)

// Button to check permissions states


button.setOnClickListener​{
if ​(Build.VERSION.​SDK_INT >​ = Build.VERSION_CODES.​M)​

managePermissions​.checkPermissions() ​} ​} ​// Receive the permissions request result


override fun ​onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
grantResults: IntArray) { ​when
(requestCode) {
PermissionsRequestCode ​->{
val ​isPermissionsGranted = ​managePermissions
.processPermissionsResult(requestCode,permissions,grantResults)

if​(isPermissionsGranted){
// Do the task now t​ oast(​ ​"Permissions granted."​) }​else​{

toast​(​"Permissions denied."​) }​ ​return }​ } } } ​// Extension function

to show toast message fun


​ ​Context.toast(message: String) {

Toast.makeText(​this​, message, Toast.​LENGTH_SHORT​).show() } ​Output:


Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

PRACTICAL 13
Programming Network Communications and Services
(JSON)
Retrofit android ​is a type-safe HTTP client for Android and Java. Retrofit is a REST Client for Java,
Android, and Kotlin by Square inc under Apache 2.0 license. With this library or module used the in-app
app for server smooth connection, like sing in sing up or downloading-uploading data.

Why Retrofit library? Because it will save your development time and also you can keep your code in
developer friendly. Retrofit has given almost all the API’s to make a server call and to receive a
response. Internally they also use GSON to do the parsing.

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


​ ​manifest
xmlns:​android​=​"http://schemas.android.com/apk/res/android"
package=​"com.example.student.retrofit13"​> ​<​uses-permission
android​:name=​"android.permission.INTERNET" ​/> ​<​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" ​/>

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


</​activity​> </​application​>

</​manifest​>

build.gradle(Module:ap
p)

dependencies {
implementation fileTree(​dir​: ​'libs'​, ​include​: [​'*.jar'​]) implementation
'com.android.support:appcompat-v7:28.+' ​implementation
'com.android.support.constraint:constraint- layout:1.0.2'
implementation 'com.squareup.retrofit2:retrofit:2.3.0' implementation
'com.squareup.retrofit2:converter-gson:2.2.0'

testImplementation ​'junit:junit:4.12' ​androidTestImplementation


'com.android.support.test:runner:0.5' ​androidTestImplementation
'com.android.support.test.espresso:espresso-core:2.2.2' ​implementation
"org.jetbrains.kotlin:kotlin-stdlib- jdk7:​$kotlin_version​" ​}
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.
activity_main.xml ​<?x​ ml 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"​>

<​ListView
android​:id=​"@+id/listViewHeroes"
android​:layout_width=​"match_parent"
android​:layout_height=​"match_parent"
android​:background=​"@color/colorAccent" ​/>

</​RelativeLayout​>

Hero.kt ​package
com.example.student.retrofit13

class ​Hero (
val ​name​: String, ​val ​realname​:
String, ​val ​team​: String, ​val
firstappearance​: String, ​val
createdby​: String, ​val ​publisher​:
String, ​val ​imageurl​: String, ​val ​bio​:
String)

Api.kt(Interface file)

package ​com.example.student.retrofit13

import ​retrofit2.Call ​import


retrofit2.http.​GET

interface ​Api {

@get:GET​(​"marvel"​) ​val ​hero​:


Call<List<Hero>>

companion object ​{

val ​BASE_URL ​= ​"https://simplifiedcoding.net/demos/" ​} }

MainActivity.kt package
​ ​com.example.student.retrofit13
import ​android.support.v7.app.AppCompatActivity ​import
android.os.Bundle ​import ​android.view.View ​import
android.widget.ListView
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

import ​android.widget.ArrayAdapter

import ​android.widget.Toast

import ​retrofit2.Call ​import ​retrofit2.Callback ​import


retrofit2.Response ​import ​retrofit2.Retrofit ​import
retrofit2.converter.gson.GsonConverterFactory

class ​MainActivity : AppCompatActivity() {


internal lateinit var ​listView​: ListView ​override fun
onCreate(savedInstanceState: Bundle?) {

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

listView ​= findViewById<View>(R.id.​listViewHeroes)​ ​as ​ListView

//calling the method to display the heroes ​getHeroes() }

private fun ​getHeroes() {


val ​retrofit = Retrofit.Builder()
.baseUrl(Api.​BASE_URL​) .addConverterFactory(GsonConverterFactory.create()) ​//Here we are using the
GsonConverterFactory to directly convert json data to object
.build()

val ​api = retrofit.create<Api>(Api::​class​.​java)​

val ​call = api.​hero

call.enqueue(​object ​: Callback<List<Hero>> {
override fun ​onResponse(call: Call<List<Hero>>, response:
Response<List<Hero>>) {
val ​heroList = response.body()

​ al ​heroes =
//Creating an String array for the ListView v
arrayOfNulls<​ String>(heroList!!.​size​)

//looping through all the heroes and inserting the names inside the string array
for ​(i ​in ​heroList.​indices​) {


heroes[i] = heroList[i].​name ​} ​//displaying the string array into listview ​listView​.​adapter =
ArrayAdapter<String>(​applicationContext,​ android.R.layout.​simple_list_item_1,​ heroes)

} ​override fun ​onFailure(call: Call<List<Hero>>, t: Throwable) {


Toast.makeText(​applicationContext​, t.​message​,
Toast.​LENGTH_SHORT)​ .show()
} }) }

}
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

Output
:
Notes By: Prof. Nikita M. Chaudhari Advanced Mobile Programming
S.N.College,Bhayandar(E). ​T.Y B.Sc. I.T.

S-ar putea să vă placă și