cs 6611 mad lab manual

142

Click here to load reader

Upload: balasubramani-manickam

Post on 14-Apr-2017

1.287 views

Category:

Engineering


19 download

TRANSCRIPT

Page 1: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

NATTRAMPALLI – 635 854

(Approved by AICTE New Delhi and Affiliated to Anna University)

NAME :

REGISTER NUMBER

SUBJECT CODE / NAME : ………………………………………..

YEAR/SEM : …………………………………….......

MAY 2016

Department of Computer Science Engineering

1

Page 2: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

NATTRAMPALLI - 635 854. VELLORE DISTRICT

Department of Computer Science Engineering

BONAFIDE CERTIFICATE

Certified with this is a bonafide record of the practical work done by

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 6 h Semester Computer

Science Engineering in Mobile Application Development LAB-CS6611 during the period JAN

2016 to APR 2016

Staff In-Charge Head of the Department

2

Page 3: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

University Register Number:

Submitted for the Practical examination held on……….....…………….at Bharathidasan

Engineering College, Nattrampalli.

Internal Examiner External Examiner

TABLE OF CONTENTS

Ex. No

Date Name of the Experiment Page No.

Staff Signature

3

Page 4: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

CS6611 MOBILE APPLICATION DEVELOPMENT LABORATORY

OBJECTIVES:

The student should be made to:

Know the components and structure of mobile application development frameworks for

Android and windows OS based mobiles.

Understand how to work with various mobile application development frameworks.

Learn the basic and important design concepts and issues of development of mobile

applications.

Understand the capabilities and limitations of mobile devices.

LIST OF EXPERIMENTS:

1. Develop an application that uses GUI components, Font and Colours

2. Develop an application that uses Layout Managers and event listeners.

3. Develop a native calculator application.

4. Write an application that draws basic graphical primitives on the screen.

5. Develop an application that makes use of database.

6. Develop an application that makes use of RSS Feed.

7. Implement an application that implements Multi-threading

8. Develop a native application that uses GPS location information.

9. Implement an application that writes data to the SD card.

10. Implement an application that creates an alert upon receiving a message.

11. Write a mobile application that creates alarm clock

Mission

4

Page 5: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Our mission is to be the leading mobile application development organization. We aim to

develop mobile apps that can change the way we do our day to day work, with a click of a

button.

Vision Our vision is to be one of the most innovative organizations in around the world. We

believe technology can makes life better for everyone, if used for a good cause. We want to

develop mobile application development training and methodologies, which can make cutting

edge technologies so that the world is a better place.

Ex.No. CREATION OF SIMPLE UI DESIGN ANDROID APPLICATION

Aim:

To create an application that uses GUI components, Font and Colors using Android Studio.

Algorithm:

1. Using the Android Studio create a project of the type mobile application.

2. Create a simple application in the project.

3. Click on the Design tab and design the prototype of the application.

4. Click on source tab and modify the application logic of the application.

5. Save the project.

6. Right click on the project and click on deploy and undeploy.

7. Then test the android application.

Steps:

1. Select File\New Project from the menu to create a new project, Studio will present you with

your first project creation screen:

5

Page 6: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

2. Enter Application name as shown above. Feel free to put your own name in the Company

Domain text field. As you type, you’ll notice the Package Name will automatically change

to create a reverse domain style name based on your Application name and Company

Domain. Click next at the bottom of the window to progress to the next part of the project

setup.

6

Page 7: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

3. Click Next option. The next screen is where you select device types and operating systems

to target. Want an App to focus on just Phone and Tablet? For now though you just want an

App that works on an Android Phone. This option is selected as the default, alongside the

default Minimum SDK.The Minimum SDK drop down menu sets the minimum version of

Android needed to run your app. selecting this value for your own projects is a matter of

balancing the SDK capabilities you want and the devices you want to support.

7

Page 8: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

4. Choose “Blank Activity”

Getting back to the new project window, click Next  in the bottom right to pick more

options for your project. This screen lets you choose a default Activity for your app. Think of an

Activity as a window within your App that displays content the user can interact with – not

unlike a View Controller in iOS. An activity can take up the entire screen or it could be a simple

pop-up. Available activities on this template range from a blank activity with an Action Bar right

up to an Activity with a MapView embedded. You will be making a lot of activities, so it’s good

to get accustomed with them. Select the Blank Activity option and click Next.

8

Page 9: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

5. If you have made it this far then well done, you are at the final screen before you dig into

some actual coding. To speed this part up a little bit you will use the pre-populated default

values, but what is actually done with these values?

Activity Name. This will give your Activity a name to refer to in code. Once the project

setup is complete Android Studio will create a .java class and use the contents of this text

field to give the class a name. This is the name you will use to refer to your Activity

inside your code.

Note: What it’s actually doing is making a subclass of Activity. Those familiar with

object-oriented programming will know what this is, but for newcomers, this basically

means that yourMainActivity is going to be a customized version of Activity that acts just

like the default one, handling things like its lifecycle and the user interface display.

Layout Name. You’re going to define your Activity in Java, but the layout of everything

it will show to the user is defined in a special sort of Android XML. You will learn how

to read and edit those files shortly.

9

Page 10: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Click Finish. Android Studio takes this as its cue to go do a bunch of behind-the-scenes

operations and create your project. As it shoots out some descriptions of what it’s doing from

time to time, you may notice it say something like the following:

6. You see your project name, which is familiar. But then there is this Gradle word, and then a

mention of Maven in the URL. The benefit of having a modern IDE like Android Studio is

that it handles a lot for you. But as you’re just beginning to learn how to use the software,

it’s good to know, in general, what it’s doing for you.

Cradle is a new build tool that is easy to use, but it also contains a lot of advanced options if

you investigate it further. It takes your Java code and XML layouts, and then uses the latest

Android build tools to create the app package file, known as an APK file. You can

customize your configurations to have development or production versions of the app that

behave differently, or add dependencies for third-party libraries.

UI Elements:

Layouts: Linear Layout o Horizontal vs Vertical, Relative Layout, Table Layout, Grid Layout,

Frame Layout

10

Page 11: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Widgets: Text View, Button, Radio Button, Toggle Button, Image View, Image Button,

Checkbox, Progress Bar, Seek Bar, Rating Bar

Web View

• Spinner

Text Fields

• Edit Text o Plain text, Name, Number, Email etc.

Containers

• Scroll View , Vertical vs. Horizontal ,List View ,Grid View ,Search View

Tab Host

• Background colour or draw able, id, padding, margin, TextColor colour value (Hex, Reba

etc.) draw able colour resource ,text Style ,typeface

7. Changing attributes (text color, background, typeface etc.) in java

TextView <<variable>> = (TextView) findViewById(R.id.<<id>>);

<<variable>>.setTextColor(getResources().getColor(R.color.<<name>>));

The color resource is defined in a “color.xml” resource file inside “values” resource directory.

E.g.:

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

<resources>

<color name="yellow">#FFFF00</color>

</resources>

<<variable>>.setBackgroundColor(getResources().getColor(R.color.<<name>>));

11

Page 12: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Changing Type Face

1. First we need to import a font face to assets directory.

2. Create an assets directory.

3. In Android Studio, select File>app>New>Java Class>Folder>Assets Folder.

4. Download a font from internet and put it under assets/fonts folder.

5. Create a new directory “font” – not necessary –

6. Modify src/MainActivity.java file to add necessary code.

7. Modify the res/layout/activity main to add respective XML components

<?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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.library.bec.ui.MainActivity" tools:showIn="@layout/activity_main">

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:id="@+id/txt" android:textColor="#f90101" android:textSize="34sp" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:src="@drawable/logo" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" />

</RelativeLayout>

12

Page 13: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Main Activity.java:

package com.library.bec.ui;

import android.graphics.Typeface;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.View;import android.view.Menu;import android.view.MenuItem;import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tF = (TextView) findViewById(R.id.txt); //find the textView with id theFont//Now we need to create a new TypeFace from the .ttf file we imported Typeface typeface = Typeface.createFromAsset(getAssets(),"font/Android Insomnia Regular.ttf"); //Set the typeface of the textView tF.setTypeface(typeface);//the type-face will change at tF.setTypeface(typeface);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); }

@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; }

13

Page 14: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId();

//noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; }

return super.onOptionsItemSelected(item); }}

14

Page 15: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

15

Page 16: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

8. First: On the Emulator

Before we can run the application, we need to setup an Android Virtual Device (AVD),

or emulator, to run it on:

Android Studio comes free with the ability to set up a software-based Android device on

your computer and run apps on it, browse websites, debug and everything you would

expect. This capability is known as the Android Emulator .

Select the menu Tools ->Android "Android SDK and AVD Manager".

Let’s run through creating a new AVD. Click Create Virtual Device… in the bottom left

to begin configuring a new virtual device.

The first decision you need to make is what type of device you want to emulate.

The Category list to the left shows all the types of device you can emulate. Clicking each

16

Page 17: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

option shows you what type of devices are available to you in that category. For now you

just want to emulate a phone sized device but if you wanted to emulate an Android Wear

watch or an Android TV then you have options to do so here.Select Nexus S in the list of

devices available to you from the phone category and click next.

Your next decision is to decide what version of Android you want your virtual device to

run. You will already have one or two available to you thanks to the setup wizard, so let’s

use one of them. Select Lollipop and make sure the one selected has the value x86 in

the ABI column. We want the emulator to be running as fast as possible on our x86

computers. :)

Click Next once this is done to move to the final screen. The last screen is simply a

confirmation of your previous choices with the option to configure some other properties

of your device such as device name, start-up orientation, and RAM size. For now leave

these set as their defaults and click Finish.

Congratulations! With relative ease you’ve just created a fresh virtual device ready for

use to test out your new app.

Now, close the AVD Manager to go back to Android Studio’s main view. Now that

you’ve configured everything, there’s but one step left…

17

Page 18: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

18

Page 19: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

8. We're now ready to run our application.

Select the menu Run -> Run.

• Note: The emulator may take a long time to start up. 19

Page 20: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

• Note: Another way to run your application is to right-click on the project in the

Package Explorer, then select Run As -> Android Application.

20

Page 21: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

21

Page 22: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Output :

22

Page 23: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Result: Thus the UI android application that uses GUI components, Font and Colours was

successfully executed.

Ex.No.1. Layout and Event Listeners

Aim:

To create an application that uses Layout Managers and event listeners using Android Studio.

Algorithm:

1. Using the Android Studio create a project of the type mobile application.

2. Create a simple application in the project.

3. Click on the Design tab and design the prototype of the application.

4. Click on source tab and modify the application logic of the application.

5. Save the project.

6. Right click on the project and click on deploy and undeploy.

7. Then test the android application.

Layouts

1. Relative Layout

As in name this layout positions elements relative to the adjacent elements. It uses the

following attributes for each element to position them: layout:alignEnd ,layout:alignStart

,layout:toEndOf ,layout:toStartOf ,layout:alignParent , layout:centreInParent

1. We will create a Text View (Large) inside the parent Relative layout by editing the xml code:

<RelativeLayoutxmlns: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:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"23

Page 24: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

app:layout_behavior="@string/appbar_scrolling_view_behavior"

tools:context="com.kani.student.text1.MainActivity"

tools:showIn="@layout/activity_main">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="SampleProgram!"

android:id="@+id/textSample" />

</RelativeLayout>

Linear Layout

1. Linear layout are two types Horizontal and Vertical.

2. Horizontal/Vertical is set using the orientation attribute.

3. In such layout the elements are arranged in order top-to-bottom or leftto-

right.

4. Let’s add a Linear Layout now. (Now you can use the drag and drop

layout editor). Change orientation to Vertical.

5. Now add an Image View to the Linear Layout. 24

Page 25: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

6. Import an image to the draw able directory. (Just as we have imported font

face in previous chapter).

7. Set the src attribute to the draw able we imported. (Click the browse

button and select the file from Draw able directory).

25

Page 26: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Table Layout:

As we all know table layout uses rows and columns to position elements.

Add table layout inside the linear layout. Table layout uses Table Row layout to create rows.

Add a Table Row to the Table Layout. Add two Buttons to the Table Row.

Change the Id’s of the two Buttons to btnClick and btnLongClick respectively.

we will use these buttons to implement event listeners

Change text to Click Me! and Long Click Me! also.

Select one of the buttons from the component tree. Pay attention to Properties window.

You can see layout: span and layout: column attributes. The table layout uses these

attributes to position elements.

If the values are unset then uses default values (span=1 and column increments according to

order of placement).

Grid Layout

This is a very useful layout. This layout has order as well as freedom.

This layout uses orderly grids with rows and columns, span and spaces.

Add a Grid Layout below the table layout.

Now drag and drop a Button to the Grid Layout.

You’ll see a green grid with many blocks.

Example:

26

Page 27: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

2. Select this button and you can see that it uses attributes layout: column, layout: row,

layout: row Span, layout: column Span. These are the attributes to position to items in Grid

Layout.

Change the row Span to.

Resize the button

Add one more button and a text field.

Edit the xml file to position them correctly

XML Coding:

<GridLayout

android:layout_width="match_parent"

android:layout_height="fill_parent"

android:id="@+id/lytGrid">

<Button

android:layout_width="202dp"

android:layout_height="156dp"

android:text="Click or Long CLick \n Me"

android:id="@+id/btnAll"

android:layout_column="3"

android:layout_row="0"

android:layout_columnSpan="1"

android:layout_rowSpan="2" />

<Button

android:layout_width="143dp"

android:layout_height="match_parent"

android:text="Show \nMy \nName"

android:id="@+id/btnShowName"

android:layout_row="1"

27

Page 28: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

android:layout_column="2"

android:layout_rowSpan="3" />

<EditText

android:layout_width="match_parent"

android:layout_height="62dp"

android:id="@+id/txtName"

android:layout_row="3"

android:layout_column="3"

android:hint="Enter your Name"

android:layout_columnSpan="1"

android:layout_rowSpan="1" />

</GridLayout>

Final XML:

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools=http://schemas.android.com/tools

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:text="Sampleprogram"

28

Page 29: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

android:id="@+id/txtSample"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<LinearLayout

android:orientation="vertical"

android:layout_width="match_parent"

android:layout_height="fill_parent"

android:layout_below="@+id/txtSample"

android:layout_centerHorizontal="true">

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:layout_gravity="center_horizontal"

android:src="@drawable/poo" />

<TableLayout

android:layout_width="match_parent"

android:layout_height="wrap_content">

<TableRow

android:layout_width="match_parent"

android:layout_height="match_parent"

android:id="@+id/tableRow"

android:orientation="horizontal">

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="ClickMe"

android:id="@+id/btnClick"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="LongClickMe"

29

Page 30: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

android:id="@+id/btnLongClick"/>

</TableRow>

</TableLayout>

<GridLayout

android:layout_width="match_parent"

android:layout_height="fill_parent"

android:id="@+id/lytGrid">

<Button

android:layout_width="202dp"

android:layout_height="156dp"

android:text="ClickorLongCLick\nMe"

android:id="@+id/btnAll"

android:layout_column="3"

android:layout_row="0"

android:layout_columnSpan="1"

android:layout_rowSpan="2" />

<Button

android:layout_width="143dp"

android:layout_height="match_parent"

android:text="Show\nMy\nName"

android:id="@+id/btnShowName"

android:layout_row="1"

android:layout_column="2"

android:layout_rowSpan="3" />

<EditText

android:layout_width="match_parent"

android:layout_height="62dp"

android:id="@+id/txtName"

android:layout_row="3"

android:layout_column="3"

android:hint="EnteryourName"

android:layout_columnSpan="1"

30

Page 31: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

android:layout_rowSpan="1" />

</GridLayout></LinearLayout></RelativeLayout>

Setting up Java Code:

package com.kani.student.eventlisteners;

import android.net.Uri;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;

import com.google.android.gms.appindexing.Action;import com.google.android.gms.appindexing.AppIndex;import com.google.android.gms.common.api.GoogleApiClient;

public class MainActivity extends AppCompatActivity { Button clickBtn, longClickBtn, allBtn, btnShow; TextView sample; EditText nameTxt; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); clickBtn = (Button) findViewById(R.id.btnClick); longClickBtn = (Button) findViewById(R.id.btnLongClick); allBtn = (Button) findViewById(R.id.btnAll); btnShow = (Button) findViewById(R.id.btnShowName); sample = (TextView) findViewById(R.id.txtSample); nameTxt = (EditText) findViewById(R.id.txtName); /*Simple Click onClick Listener*/

31

Page 32: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

clickBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "Hai III CSE!", Toast.LENGTH_SHORT).show(); } }); /*Implement Long Click Listener*/ longClickBtn.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getApplicationContext(), "Hai BEC !", Toast.LENGTH_SHORT).show(); return false; } });

allBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "You Just Clicked Me!", Toast.LENGTH_SHORT).show(); } }); allBtn.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getApplicationContext(), "You clicked me for so long!", Toast.LENGTH_SHORT).show(); return false; } }); btnShow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {

//sample.setText(nameTxt.getText().toString()); Toast.makeText(getApplicationContext(), "K.POOVAZHAKI!", Toast.LENGTH_SHORT).show(); } });

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override32

Page 33: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); }

@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; }

@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId();

//noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; }

return super.onOptionsItemSelected(item); }

@Override public void onStart() { super.onStart();

// ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kani.student.eventlisteners/http/host/path")33

Page 34: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

); AppIndex.AppIndexApi.start(client, viewAction); }

@Override public void onStop() { super.onStop();

// ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.kani.student.eventlisteners/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }}Output:

34

Page 35: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Result: Thus the Layout and Event listener android application was successfully executed.

Ex.No.2. Layout and Event Listeners

Aim:

To create an application that uses Layout Managers and event listeners using Android Studio.

Algorithm:

1. Using the Android Studio create a project of the type mobile application.

2. Create a simple application in the project.

3. Click on the Design tab and design the prototype of the application.

4. Click on source tab and modify the application logic of the application.

5. Save the project.

6. Right click on the project and click on deploy and undeploy.

7. Then test the android application.

Setting up 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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.library.bec.ex_1_eventlistener.MainActivity" tools:showIn="@layout/activity_main">

<TextView android:text="hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" />

<LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"

35

Page 36: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:id="@+id/background" android:weightSum="1">

<Button android:layout_width="266dp" android:layout_height="wrap_content" android:text="Green" android:id="@+id/btnGreen" android:layout_weight="0.07" />

<Button android:layout_width="269dp" android:layout_height="wrap_content" android:text="Blue" android:id="@+id/btnBlue" android:layout_weight="0.07" /> </LinearLayout></RelativeLayout>Setting up Java:

package com.library.bec.ex_1_eventlistener;

import android.graphics.Color;import android.net.Uri;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.LinearLayout;

import com.google.android.gms.appindexing.Action;import com.google.android.gms.appindexing.AppIndex;import com.google.android.gms.common.api.GoogleApiClient;

public class MainActivity extends AppCompatActivity { LinearLayout background; Button btnGreen, btnBlue; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client;

@Override

36

Page 37: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); background = (LinearLayout) findViewById(R.id.background); btnGreen = (Button) findViewById(R.id.btnGreen); btnBlue = (Button) findViewById(R.id.btnBlue);

btnGreen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { background.setBackgroundColor(Color.parseColor("#00ff00")); } }); btnBlue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { background.setBackgroundColor(Color.parseColor("#006699")); } }); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); }

@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; }

@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId();

//noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; }

return super.onOptionsItemSelected(item); }

@Override public void onStart() {37

Page 38: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

super.onStart();

// ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.library.bec.ex_1_eventlistener/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); }

@Override public void onStop() { super.onStop();

// ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.library.bec.ex_1_eventlistener/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }}

Output:

38

Page 39: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Result: Thus the android Event Listener application was successfully executed.

ExNo. CALCULATOR APPLICATION

Aim: To create a native calculator application using Android Studio.

Algorithm:

Using the Android Studio create a project of the type mobile application.

Create a simple application in the project.

Click on the Design tab and design the prototype of the application.

Click on source tab and modify the application logic of the application.

Save the project.

Right click on the project and click on deploy and undeploy.

Then test the android application.

Steps:

• In this Tutorial we are going to start a new project Calculator.

• First of all, to start with we are going to create a simple calculator to do simple

arithmetic operations (i.e., one operator and two operands).

• Start Android Studio .Create a new Project.

39

Page 40: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

• Target Android devices >> Check Phone and Tablet

• Select a Blank Activity >>

• Click Finish keeping the default settings for Activity (Name: Main Activity…..).

Setting up Layout

Skip to XML Code

<?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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.javasamples.calci1.MainActivity" tools:showIn="@layout/activity_main"> <EditText android:id="@+id/result_id" android:layout_width="fill_parent" android:layout_height="120dp" /> <Button android:id="@+id/Btn7_id" android:layout_width="70dp" android:layout_height="60dp"40

Page 41: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

android:layout_below="@id/result_id" android:text="7" android:onClick="btn7Clicked"/> <Button android:id="@+id/Btn8_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/result_id" android:layout_toRightOf="@id/Btn7_id" android:text="8" android:onClick="btn8Clicked"/> <Button android:id="@+id/Btn9_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/result_id" android:layout_toRightOf="@id/Btn8_id" android:text="9" android:onClick="btn9Clicked"/> <Button android:id="@+id/Btnclear_id" android:layout_width="90dp" android:layout_height="60dp" android:layout_below="@id/result_id" android:layout_toRightOf="@id/Btn9_id" android:text="clear" android:onClick="btnclearClicked"/> <Button android:id="@+id/Btn4_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/Btn7_id" android:text="4" android:onClick="btn4Clicked"/> <Button android:id="@+id/Btn5_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/Btn8_id" android:layout_toRightOf="@id/Btn4_id" android:text="5" android:onClick="btn5Clicked"/> <Button android:id="@+id/Btn6_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/Btn9_id" android:layout_toRightOf="@id/Btn5_id"41

Page 42: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

android:text="6" android:onClick="btn6Clicked"/> <Button android:id="@+id/Btnplus_id" android:layout_width="90dp" android:layout_height="60dp" android:layout_below="@id/Btnclear_id" android:layout_toRightOf="@id/Btn6_id" android:text="+" android:onClick="btnplusClicked"/> <Button android:id="@+id/Btn1_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/Btn4_id" android:text="1" android:onClick="btn1Clicked"/> <Button android:id="@+id/Btn2_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/Btn5_id" android:layout_toRightOf="@id/Btn1_id" android:text="2" android:onClick="btn2Clicked"/> <Button android:id="@+id/Btn3_id" android:layout_width="70dp" android:layout_height="60dp" android:layout_below="@id/Btn6_id" android:layout_toRightOf="@id/Btn2_id" android:text="3" android:onClick="btn3Clicked"/> <Button android:id="@+id/Btnminus_id" android:layout_width="90dp" android:layout_height="60dp" android:layout_below="@id/Btnplus_id" android:layout_toRightOf="@id/Btn3_id" android:text="-" android:onClick="btnminusClicked"/> <Button android:id="@+id/Btnequal_id" android:layout_width="110dp" android:layout_height="60dp" android:layout_below="@id/Btn1_id" android:text="=" android:onClick="btnequalClicked" />42

Page 43: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

<Button android:id="@+id/Btndivide_id" android:layout_width="90dp" android:layout_height="60dp" android:layout_below="@id/Btn1_id" android:layout_toRightOf="@id/Btnequal_id" android:text="/" android:onClick="btndivideClicked" /> <Button android:id="@+id/Btnmulti_id" android:layout_width="90dp" android:layout_height="60dp" android:layout_below="@id/Btnminus_id" android:layout_toRightOf="@id/Btndivide_id" android:text="*" android:onClick="btnmultiClicked"/></RelativeLayout>Setting up Java

package com.javasamples.calci1;import android.net.Uri;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.EditText;import com.google.android.gms.appindexing.Action;import com.google.android.gms.appindexing.AppIndex;import com.google.android.gms.common.api.GoogleApiClient;public class MainActivity extends AppCompatActivity { public String str = ""; Character op = 'q'; int i, num, numtemp; EditText showResult; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); showResult = (EditText) findViewById (R.id.result_id); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } public void btn1Clicked(View v) {

43

Page 44: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

insert(1); } public void btn2Clicked(View v) { insert(2); } public void btn3Clicked(View v) { insert(3); } public void btn4Clicked(View v) { insert(4); } public void btn5Clicked(View v) { insert(5); } public void btn6Clicked(View v) { insert(6); } public void btn7Clicked(View v) { insert(7); } public void btn8Clicked(View v) { insert(8); } public void btn9Clicked(View v) { insert(9); } public void btnplusClicked(View v) { perform(); op = '+'; } public void btnminusClicked(View v) { perform(); op = '-'; } public void btndivideClicked(View v) { perform(); op = '/'; } public void btnmultiClicked(View v) { perform(); op = '*'; } public void btnequalClicked(View v) { calculate(); } public void btnclearClicked(View v) { reset(); } private void reset() { // TODO Auto-generated method stub str = ""; op = 'q'; num = 0; numtemp = 0; showResult.setText(""); } private void insert(int j) { // TODO Auto-generated method stub str = str + Integer.toString(j); num = Integer.valueOf(str).intValue(); showResult.setText(str); } private void perform() { // TODO Auto-generated method stub str = "";44

Page 45: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

numtemp = num; } private void calculate() { // TODO Auto-generated method stub if (op == '+') num = numtemp + num; else if (op == '-') num = numtemp - num; else if (op == '/') num = numtemp / num; else if (op == '*') num = numtemp * num; showResult.setText("" + num); } @Override public void onStart() { super.onStart();

// ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.javasamples.calci1/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop();

// ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.javasamples.calci1/http/host/path")); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }}

Output:45

Page 46: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Result: Thus the android Calculator application was successfully executed.

Ex.no. CREATION OF SIMPLE GRAPHICAL APPLICATION

Aim:

To create an application that draws basic graphical primitives on the screen using Android

Studio.

Algorithm:

1. Using the Android Studio create a project of the type mobile application.

2. Create a simple application in the project.

3. Click on the Design tab and design the prototype of the application.

4. Click on source tab and modify the application logic of the application.

5. Save the project.

6. Right click on the project and click on deploy and undeploy.

7. Then test the android application.

46

Page 47: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Steps:

1. View class which is used to draw graphical items on to the android app screen.

2. In this exercise we will draw some graphic primitives using Paint, View, Canvas and a

method on Draw ().

3. Go ahead and start our project.

4. In the Add an Activity section Select No Activity.

47

Page 48: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

5. Open the Project Window.

6. Expand the app and then the java folders.

48

Page 49: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

7. Now we need to extend the View Class to the Sample Canvas class we just created. Go ahead

and edit the Java File.

8. Now we need to create a Paint object.

9. So above the constructor definition add the following code.

10. Now place the cursor below the constructor definition and press [ALT] + [Insert] and select

Override Methods from the popup Menu.

11. To draw a rectangle we use the function:

canvas.drawRect (float left, float top, float right, float bottom, Paint paint) ;

The arguments can be depicted as shown below:

The co-ordinates of: A = (left, top) B = (right, bottom) paint is the paint object we created.

Let’s draw a rectangle now:

canvas.drawRect(100,100,300,300,paint) ;

9. Drawing a circle

canvas.drawCircle (float cx, float cy, float radius, Paint paint) The co-ordinates of A =

(cx,cy).And the length AB = radius.Let’s draw a circle with fill color green center at (200,200)

and radius paint.setColor(Color.GREEN) ; canvas.drawCircle(200,200,75,paint) ;

Setting up Java:

packagecom.kani.student.kani;

importandroid.graphics.Bitmap;

importandroid.graphics.Canvas;

importandroid.graphics.Color;

importandroid.graphics.Paint;

importandroid.graphics.drawable.BitmapDrawable;

importandroid.net.Uri;

importandroid.os.Bundle;

importandroid.support.design.widget.FloatingActionButton;

49

Page 50: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

importandroid.support.design.widget.Snackbar;

importandroid.support.v7.app.AppCompatActivity;

importandroid.support.v7.widget.Toolbar;

importandroid.view.Menu;

importandroid.view.MenuItem;

importandroid.view.View;

importandroid.widget.LinearLayout;

importcom.google.android.gms.appindexing.Action;

importcom.google.android.gms.appindexing.AppIndex;

importcom.google.android.gms.common.api.GoogleApiClient;

importcom.google.android.gms.common.api.PendingResult;

importcom.google.android.gms.common.api.Status;

publicclassMainActivity extends AppCompatActivity {

floatx,y,radius;

/**

* ATTENTION: This was auto-generated to implement the App Indexing API.

* See https://g.co/AppIndexing/AndroidStudio for more information.

*/

private GoogleApiClient client;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Paintpaint =new Paint();

paint.setColor(Color.parseColor("#CD5C5C"));

Bitmap bg = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(bg);

canvas.drawRect(50, 50, 300, 300, paint);

LinearLayout ll = (LinearLayout) findViewById(R.id.rect);

ll.setBackgroundDrawable(new BitmapDrawable(bg));

paint.setColor(Color.parseColor("#FF0786FC"));

50

Page 51: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

canvas.drawCircle(200, 200, 100,paint);

LinearLayout ll1 = (LinearLayout) findViewById(R.id.circle);

paint.setColor(Color.BLACK);

canvas.drawLine(100, 200, 300, 200, paint);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

setSupportActionBar(toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

fab.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)

.setAction("Action", null).show();

} });

// ATTENTION: This was auto-generated to implement the App Indexing API.

// See https://g.co/AppIndexing/AndroidStudio for more information.

client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.menu_main, menu);

return true; }

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement

if (id == R.id.action_settings) {

return true; }

return super.onOptionsItemSelected(item); }

51

Page 52: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

@Override

public void onStart() {

super.onStart();

// ATTENTION: This was auto-generated to implement the App Indexing API.

// See https://g.co/AppIndexing/AndroidStudio for more information.

client.connect();

Action viewAction = Action.newAction(

Action.TYPE_VIEW, // TODO: choose an action type.

"Main Page", // TODO: Define a title for the content shown.

// TODO: If you have web page content that matches this app activity's content,

// make sure this auto-generated web page URL is correct.

// Otherwise, set the URL to null.

Uri.parse("http://host/path"),

// TODO: Make sure this auto-generated app deep link URI is correct.

Uri.parse("android-app://com.kani.student.kani/http/host/path") );

AppIndex.AppIndexApi.start(client, viewAction); }

@Override

public void onStop() {

super.onStop();

// ATTENTION: This was auto-generated to implement the App Indexing API.

// See https://g.co/AppIndexing/AndroidStudio for more information.

Action viewAction = Action.newAction(

Action.TYPE_VIEW, // TODO: choose an action type.

"Main Page", // TODO: Define a title for the content shown.

// TODO: If you have web page content that matches this app activity's content,

// make sure this auto-generated web page URL is correct.

// Otherwise, set the URL to null.

Uri.parse("http://host/path"),

// TODO: Make sure this auto-generated app deep link URI is correct.

Uri.parse("android-app://com.kani.student.kani/http/host/path") );

PendingResult<Status> end = AppIndex.AppIndexApi.end(client, viewAction);

client.disconnect(); }}

52

Page 53: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Content_main.xml:

<?xmlversion="1.0"encoding="utf-8"?>

<RelativeLayoutxmlns: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:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

app:layout_behavior="@string/appbar_scrolling_view_behavior"

tools:context="com.kani.student.kani.MainActivity"

tools:showIn="@layout/activity_main">

<LinearLayout

android:orientation="horizontal"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:layout_marginTop="184dp"

android:id="@+id/rect"></LinearLayout>

</RelativeLayout>

Output:

53

Page 54: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Result: Thus the android Graphical Primitive Screens application was successfully

executed.

Ex.No. CREATION OF SIMPLE DATA HANDLING APPLICATION

Aim:

To create an application that makes use of database using Android Studio.

Algorithm:

1. Using the Android Studio create a project of the type mobile application.

2. Create a simple application in the project.

3. Click on the Design tab and design the prototype of the application.

4. Click on source tab and modify the application logic of the application.

5. Save the project.

6. Right click on the project and click on deploy and undeploy.54

Page 55: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

7. Then test the android application.

Steps:

To use a database to save and access data.

We will use the SQLite Database and SQLiteOpenHelper classes to implement database

handling.

55

Start a New Project “Namelist”:

Page 56: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

56

Page 57: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Open the activity_main.xml layout and in my android studio 1.5 there is bunch of

custom views with a floating button.

Setting up XML:

57

Page 58: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

<?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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.javasamples.mydata1.MainActivity" tools:showIn="@layout/activity_main">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:weightSum="1">

<TextView android:layout_width="276dp" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Enter your name" android:id="@+id/textView" android:layout_weight="0.03" />

<EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/name" android:layout_weight="0.03" android:hint="your name here" />

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Enter your Age" android:id="@+id/textView2"58

Page 59: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

android:layout_weight="0.03" />

<EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/age" android:layout_weight="0.03" android:hint=" your Age Here" />

<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ADD DATA" android:id="@+id/button_add" android:layout_weight="0.03" /></LinearLayout></RelativeLayout>Setting up Main activity .java

DatabaseHelper.java

package com.infotech.rit.database_con;

import android.content.ContentValues;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper{ public static final String DATABASE_NAME="student.db"; public static final String TABLE_NAME="student_tb"; public static final String COL1="ID"; public static final String COL2="NAME"; public static final String COL3="AGE";

public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1);

}

@Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table" + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,AGE INTEGER)"); }

59

Page 60: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("drop table if exists "+TABLE_NAME); onCreate(db); } public boolean insertData(String name,String age) { SQLiteDatabase db=this.getWritableDatabase(); ContentValues contentValues=new ContentValues(); contentValues.put(COL2,name); contentValues.put(COL3,age);

long result=db.insert(TABLE_NAME,null,contentValues); if(result==-1) return false; else return true; }}MainActivity.java

package com.infotech.rit.database_con;

import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

DatabaseHelper mydb; EditText name,age; Button btnaddData;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mydb=new DatabaseHelper(this);

name=(EditText)findViewById(R.id.name); age=(EditText)findViewById(R.id.age); btnaddData=(Button)findViewById(R.id.button_add); addData(); }60

Page 61: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

public void addData() { btnaddData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean isInserted= mydb.insertData(name.getText().toString(),age.getText().toString()); if(isInserted=true) Toast.makeText(MainActivity.this,"data inserted",Toast.LENGTH_LONG).show(); else Toast.makeText(MainActivity.this,"insertion failed",Toast.LENGTH_LONG).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); }}Output:

Result: Thus the android Database handling application was successfully executed.

61

Page 62: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Ex.No. CREATION OF SIMPLE RSS FEED PARSING APPLICATION

Aim:

To develop an application that parse RSS feeds from XML RSS File in internet using Android

Studio.

Algorithm:

1. Using the Android Studio create a project of the type mobile application.

2. Create a simple application in the project.

3. Click on the Design tab and design the prototype of the application.

4. Click on source tab and modify the application logic of the application.

5. Save the project.

6. Right click on the project and click on deploy and undeploy.

7. Then test the android application.

Steps:

Create a new project with an empty activity.

Edit the xml layout file to create a layout with a List View with id lstMain.

Setting up Main Activity java:

package com.infotech.rit.database_con;import java.io.IOException;import java.net.MalformedURLException;import java.net.URL;import javax.xml.parsers.ParserConfigurationException;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.xml.sax.InputSource;import org.xml.sax.SAXException;import org.xml.sax.XMLReader;import android.app.ListActivity;import android.content.Intent;import android.net.Uri;import android.os.AsyncTask;import android.os.Bundle;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;

62

Page 63: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

public class AndroidRssReader extends ListActivity{ private RSSFeed myRssFeed = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

new MyTask().execute();

} private class MyTask extends AsyncTask {

@Override protected Void doInBackground(Void... arg0) { try { URL rssUrl = new URL("http://www.gov.hk/en/about/rss/govhkrss.data.xml"); SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance(); SAXParser mySAXParser = mySAXParserFactory.newSAXParser(); XMLReader myXMLReader = mySAXParser.getXMLReader(); RSSHandler myRSSHandler = new RSSHandler(); myXMLReader.setContentHandler(myRSSHandler); InputSource myInputSource = new InputSource(rssUrl.openStream()); myXMLReader.parse(myInputSource);

myRssFeed = myRSSHandler.getFeed(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

return null; }

@Override protected void onPostExecute(Void result) {63

Page 64: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

if (myRssFeed!=null) { TextView feedTitle = (TextView)findViewById(R.id.feedtitle); TextView feedDescribtion = (TextView)findViewById(R.id.feeddescribtion); TextView feedPubdate = (TextView)findViewById(R.id.feedpubdate); TextView feedLink = (TextView)findViewById(R.id.feedlink); feedTitle.setText(myRssFeed.getTitle()); feedDescribtion.setText(myRssFeed.getDescription()); feedPubdate.setText(myRssFeed.getPubdate()); feedLink.setText(myRssFeed.getLink());

ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1,myRssFeed.getList()); setListAdapter(adapter);

}else{

TextView textEmpty = (TextView)findViewById(android.R.id.empty); textEmpty.setText("No Feed Found!"); }

super.onPostExecute(result); }

}

@Override protected void onListItemClick(ListView l, View v, int position, long id) {

Uri feedUri = Uri.parse(myRssFeed.getItem(position).getLink()); Intent myIntent = new Intent(Intent.ACTION_VIEW, feedUri); startActivity(myIntent); }}XML Coding:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">

<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />

64

Page 65: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/feedtitle" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/feeddescribtion" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/feedpubdate" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:autoLink="web" android:id="@+id/feedlink" />

<ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@android:id/empty" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="waiting" /></LinearLayout>Setting up Manifest.xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javasamples.rss"> <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="19" /> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar"> <intent-filter>

65

Page 66: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- ATTENTION: This was auto-generated to add Google Play services to your project for App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. --> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> </application>

</manifest>

Output:

66

Page 67: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Result: Thus the android RSS feed application was successfully executed.

67

Page 68: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Ex.No. 1. CREATION OF MULTITHREADING IN ANDROID APPLICATION

Aim:

To develop Multithreading in an application using Android Studio.

Algorithm:

1. Using the Android Studio create a project of the type mobile application.

2. Create a simple application in the project.

3. Click on the Design tab and design the prototype of the application.

4. Click on source tab and modify the application logic of the application.

5. Save the project.

6. Right click on the project and click on deploy and undeploy.

7. Then test the android application.

Steps:

• When an application is launched, the system creates a thread of execution for the

application, called "main." This thread is very important because it is in charge of

dispatching events to the appropriate user interface widgets, including drawing events.

• It is also the thread in which your application interacts with components from the

Android UI toolkit (components from the android.widget and android.view packages).

As such, the main thread is also sometimes called the UI thread.

• The system does not create a separate thread for each instance of a component.

All components that run in the same process are instantiated in the UI thread, and

system calls to each component are dispatched from that thread.

• When your app performs intensive work in response to user interaction, this

single thread model can yield poor performance unless you implement your application

properly.

• Specifically, if everything is happening in the UI thread, performing long

operations such as network access or database queries will block the whole UI.

• When the thread is blocked, no events can be dispatched, including drawing

events. From the user's perspective, the application appears to hang. Even worse, if the

UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is

presented with the infamous "application not responding" (ANR) dialog.

68

Page 69: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

• Additionally, the Andoid UI toolkit is not threadsafe. So, you must not manipulate

your UI from a worker thread—you must do all manipulation to your user interface

from the UI thread. Thus, there are simply two rules to Android's single thread model:

• Do not block the UI thread.

• Do not access the Android UI toolkit from outside the UI thread?

WORKER THREADS

Because of the single thread model described above, it's vital to the responsiveness of your

application's UI that you do not block the UI thread. If you have operations to perform that are

not instantaneous, you should make sure to do them in separate threads ("background" or

"worker" threads).

• We are going to create an app that loads image bitmap from a URL and sets it to

an ImageView.

• We are using two interface here – The User Interface and the Network Interface,

we need to implement multithreading i.e. create a new thread to interact with the

network.

• Create a new Project (Multi Threading) with an empty activity (MainActivity).

• Edit the activity_main.xml to add an ImageView and a Button which when

clicked loads image to the ImageView. Testing:

Run the application in an emulator or a device and test it.

You need to be connected to internet to load image from internet.

Setting up 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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior"

69

Page 70: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

tools:context="com.javasamples.multi1.MainActivity" tools:showIn="@layout/activity_main">

<TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/TextView01"/>

<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/Button01" android:text="click to change text" android:layout_below="@+id/EditText01" android:layout_alignParentStart="true" android:layout_marginTop="89dp" android:textColor="#f90303" android:textSize="34sp" />

<EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/EditText01" android:text="@+id/EditText01" android:textSize="34dp" android:textColor="#fc0505" /></RelativeLayout>Setting up Java:

package com.javasamples.multi1;

import android.net.Uri;

import android.os.Bundle;

import android.os.Handler;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

import com.google.android.gms.appindexing.Action;

import com.google.android.gms.appindexing.AppIndex;

import com.google.android.gms.common.api.GoogleApiClient;

public class MainActivity extends AppCompatActivity {

/**

70

Page 71: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

* ATTENTION: This was auto-generated to implement the App Indexing API.

* See https://g.co/AppIndexing/AndroidStudio for more information.

*/

private GoogleApiClient client;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

((Button)findViewById(R.id.Button01)).setOnClickListener(new

View.OnClickListener() {

@Override

public void onClick(View v) {

updateUI("start of long operation");

// This will cause the UI to freeze

updateUI(doLongOperation());

//This causes the application to crash

/* (new Thread(new Runnable() {

@Override

public void run() {

updateUI(doLongOperation());

}

})).start(); */

/*

// option 1

final Handler myHandler = new Handler(){

@Override

public void handleMessage(Message msg) {

updateUI((String)msg.obj);

}

};

(new Thread(new Runnable() {

71

Page 72: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

@Override

public void run() {

Message msg = myHandler.obtainMessage();

msg.obj = doLongOperation();

myHandler.sendMessage(msg);

}

})).start();

*/

// option 2

final Handler myHandler = new Handler();

(new Thread(new Runnable() {

@Override

public void run() {

final String res = doLongOperation();

for (int i = 0; i < 30; i++) {

myHandler.post(new Runnable() {

@Override

public void run() {

updateUI(res);

}

});

}

}

})).start();

}

});

// ATTENTION: This was auto-generated to implement the App Indexing API.

// See https://g.co/AppIndexing/AndroidStudio for more information.

client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

}

72

Page 73: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

public void updateUI(String str) {

((TextView) findViewById(R.id.TextView01)).setText(str);

}

public String doLongOperation() {

try {

Thread.sleep(5000);

} catch (InterruptedException e) {

e.printStackTrace();

}

return "end of long operation";

}

@Override

public void onStart() {

super.onStart();

// ATTENTION: This was auto-generated to implement the App Indexing API.

// See https://g.co/AppIndexing/AndroidStudio for more information.

client.connect();

Action viewAction = Action.newAction(

Action.TYPE_VIEW, // TODO: choose an action type.

"Main Page", // TODO: Define a title for the content shown.

// TODO: If you have web page content that matches this app activity's

content,

// make sure this auto-generated web page URL is correct.

// Otherwise, set the URL to null.

Uri.parse("http://host/path"),

// TODO: Make sure this auto-generated app deep link URI is correct.

Uri.parse("android-app://com.javasamples.multi1/http/host/path")

);

AppIndex.AppIndexApi.start(client, viewAction);

}

73

Page 74: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

@Override

public void onStop() {

super.onStop();

// ATTENTION: This was auto-generated to implement the App Indexing API.

// See https://g.co/AppIndexing/AndroidStudio for more information.

Action viewAction = Action.newAction(

Action.TYPE_VIEW, // TODO: choose an action type.

"Main Page", // TODO: Define a title for the content shown.

// TODO: If you have web page content that matches this app activity's

content,

// make sure this auto-generated web page URL is correct.

// Otherwise, set the URL to null.

Uri.parse("http://host/path"),

// TODO: Make sure this auto-generated app deep link URI is correct.

Uri.parse("android-app://com.javasamples.multi1/http/host/path")

);

AppIndex.AppIndexApi.end(client, viewAction);

client.disconnect(); }}

Output:

Result: Thus the android Multithreading application was successfully executed.

74

Page 75: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Ex.No. 2. CREATION OF MULTITHREADING IN ANDROID

APPLICATION

Aim:

To develop Multithreading in an application using Android Studio.

Algorithm:

8. Using the Android Studio create a project of the type mobile application.

9. Create a simple application in the project.

10. Click on the Design tab and design the prototype of the application.

11. Click on source tab and modify the application logic of the application.

12. Save the project.

13. Right click on the project and click on deploy and undeploy.

14. Then test the android application.

Steps:

• When an application is launched, the system creates a thread of execution for the

application, called "main." This thread is very important because it is in charge of

dispatching events to the appropriate user interface widgets, including drawing events.

• It is also the thread in which your application interacts with components from the

Android UI toolkit (components from the android.widget and android.view packages).

As such, the main thread is also sometimes called the UI thread.

• The system does not create a separate thread for each instance of a component.

All components that run in the same process are instantiated in the UI thread, and

system calls to each component are dispatched from that thread.

• When your app performs intensive work in response to user interaction, this

single thread model can yield poor performance unless you implement your application

properly.

• Specifically, if everything is happening in the UI thread, performing long

operations such as network access or database queries will block the whole UI.

• When the thread is blocked, no events can be dispatched, including drawing

events. From the user's perspective, the application appears to hang. Even worse, if the

75

Page 76: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is

presented with the infamous "application not responding" (ANR) dialog.

• Additionally, the Andoid UI toolkit is not threadsafe. So, you must not manipulate

your UI from a worker thread—you must do all manipulation to your user interface

from the UI thread. Thus, there are simply two rules to Android's single thread model:

• Do not block the UI thread.

• Do not access the Android UI toolkit from outside the UI thread?

WORKER THREADS

Because of the single thread model described above, it's vital to the responsiveness of your

application's UI that you do not block the UI thread. If you have operations to perform that are

not instantaneous, you should make sure to do them in separate threads ("background" or

"worker" threads).

• We are going to create an app that loads image bitmap from a URL and sets it to

an ImageView.

• We are using two interface here – The User Interface and the Network Interface,

we need to implement multithreading i.e. create a new thread to interact with the

network.

• Create a new Project (Multi Threading) with an empty activity (MainActivity).

• Edit the activity_main.xml to add an ImageView and a Button which when

clicked loads image to the ImageView. Testing:

Run the application in an emulator or a device and test it.

You need to be connected to internet to load image from internet.

Setting up 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"

76

Page 77: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

app:layout_behavior="@string/appbar_scrolling_view_behavior"

tools:context="com.library.bec.ex_multithrading1.MainActivity"

tools:showIn="@layout/activity_main">

<LinearLayout

android:orientation="vertical"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_alignParentTop="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true">

<ProgressBar

style="?android:attr/progressBarStyleHorizontal"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:id="@+id/progressBar" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:id="@+id/txtdis" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Start"

77

Page 78: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

android:id="@+id/button"

android:onClick="startprogress"/>

</LinearLayout></RelativeLayout>

Setting up Java

package com.library.bec.ex_multithrading1;

import android.net.Uri;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.View;import android.view.Menu;import android.view.MenuItem;import android.widget.ProgressBar;import android.widget.TextView;

import com.google.android.gms.appindexing.Action;import com.google.android.gms.appindexing.AppIndex;import com.google.android.gms.common.api.GoogleApiClient;

public class MainActivity extends AppCompatActivity { private ProgressBar progress; private TextView t1; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progress = (ProgressBar) findViewById(R.id.progressBar); t1 = (TextView) findViewById(R.id.txtdis); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); }

78

Page 79: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; }

@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId();

//noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; }

return super.onOptionsItemSelected(item); }

public void startprogress(View view) { Runnable runnable = new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { final int value = i; doSomeWork(); progress.post(new Runnable() { @Override public void run() { t1.setText("Updating"); progress.setProgress(value); } }); } } }; new Thread(runnable).start(); } private void doSomeWork() { try { Thread.sleep(2000); } catch (Exception e) { } } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown.79

Page 80: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

// TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.library.bec.ex_multithrading1/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.library.bec.ex_multithrading1/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }}Output:

80

Page 81: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Result: Thus the android GPS location application was successfully executed.

Ex.No. CREATION OF SIMPLE GPS LOCATION APPLICATION

Aim:

To develop a GPS Location application using Android Studio.

Algorithm:

• Using the Android Studio create a project of the type mobile application.

• Create a simple application in the project.

• Click on the Design tab and design the prototype of the application.

• Click on source tab and modify the application logic of the application.

• Save the project.

• Right click on the project and click on deploy and undeploy.

• Then test the android application.

Steps:

For this we will use:

• System location service

• LocationManager and LocationListener

• Permission to access FINE_LOCATION

• Start a new project “GeoLocation” with an empty activity.

• Edit the activity_main.xml to change the parent layout to LinearLayout (Verical)

and to add the GPS locating cannot be used indoors.

If using an emulator you need to pass the location values yourself using the settings of the

emulator.

So, it is better to test it in a device outdoor.

Setting up XML:

81

Page 82: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

<?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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.javasamples.ex_8_gps.MainActivity" tools:showIn="@layout/activity_main"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/Linearlayout" android:layout_below="@+id/textview1" android:layout_alignParentStart="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textview1" android:layout_alignParentTop="true" android:text="Lattitude" android:textSize="34dp" /> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/Linearlayout1" android:layout_below="@+id/textview1" android:layout_alignParentStart="true" >

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textview2" android:layout_alignParentTop="true" android:text="Longitude" android:textSize="34dp" /> </LinearLayout></RelativeLayout>

Setting up Java:

82

Page 83: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

package com.javasamples.ex_8_gps;

import android.Manifest;import android.content.Context;import android.content.pm.PackageManager;import android.location.Criteria;import android.location.Location;import android.location.LocationListener;import android.location.LocationManager;import android.os.Build;import android.os.Bundle;import android.support.v4.content.ContextCompat;import android.support.v7.app.AppCompatActivity;import android.view.Menu;import android.view.MenuItem;import android.widget.TextView;import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements LocationListener { LocationManager lmanager; String provider;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); provider = lmanager.getBestProvider(criteria, false);

if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } if (provider != null && !provider.equals("")) { Location location = lmanager.getLastKnownLocation(provider); lmanager.requestLocationUpdates(provider, 20000, 1, (LocationListener) this); if (location != null) { onLocationChanged(location); } else { Toast.makeText(getBaseContext(), "Location not available", Toast.LENGTH_LONG).show();83

Page 84: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

} } else { Toast.makeText(getBaseContext(), "Location Found", Toast.LENGTH_LONG).show(); } }

@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; }

@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId();

//noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; }

return super.onOptionsItemSelected(item); }

@Override public void onLocationChanged(Location location) { TextView t1 = (TextView) findViewById(R.id.textview1); TextView t2 = (TextView) findViewById(R.id.textview2);

t1.setText("" + location.getLatitude()); t2.setText("" + location.getLongitude());

}

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

}

@Override public void onProviderEnabled(String provider) {

}84

Page 85: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

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

Setting up Manifest.xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javasamples.ex_8_gps"> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>

Output:

85

Page 86: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Result: Thus the android GPS location application was successfully executed.

Ex.No. CREATION OF WRITING DATA TO SD CARD APPLICATION

Aim:

To develop a Writing data to SD Card application using Android Studio.

Algorithm:

• Using the Android Studio create a project of the type mobile application.

• Create a simple application in the project.

• Click on the Design tab and design the prototype of the application.

• Click on source tab and modify the application logic of the application.

• Save the project.

• Right click on the project and click on deploy and undeploy.

• Then test the android application.

Steps:

• To learn how to use memory to store data in android studio app. • For this we use output stream classes.

86

Page 87: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

• Here we will use FileOutputStream to write data and FileInputStream to read data. • Edit the layout to add a text field through which we will input the text to be

written into file.

• Two buttons to execute writing and reading of file respectively.

• A TextView to display the text inside the file after reading.

Setting up 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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.javasamples.ex_9.MainActivity" tools:showIn="@layout/activity_main">

<LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/txtdata"/> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="286dp"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button1" android:onClick="readdata" android:text="Read data"/> <Button

87

Page 88: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button2" android:onClick="writedata" android:text="Write data"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button3" android:onClick="clear" android:text="Clear"/>

</LinearLayout>

</LinearLayout></RelativeLayout>Setting up Manifest.XML:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javasamples.ex_9"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" > </uses-permission>

<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" />

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

</manifest>Setting up Java:

88

Page 89: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

package com.javasamples.ex_9;

import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.EditText;import android.widget.Toast;

import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity { EditText E1;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); E1 = (EditText) findViewById(R.id.txtdata); }

@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; }

89

Page 90: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId();

//noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; }

return super.onOptionsItemSelected(item); }

public void readdata(View view) { try {

File f = new File("/sdcard/myfile.txt"); FileInputStream fin = new FileInputStream(f); BufferedReader bf=new BufferedReader(new InputStreamReader(fin)); String drow=""; String dbuf=""; while ((drow=bf.readLine())!=null) { dbuf+=drow+"\n"; E1.setText(dbuf); bf.close(); fin.close(); } Toast.makeText(getBaseContext(), "data read from sd card", Toast.LENGTH_LONG).show(); } catch(Exception e) { Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show(); } } public void writedata(View view) { try { File f = new File("/sdcard/myfile.txt"); f.createNewFile(); FileOutputStream fout = new FileOutputStream(f); OutputStreamWriter mout = new OutputStreamWriter(fout); mout.append(E1.getText().toString()); mout.close(); fout.close(); Toast.makeText(getBaseContext(), "data written to sd card", 90

Page 91: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Toast.LENGTH_LONG).show(); } catch(Exception e) { Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show(); } } public void clear(View view) { E1.setText(""); } }OUTPUT:

Result: Thus the android Writing data to SD Card application was successfully executed.

Ex.No. CREATION SIMPLE ALARM CLOCK APPLICATION

Aim:

To develop a Simple Alarm Clock application using Android Studio.

Algorithm:

• Using the Android Studio create a project of the type mobile application.

• Create a simple application in the project.

• Click on the Design tab and design the prototype of the application.

• Click on source tab and modify the application logic of the application.

• Save the project.

91

Page 92: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

• Right click on the project and click on deploy and undeploy.

• Then test the android application.

Setting up XML.file

<?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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.javasamples.ex_11_alarm.MainActivity" tools:showIn="@layout/activity_main"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentRight="true" android:layout_alignParentLeft="true" android:layout_alignParentEnd="true" android:layout_alignParentTop="true"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Set Time for Alarm in Seconds" android:id="@+id/textView" android:textColor="#f3021a" android:textSize="34dp" /> <EditText android:layout_width="match_parent" android:layout_height="164dp" android:id="@+id/txttime" android:inputType="none" /> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentRight="true" android:layout_alignParentLeft="true" android:layout_alignParentEnd="true" android:layout_alignParentTop="true">

92

Page 93: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start Alarm" android:id="@+id/button" android:onClick="Startalarm" android:textColor="#fc0404" android:textSize="34sp" /> </LinearLayout> </LinearLayout></RelativeLayout>Setting up Java

package com.javasamples.ex_11_alarm;import android.app.AlarmManager;import android.app.PendingIntent;import android.content.Intent;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml.93

Page 94: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void Startalarm(View view) { EditText E1=(EditText)findViewById(R.id.txttime); int i=Integer.parseInt(E1.getText().toString()); Intent intent=new Intent(this,MyBroadcastReceiver.class); PendingIntent pendingIntent=PendingIntent.getBroadcast(this.getApplicationContext(),234324243,intent,0); AlarmManager alarmManager=(AlarmManager)getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+(i*1000),pendingIntent); Toast.makeText(this,"Alarm set in" +i +"Seconds",Toast.LENGTH_LONG).show(); }}Setting up BroadcastReceiver java

package com.javasamples.ex_11_alarm;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.os.Vibrator;import android.widget.Toast;public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context,"alarm started",Toast.LENGTH_LONG).show(); Vibrator vibrator=(Vibrator)context.getSystemService(context.VIBRATOR_SERVICE); vibrator.vibrate(2000); }}Setting up Manifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javasamples.ex_11_alarm"> <uses-permission android:name="android.permission.VIBRATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />

94

Page 95: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

</intent-filter> </activity> <receiver android:name=".MyBroadcastReceiver"></receiver> </application> </manifest>Output:

Result: Thus the android Alarm Clock application was successfully executed.

Ex.No. CREATION OF SIMPLE ALERT MESSAGE

Aim:

To develop an application that creates an alert upon receiving a message application using

Android Studio.

Algorithm:

• Using the Android Studio create a project of the type mobile application.

• Create a simple application in the project.

• Click on the Design tab and design the prototype of the application.

• Click on source tab and modify the application logic of the application.95

Page 96: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

• Save the project.

• Right click on the project and click on deploy and undeploy.

• Then test the android application.

Steps:

Setting up the Project • Create a new project “Alert application” with an empty activity.

• Use the Layout editor to add two buttons to start and cancel alarm respectively.

• Set their ids to btnStart and btnCancel.

Setting up XML.file

<?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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.javasamples.ex_10_alarm.MainActivity" tools:showIn="@layout/activity_main">

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Message" android:textSize="34sp" android:id="@+id/textview"/> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textMultiLine" android:ems="10" android:id="@+id/editText"/>

<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Notify"

96

Page 97: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

android:id="@+id/button" android:textSize="34sp" android:onClick="notify" android:layout_gravity="bottom" /></RelativeLayout>Setting up Java

package com.javasamples.ex_10_alarm;

import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.Intent;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); }

@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; }97

Page 98: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId();

//noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; }

return super.onOptionsItemSelected(item); }

public void notify(View view) { EditText E1=(EditText)findViewById(R.id.editText); Intent intent=new Intent(this,ResultActivity.class); PendingIntent pendingIntent=PendingIntent.getActivity(this, 0, intent, 0); Notification notification=new Notification.Builder(this).setContentTitle("New Message").setContentText(E1.getText().toString()).setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pendingIntent).build(); NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); int l; l = Notification.FLAG_AUTO_CANCEL; manager.notify(0,notification); }}Output:

98

Page 99: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Result: Thus the android application for display alert message was successfully

executed

99

Page 100: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Viva -Voce

What is android?

A.Android is a stack of software for mobile devices which has Operating System, middleware

and some key applications. The application executes within its own process and its own instance

of Dalvik Virtual Machine. Many Virtual Machines run efficiently by a DVM device. DVM

executes Java language byte code which later transforms into .dex format files.

What are the advantages of Android?

* Features like weather details, live RSS feeds, opening screen, icon on the opening screen can

be customized

* Optimized DVM for mobile devices

* SQLite enables to store the data in a structured manner.

* Supports GSM telephone and Bluetooth, WiFi, 3G and EDGE technologies

* The development is a combination of a device emulator, debugging tools, memory profiling

and plug-in for Eclipse IDE.

Describe the APK format.

A.The APK file is compressed the AndroidManifest.xml file, application code (.dex files),

resource files, and other files. A project is compiled into a single .apk file.

What is .apk extension?

A.The extension for an Android package file, which typically contains all of the files related to a

single Android application. The file itself is a compressed collection of an AndroidManifest.xml

file, application code (.dex files), resource files, and other files. A project is compiled into a

single .apk file.

What is .dex extension?

A.Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped

into a single .apk file on the device. .dex files can be created by automatically translating

compiled applications written in the Java programming language.

100

Page 101: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

What is an activity?

A. A single screen in an application, with supporting Java code. An activity presents a visual

user interface for one focused endeavor the user can undertake.

What is a service?

A.A service doesn’t have a visual user interface, but rather runs in the background for an

indefinite period of time.

Describe a real time scenario where android can be used?

A .Imagine a situation that you are in a country where no one understands the language you

speak and you can not read or write. However, you have mobile phone with you.

How to select more than one option from list in android xml file? ********

A. Give an example.

Specify android id, layout height and width as depicted in the following example.

What languages does Android support for application development?

A.Android applications are written using the Java programming

language.

What is the Android Open Source Project?

A. We use the phrase “Android Open Source Project” or “AOSP” to refer to the people, the

processes, and the source code that make up Android.

What features does it have?

Browse our award-winning audio and video content

- Save contributors, topics and sections to your favourites folder

101

Page 102: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

- Add favourites to your homescreen with an expanded view or link

- Swipe through stunning full-screen picture galleries

- Share articles and galleries via the Android share function

Will it work on my phone?

A.The app will work on all phones and tablets running Android version 1.6 and above.

What is Mono for Android?

A. Mono for Android is a software development kit that allows developers to use the C#

language to create mobile applications for Android-based devices.Mono for Android exposes

two sets of APIs, the core .NET APIs that C# developers are familiar with as well as a C#

binding to Android's native APIs exposed through the Mono.Android.* namespace.You can use

Mono for Android to develop applications that are distributed through the Android Application

Stores or to deploy software to your personal hardware or the Android simulator.

Where is the UI Designer?

A. Mono for Android does not bundle a UI designer to create the UI XML files We do not

provide an integrated UI designer in Mono for Android 1.0. No decisions past that have been

made. We will be listening to user feedback to decide where to put resources for the future

versions.

How do I turn off, or reboot Android?

A. In earlier releases, you had to pull the battery or press the reset button, in newer releases, you

can hold down the 'end call' button and see a menu.

Can the user set a priority?

A. Don’t know, post your question to the developer’s community board.

What’s so special about Android?

102

Page 103: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

A. Unlike the proprietary iPhone operating system (now known as "iOS,"), which is under the

complete control of Apple — and the same goes for Research in Motion’s BlackBerry OS or

Microsoft’s Windows Phone platform — Google released Android as an open-source OS under

the auspices of the Open Handset Alliance, leaving phone manufacturers (relatively) free to

tweak Android as they see fit for a given handset.

Are Android phones called "Droids"?

A. Not necessarily. "Droid" is a brand name used by Verizon Wireless for its Android-based

phones — the Droid X, the Droid Eris, the Droid Incredible and so on. The HTC Evo 4G on

Sprint is not a "Droid," per se, but it’s still an Android smartphone.

How many apps are available for Android?

A. About 70,000 or so, growing by the day — still just a fraction of the 225,000-plus apps in the

Apple App Store, but the official Android Marketplace has quite the head of steam, not to

mention plenty of goodwill from the developer community given that Google doesn’t give apps

the star-chamber treatment.

What are the hottest new Android phones out right now?

A. Well, earlier this summer we got the HTC Evo 4G, which supports Sprint’s budding, next-

generation WiMax data network and boasts a 4.3-inch display — the same size as the screen on

the Motorola Droid X, another eyepopper of a phone, except it’s on Verizon instead of Sprint.

Samsung is in the midst of releasing a series of what it calls its Galaxy S-class Android phones:

They’re thin and light, they all have high-contrast 4-inch "Super

AMOLED" screens, and they’re available (or will be soon) on all four of the big U.S. carriers. If

you’re looking for an Android phone with a slide-out QWERTY, consider the new Motorola

Droid 2 on Verizon or the upcoming Samsung Epic 4G for Sprint.

How will you record a phone call in Android? How to get a handle on Audio Stream for a

call in Android?

A. Permissions.PROCESS_OUTGOING_CALLS: Allows an application to monitor, modify, or

abort outgoing calls. 103

Page 104: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Why cannot you run standard Java bytecode on Android?

A. Android uses Dalvik Virtual Machine (DVM) which requires a special bytecode. We need to

convert Java class files into Dalvik Executable files using an Android tool called "dx". In normal

circumstances, developers will not be using this tool directly and build tools will care for the

generation of DVM compatible files.

Can you deploy executable JARs on Android? Which packaging is supported by Android?

A. No. Android platform does not support JAR deployments. Applications are packed into

Android Package

(.apk) using Android Asset Packaging Tool (aapt) and then deployed on to Android platform.

Google provides Android Development Tools for Eclipse that can be used to generate Android

Package.

Android application can only be programmed in Java?

A. False. You can program Android apps in C/C++ using NDK .

What is an action?

A. The Intent Sender desires something or doing some task

What are Dalvik Executable files?

A. Dalvik Executable files have .dex extension and are zipped into a single .apk file on the

device.

How does Android system track the applications?

A. Android system assigns each application a unique ID that is called Linux user ID. This ID is

used to track each application.

When does Android start and end an application process?

A. Android starts an application process when application's component needs to be executed. It

then closes the process when it's no longer needed (garbage collection).

104

Page 105: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

How can two Android applications share same Linux user ID and share same VM?

A. The applications must sign with the same certificate in order to share same Linux user ID and

share same VM.

Can I use the GoToMeeting app for Android on my Android device?*****

A. Yes. If you’re running Android 2.2 or higher, you can install the GoToMeeting app from the

Android Market to join meetings and webinars as an attendee. We recommend using devices

with a 1Ghz processor or higher for optimal performance.

Does Android support Adobe Flash in the browser?

A.Flash support varies by device with Android 2.1. The Samsung Acclaim does not have Flash

support upon launch, but the HTC Desire will support Flash Lite 4.0 running Android 2.1. Flash

10.1 support is coming to Android-powered phones with Android 2.2.

Does Android support push email or is it pull?

A. Android 2.1 supports push e-mail for Exchange mail and Gmail.

Will the App run on my Android phone?

A. Yes, our App is fully compatible with any Android phone running Android software v2.1 or

later.

How do I install your App?

A. You can install our App from the Android Market by following the below steps:

Open the Android Market application in the Applications menu.

Hit the search icon and type in E.ON

To install it, hit the ‘Free’ button on the left hand side

105

Page 106: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

In the next screen, it will give you more details about the application including the different

functionalities it will need to access. Just click on OK to finish installing the application.

70. How do I find and download updates to the E.ON Android application?

A. Any updates to our App will appear on your notification menu at the top of your screen. Just

tap on the E.ON App icon and you'll be taken into the Android Market and be presented with the

E.ON App download page.

What is an Intent?

A class (Intent) which describes what a caller desires to do. The caller will send this intent to

Android's intent resolver, which finds the most suitable activity for the intent. E.g. opening a

PDF document is an intent, and the Adobe Reader apps will be the perfect activity for that intent

(class).

What is a Sticky Intent?

A. Sticky Intent is also a type of Intent which allows a communication between a function and a

service sendStickyBroadcast() performs a sendBroadcast(Intent) known as sticky, i.e. the Intent

you are sending stays around after the broadcast is complete, so that others can quickly retrieve

that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter ) . In all

other ways, this behaves the same as sendBroadcast(Intent). One example of a sticky broadcast

sent via the operating system is ACTION_BATTERY_CHANGED. When you call

registerReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that

was last broadcast for that action. Hence, you can use this to find the state of the battery without

necessarily registering for all future state changes in the battery.

What is a resource?

A. user defined JSON, XML, bitmap, or other file, injected into the application build process,

which can later be loaded from code.

How will you record a phone call in Android? or How to handle an Audio Stream for a call

in Android?

Permission.PROCESS_OUTGOING_CALLS: Will Allow an application to monitor, modify, or

abort outgoing calls. So using that permission we can monitor the Phone calls.

106

Page 107: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Does Android support the Bluetooth serial port profile? Yes.

Can an application be started on powerup? Yes.

How to Translate in Android?

The Google translator translates the data of one language into another language by using XMPP

to transmit data. You can type the message in English and select the language which is

understood by the citizens of the country in order to reach the message to the citizens.

Describe Briefly the Android Application Architecture Android Application Architecture has

the following components: Services like Network Operation

Intent - To perform inter-communication between activities or servicesResource Externalization

- such as strings and graphics .Notification signaling users - light, sound, icon, notification,

dialog etc.

Content Providers - They share data between applications

What is needed to make a multiple choice list with a

custom view for each row?

A. Multiple choice list can be viewed by making the CheckBox android:id value be

“@android:id /text1". That is the ID used by Android for the CheckedTextView in

simple_list_item_multiple_choice.

What dialog boxes are supported in Android? Android supports 4 dialog boxes:

• AlertDialog : An alert dialog box supports 0 to 3 buttons and a list of selectable elements,

including check boxes and radio buttons. Among the other dialog boxes, the most

suggested dialog box is the alert dialog box.

• ProgressDialog : This dialog box displays a progress wheel or a progress bar. It is an

extension of AlertDialog and supports adding buttons.

• DatePickerDialog : This dialog box is used for selecting a date by the user.

TimePickerDialog: This dialog box is used for selecting time by the user.

Introduction Android:

Android is an operating system for mobile devices that includes middleware and key

applications, and uses a modified version of the Linux kernel. It was initially developed by 107

Page 108: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Android Inc...It allows developers to write managed code in the Java language, controlling the

device via Google-developed Java libraries….. The Android SDK includes a comprehensive set

of development tools. These include a debugger, libraries, a handset emulator (based on QEMU),

documentation, sample code, and tutorials. Currently supported development platforms include

x86-architecture computers running Linux (any modern desktop Linux distribution), Mac OS X

10.4.8 or later, Windows XP or Vista. Android does not use established Java standards, i.e. Java

SE and ME. This prevents compatibility among Java applications written for those platforms and

those for the Android platform. Android only reuses the Java language syntax, but does not

provide the full-class libraries and APIs bundled with Java SE or ME

Features of Android:

Application framework enabling reuse and replacement of components

Dalvik virtual machine optimized for mobile devices

Integrated browser based on the open source WebKit engine

Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the

OpenGL ES 1.0 specification (hardware acceleration optional)

SQLite for structured data storage

Media support for common audio, video, and still image formats (MPEG4, H.264, MP3,

AAC, AMR, JPG,

PNG, GIF)

GSM Telephony (hardware dependent)

Bluetooth, EDGE, 3G, and WiFi (hardware dependent)

Camera, GPS, compass, and accelerometer (hardware dependent)

Rich development environment including a device emulator, tools for debugging,

memory and performance profiling, and a plugin for the Eclipse IDE.

What is an Application?

A. Collection of one or more activities, services, listeners, and intent receivers. An application

has a single manifest, and is compiled into a single .apk file on the device.

What is a Content Provider?

108

Page 109: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

A. A class built on ContentProvider that handles content query strings of a specific format to

return data in a specific format. See Reading and writing data to a content provider for

information on using content providers.

What is Drawable?

A. A compiled visual resource that can be used as a background, title, or other part of the screen.

It is compiled into an android.graphics.drawable subclass.

What are fragments in Android Activity?

A. Fragment represents a behavior or a portion of user interface in an Activity. And it is a self-

contained component with its own UI and lifecycle.

What is Service?

A. Service doesn't have a visual user interface, but rather runs in the background for an

indefinite period of time. For Example, a service might play background for music as the user

attends to other matters.

What is BroadReceivers?

A. BroadcastReceiver is a component that does nothing but receive and react to broadcast

announcements.

For example, the battery is low or that the user changed a language preference.

Android latest Version? A. Android 4.0.3

How many ways data stored in Android?

SharedPreferences, Internal Storage, .External Storage, SQLite Database, .Network connection

Types of Android applications?

Foreground, Background, .Intermittent, .Widget

109

Page 110: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

Android Development Tools?

The Android SDK and Virtual Device Manager Used to create and manage Android

Virtual Devices (AVD) and SDK packages.

The Android Emulator An implementation of the Android virtual machine designed to

run within a virtual device on your development computer. Use the emulator to test and

debug your Android applications.

Dalvik Debug Monitoring Service (DDMS) Use the DDMS perspective to monitor and

control the Dalvik virtual machines on which your debugging your application.

Android Asset Packaging Tool (AAPT) constructs the destributable Android packages

files (.apk).

Android Debug Bridge (ADB) A client-server application that provedes a link to a

running emulator.It lets you copy files, install compiled application packages (.apk), and

run shell commands.

What is View in Android?

A. Views are the base class for all visual interface elements (commonly known as controls or

widgets). All UI controls, including the layout classes, are derived for View.

What View Group in Android?

A. View Groups are extensions of the View class that can contain multiple child View.Extend

the ViewGroup class to create compound controls made up of interconnected child Views.

Implicent Intents and Late Runtime Binding?

A. An implicit Intent is mechanism that lets anonymous application components service action

request.That means you can ask the system to launch an Activity that can perform a given action

without knowing which application, or Activity, will do so.

What are Native Android Actions?

Native Android applications also use Intents to launch Activities and sub Activities

110

Page 111: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

ACTION-ANSWER Opens an Activity that handles immediately initiates a call using the

number supplied in the Intent URI. Genereally it's considered better from to use ACTION_DIAL

if possible.

ACTION_DELETE Starts an Activity hat lets you delete the data specified at that Intent's data

URI.

ACTION_DIAL Brings up a dialer application with the number to dial pre-populated from the

Intent URI. By default this is handled by the native Android phone dialer.

ACTION_EDIT Requests an Activity that can edit that data at the specified Intent

URI.ACTION_INSERT

ACTION_PICK, ACTION_SEARCH, ACTION_SENDTO, ACTION_SEND,

ACTION_VIEW, ACTION_WEB_SEARCH

What is Adapter?

A. Adapter are bridging classes that bind data to Views (such as List Views) used in the

user interface. The adapter is responsible for creating for creating the child Views used to

represent each item within the parent View, and providing access to the underlying data.

General Android questions

• The Activity life cycle is must. Different phases of Activity Life cycle. For example:

when and how the activity comes to foreground? Different Kinds of Intents ,Different

Kinds of Context ,Different Storage Methods in android

• Kinds of Log debugger and Debugger Configuration How to debug the application

on real device.

• How do you ensure that the app design will be consistent across the different screen

resolutions Thread concepts also plus points as we deal with the treads more.

• Can you able to build custom views and how?

• How to create flexible layouts, For example to place English, Chinese fonts.

• What is localization and how to achieve?

• How to avoid ANR status

111

Page 112: Cs 6611 mad lab manual

5105 –BHARATHIDASAN ENGINEERING COLLEGE

• How to do Memory management

• Inter Process Communication (IPC)

• What is onCreate(Bundle savedInstanceState), Have you used savedInstanceState when

and why?

112