0% found this document useful (0 votes)
392 views

Mobile Application Development Lab Manual

The document provides information about the Mobile Application Development Lab at Saveetha Engineering College. It outlines the objectives of the lab which are to understand mobile application development frameworks, design concepts, and capabilities/limitations of mobile devices. It then lists 12 experiments to be performed which involve developing apps using various mobile features like GUIs, layouts, databases, GPS, etc. It also lists the expected outcomes and references/equipment required.

Uploaded by

Naveen Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
392 views

Mobile Application Development Lab Manual

The document provides information about the Mobile Application Development Lab at Saveetha Engineering College. It outlines the objectives of the lab which are to understand mobile application development frameworks, design concepts, and capabilities/limitations of mobile devices. It then lists 12 experiments to be performed which involve developing apps using various mobile features like GUIs, layouts, databases, GPS, etc. It also lists the expected outcomes and references/equipment required.

Uploaded by

Naveen Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

1

19CS414

MOBILE APPLICATION DEVELOPMENT LAB


MANUAL
Department of Computer Science & Engineering
Saveetha Engineering College

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


2

MOBILE APPLICATION DEVELOPMENT LABORATORY            

OBJECTIVES:

 To understand the components and structure of mobile application development frameworks for Android
and windows OS based mobiles.
 To understand how to work with various mobile application development frameworks.
 To learn the basic and important design concepts and issues of development of mobile applications.
 To 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. Write an application that draws basic graphical primitives on the screen.
4. Develop an application that makes use of databases.
5. Develop an application that makes use of Notification Manager
6. Implement an application that uses Multi-threading
7. Develop a native application that uses GPS location information
8. Implement an application that writes data to the SD card.
9. Implement an application that creates an alert upon receiving a message
10. Write a mobile application that makes use of RSS feed
11. Develop a mobile application to send an email.
12. Develop a Mobile application for simple needs (Mini Project)

OUTCOMES:

Upon Completion of the course, the students will be able to:

 Develop mobile applications using GUI and Layouts.


 Develop mobile applications using Event Listener.
 Develop mobile applications using Databases.
 Develop mobile applications using RSS Feed, Internal/External Storage, SMS, Multi-threading and GPS.
 Analyze and discover own mobile app for simple needs.

REFERENCES:

1. Build Your Own Security Lab, Michael Gregg, Wiley India

LIST OF EQUIPMENTS FOR A BATCH OF 30 STUDENTS:

SOFTWARE: C / C++ / Java or equivalent compiler GnuPG, Snort, N-Stalker or Equivalent

HARDWARE: Standalone desktops – 30 Nos. (or) Server supporting 30 terminals or more.

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


3

CONTENTS

S.N EXPERIMENTS DATE MARKS


O SIGNATURE

1 Develop an application that uses GUI Components, Fonts


and Colors

2 Develop an application that uses Layout Managers and


Event Listeners

3 Application that draws basic graphical primitives on the


screen

4 Develop an application that makes use of databases

5 Implement an application that creates an alert upon


receiving a message

6 Develop a native application that uses GPS location


information

7 Implement an application that writes data to the SD card

8 Write a mobile application that creates alarm clock

9 Develop an application that makes use of RSS Feed

10 Develop a native calculator application

Multithreading
11

12 E-Mail

13 Mini Project – Speech to text converter

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


4

1. Develop an application that uses GUI Components, Fonts and Colors

AIM:
To develop an application that uses GUI Components, Fonts and Colors.

PROCEDURE:
1. Open Android Studio IDE.
2. Create the project Ex_No_1.
3. Go to package explorer in the left hand side. Select the project Ex_No_1.

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


5

4. Go to res folder and select layout. Double click the activity_main.xml file.
5. Now you can see the Graphical layout window.
6. Drag and drop the following components:
a. One TextView with text Hello World
b. Three Buttons with labeled as Change Font Size, Change Font Color and Change Font Style
7. Again go to package explorer in the left hand side. Select the project Ex_No_1.
8. Go to src folder. Double click the MainActivity.java file.
9. In java file write the activities done by the application such as, actions of buttons.
10. Finally run the android application.

PROGRAM:
Activity-main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:gravity="center"
android:text="Hello World!"
android:textSize="25sp"
android:textStyle="bold" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:gravity="center"
android:text="Change font size"
android:textSize="25sp" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:gravity="center"
android:text="Change color"
android:textSize="25sp" />
</LinearLayout>

MainActivity.java:
package com.example.sreer.font;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity


{
intch=1;

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


6

float font=30;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView t= (TextView) findViewById(R.id.textView);
Button b1= (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
t.setTextSize(font);
font = font + 5;
if (font == 50)
font = 30;
}
});
Button b2= (Button) findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (ch) {
case 1:
t.setTextColor(Color.RED);
break;
case 2:
t.setTextColor(Color.GREEN);
break;
case 3:
t.setTextColor(Color.BLUE);
break;
case 4:
t.setTextColor(Color.CYAN);
break;
case 5:
t.setTextColor(Color.YELLOW);
break;
case 6:
t.setTextColor(Color.MAGENTA);
break;
}
ch++;
if (ch == 7)
ch = 1;
}
});
}
}

OUTPUT:

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


7

RESULT:
Thus the application that uses GUI Components, Fonts and Colors has been developed and the output was verified.

2. Develop an application that uses Layout Managers and Event Listeners

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


8

AIM:
To develop an application that uses Layout Managers and Event Listeners.
PROCEDURE:
1. Open Android Studio IDE.
2. Create the project Ex_No_2.
3. Go to package explorer in the left hand side. Select the project Ex_No_2.
4. Go to res folder and select layout. Double click the activity_main.xml file.
5. Now you can see the Graphical layout window.
6. Drag and drop the following components:
a. Four TextViews with texts as Name, Gender, Degree and Programming Knowledge
b. One EditText
c. One Button with labeled as SUBMIT
7. Again go to package explorer in the left hand side. Select the project Ex_No_2.
8. Go to src folder. Double click the MainActivity.java file.
9. In java file write the activities done by the application such as, actions of button.
10. Finally run the android application.

PROGRAM
activity-main.xml:

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


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

<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:text="Details Form"
android:textSize="25sp"
android:gravity="center"/>
</LinearLayout>

<GridLayout
android:id="@+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:layout_marginBottom="200dp"
android:columnCount="2"
android:rowCount="3">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="0"
android:layout_column="0"
android:text="Name"
android:textSize="20sp"

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


9

android:gravity="center"/>

<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="0"
android:layout_column="1"
android:ems="10"/>

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="1"
android:layout_column="0"
android:text="Reg.No"
android:textSize="20sp"
android:gravity="center"/>

<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="1"
android:layout_column="1"
android:inputType="number"
android:ems="10"/>

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="2"
android:layout_column="0"
android:text="Dept"
android:textSize="20sp"
android:gravity="center"/>

<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="2"
android:layout_column="1"
android:spinnerMode="dropdown"/>

</GridLayout>

<Button
android:id="@+id/button"
android:layout_width="wrap_content"

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


10

android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_marginBottom="150dp"
android:text="Submit"/>

</RelativeLayout>

MainActivity.java:

package com.example.sreer.data;
importandroid.content.Intent;
import android.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.ArrayAdapter;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.Spinner;

public class MainActivity extends AppCompatActivity {

EditText e1,e2;
Button bt;
Spinner s;
String [] dept_array={"CSE","ECE","IT","Mech","Civil"};

String name,reg,dept;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1= (EditText) findViewById(R.id.editText);
e2= (EditText) findViewById(R.id.editText2);
bt= (Button) findViewById(R.id.button);
s= (Spinner) findViewById(R.id.spinner);

ArrayAdapter adapter= new ArrayAdapter(MainActivity.this,android.R.layout.simple_spinner_item,dept_array);


s.setAdapter(adapter);

bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

name=e1.getText().toString();
reg=e2.getText().toString();
dept=s.getSelectedItem().toString();
Intent i = new Intent(MainActivity.this,MainActivity2.class);

i.putExtra("name_key", name);
i.putExtra("reg_key",reg);
i.putExtra("dept_key", dept);
startActivity(i);
}
});
}

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


11

}
Activity-main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.admin.myapp.MainActivity2"
android:orientation="vertical"
android:gravity="center">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>

</LinearLayout>

Main2Activity.java:
package com.example.sreer.data;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity2 extends AppCompatActivity {


TextView t1,t2,t3;

String name,reg,dept;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

t1= (TextView) findViewById(R.id.textView1);


t2= (TextView) findViewById(R.id.textView2);

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


12

t3= (TextView) findViewById(R.id.textView3);


Intent i = getIntent();

name=i.getStringExtra("name_key");
reg=i.getStringExtra("reg_key");
dept=i.getStringExtra("dept_key");
t1.setText(name);
t2.setText(reg);
t3.setText(dept);
}}
OUTPUT:

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


13

RESULT:
Thus the application that uses Layout Managers and Event Listener has been developed and the output was verified.

3. Application that draws basic graphical primitives on the screen

AIM:
To develop an application that draws basic graphical primitives on the screen.
PROCEDURE:
1. Open Android Studio IDE.
2. Create the project Ex_No_7.
3. Go to package explorer in the left hand side. Select the project Ex_No_7.
4. Go to res folder and select layout. Double click the activity_main.xml file.
5. Now you can see the Graphical layout window.
6. Drag and drop only one ImageView
7. Again go to package explorer in the left hand side. Select the project Ex_No_6.
8. Go to src folder. Double click the MainActivity.java file.
9. In java file write the activities done by the application such as drawing the graphical primitives.
10. Finally run the android application.

PROGRAM
activity-main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageView" />
</RelativeLayout>

MainActivity.java:
package com.example.sreer.graph;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


14

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

Bitmap bg = Bitmap.createBitmap(720, 1280, Bitmap.Config.ARGB_8888);

ImageViewi = (ImageView) findViewById(R.id.imageView);


i.setBackgroundDrawable(new BitmapDrawable(bg));

Canvas canvas = new Canvas(bg);

Paint paint = new Paint();


paint.setColor(Color.BLUE);
paint.setTextSize(50);

canvas.drawText("Rectangle", 420, 150, paint);


canvas.drawRect(400, 200, 650, 700, paint);

canvas.drawText("Circle", 120, 150, paint);


canvas.drawCircle(200, 350, 150, paint);

canvas.drawText("Square", 120, 800, paint);


canvas.drawRect(50, 850, 350, 1150, paint);

canvas.drawText("Line", 480, 800, paint);


canvas.drawLine(520, 850, 520, 1150, paint);
}
}

OUTPUT:

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


15

4. Develop an application that makes use of databases

AIM:
To develop an application that makes use of database.
PROCEDURE:
1. Open Android Studio IDE.
2. Create the project Ex_No_4.
3. Go to package explorer in the left hand side. Select the project Ex_No_4.
4. Go to res folder and select layout. Double click the activity_main.xml file.
5. Now you can see the Graphical layout window.
6. Drag and drop the following components:
a. Three TextViews with texts as Reg.No., Name and Marks
b. Three EditTexts
c. Five Buttons with labeled asINSERT,DELETE
7. Again go to package explorer in the left hand side. Select the project Ex_No_4.
8. Go to src folder. Double click the MainActivity.java file.
9. In java file write the activities done by the application such as, actions of button.
10. Finally run the android application.

PROGRAM:

activity_main.xml:

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


<AbsoluteLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="50dp"
android:layout_y="20dp"
android:text="Student Details"
android:textSize="30sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="110dp"
android:text="Enter Rollno:"
android:textSize="20sp" />

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


16

<EditText
android:id="@+id/Rollno"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="100dp"
android:inputType="number"
android:textSize="20sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="160dp"
android:text="Enter Name:"
android:textSize="20sp" />

<EditText
android:id="@+id/Name"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="150dp"
android:inputType="text"
android:textSize="20sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="210dp"
android:text="Enter Marks:"
android:textSize="20sp" />

<EditText
android:id="@+id/Marks"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="200dp"
android:inputType="number"
android:textSize="20sp" />

<Button
android:id="@+id/Insert"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
android:layout_y="300dp"
android:text="Insert"
android:textSize="30dp" />

<Button
android:id="@+id/Delete"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="200dp"

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


17

android:layout_y="300dp"
android:text="Delete"
android:textSize="30dp" />

<Button
android:id="@+id/Update"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
android:layout_y="400dp"
android:text="Update"
android:textSize="30dp" />

<Button
android:id="@+id/View"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="200dp"
android:layout_y="400dp"
android:text="View"
android:textSize="30dp" />

<Button
android:id="@+id/ViewAll"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_x="100dp"
android:layout_y="500dp"
android:text="View All"
android:textSize="30dp" />

</AbsoluteLayout>

MainActivity.java:

package com.example.sreer.details;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener


{
EditTextRollno,Name,Marks;
Button Insert,Delete,Update,View,ViewAll;
SQLiteDatabasedb;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


18

Rollno=(EditText)findViewById(R.id.Rollno);
Name=(EditText)findViewById(R.id.Name);
Marks=(EditText)findViewById(R.id.Marks);
Insert=(Button)findViewById(R.id.Insert);
Delete=(Button)findViewById(R.id.Delete);
Update=(Button)findViewById(R.id.Update);
View=(Button)findViewById(R.id.View);
ViewAll=(Button)findViewById(R.id.ViewAll);

Insert.setOnClickListener(this);
Delete.setOnClickListener(this);
Update.setOnClickListener(this);
View.setOnClickListener(this);
ViewAll.setOnClickListener(this);

db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);


db.execSQL("CREATE TABLE IF NOT EXISTS student(rollnoVARCHAR,nameVARCHAR,marks
VARCHAR);");
}
public void onClick(View view)
{

if(view==Insert)
{

if(Rollno.getText().toString().trim().length()==0||
Name.getText().toString().trim().length()==0||
Marks.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter all values");
return;
}
db.execSQL("INSERT INTO student VALUES('"+Rollno.getText()+"','"+Name.getText()+
"','"+Marks.getText()+"');");
showMessage("Success", "Record added");
clearText();
}

if(view==Delete)
{

if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE rollno='"+Rollno.getText()+"'");
showMessage("Success", "Record Deleted");
}
else
{
showMessage("Error", "Invalid Rollno");

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


19

}
clearText();
}

if(view==Update)
{

if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'", null);
if(c.moveToFirst()) {
db.execSQL("UPDATE student SET name='" + Name.getText() + "',marks='" + Marks.getText() +
"' WHERE rollno='"+Rollno.getText()+"'");
showMessage("Success", "Record Modified");
}
else {
showMessage("Error", "Invalid Rollno");
}
clearText();
}

if(view==View)
{

if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'", null);
if(c.moveToFirst())
{
Name.setText(c.getString(1));
Marks.setText(c.getString(2));
}
else
{
showMessage("Error", "Invalid Rollno");
clearText();
}
}

if(view==ViewAll)
{
Cursor c=db.rawQuery("SELECT * FROM student", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Rollno: "+c.getString(0)+"\n");

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


20

buffer.append("Name: "+c.getString(1)+"\n");
buffer.append("Marks: "+c.getString(2)+"\n\n");
}
showMessage("Student Details", buffer.toString());
}
}
public void showMessage(String title,String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void clearText()
{
Rollno.setText("");
Name.setText("");
Marks.setText("");
Rollno.requestFocus();
}

OUTPUT:

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


21

RESULT:
Thus the application that makes use of database has been developed and the output was verified.

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

AIM:
To implement an application that creates an alert upon receiving a message.
PROCEDURE:
1. Open Android Studio IDE.
2. Create the project Ex_No_10.
3. Go to package explorer in the left hand side. Select the project Ex_No_10.
4. Go to res folder and select layout. Double click the activity_main.xml file.
5. Now you can see the Graphical layout window.
6. This application has no components, because this just generates a notification alone.
7. Again go to package explorer in the left hand side. Select the project Ex_No_10.
8. Go to src folder. Double click the MainActivity.java file.
9. In java file write the activities done by the application such as receiving a message and notify it.
10. Get the following permissions in AndroidManifest.xml file:
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
11. Add Receiver class as receiver in AndroidManifest.xml file.
12. Finally run the android application.

PROGRAM:
Activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical">

<TextView
android:layout_width="wrap_content"

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


22

android:layout_height="wrap_content"
android:text="Message"
android:textSize="30sp" />

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textSize="30sp" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:layout_gravity="center"
android:text="Notify"
android:textSize="30sp"/>
</LinearLayout>

MainActivity.java:
package com.example.alert;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity
{
Button notify;
EditText e;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notify= (Button) findViewById(R.id.button);
e= (EditText) findViewById(R.id.editText);
notify.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
PendingIntent pending = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
Notification noti = new Notification.Builder(MainActivity.this).setContentTitle("New
Message").setContentText(e.getText().toString()).setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pending).b
uild();
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
noti.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(0, noti);

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


23

}});}}
OUTPUT:

RESULT:
Thus the application that creates an alert upon receiving a message has been developed and the output was verified.

6. Develop a native application that uses GPS location information

AIM:
To develop a native application that uses GPS location information.
PROCEDURE:
1. Open Android Studio IDE.
2. Create the project Ex_No_5.
3. Go to package explorer in the left hand side. Select the project Ex_No_5.
4. Go to res folder and select layout. Double click the activity_main.xml file.
5. Now you can see the Graphical layout window.
6. Drag and drop the following components:
a. One TextView with text as Current Location
b. Two TextViews without any texts.
7. Again go to package explorer in the left hand side. Select the project Ex_No_5.
8. Go to src folder. Double click the MainActivity.java file.
9. In java file write the activities done by the application such as finding current location and print them.
10. Get the following permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
11. Finally run the android application.

PROGRAM:
activitymain.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="2.0">

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


24

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1.9">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textSize="12sp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="0.1">

<fragment
android:id="@+id/fragment1map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

</LinearLayout>
</LinearLayout>.

MainActivity.Java

package com.example.location;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import android.location.Location;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements OnMyLocationChangeListener
{
GoogleMap gmap;
@SuppressLint("NewApi") @Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MapFragment mp=(MapFragment)getFragmentManager().findFragmentById(R.id.fragment1map);
gmap=mp.getMap();

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


25

gmap.setMyLocationEnabled(true);
gmap.setOnMyLocationChangeListener(this);
}
@Override
public void onMyLocationChange(Location arg0)
{
// TODO Auto-generated method stub
TextView t=(TextView)findViewById(R.id.textView1);
double lat=arg0.getLatitude();
double lag=arg0.getLongitude();
t.setText("LATITUDE:"+lat+"LONGITUDE:"+lag);
gmap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lag))
.title("You Are Here !!!"));
}

OUTPUT:

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


26

RESULT:
Thus the application that uses GPS location information has been developed and the output was verified.

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


27

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

AIM:
To implement an application that writes data to the SD card.
PROCEDURE:
1. Open Android Studio IDE.
2. Create the project Ex_No_6.
3. Go to package explorer in the left hand side. Select the project Ex_No_6.
4. Go to res folder and select layout. Double click the activity_main.xml file.
5. Now you can see the Graphical layout window.
6. Drag and drop the following components:
a. Two EditTexts
b. Two Buttons with labeled as READ and SAVE
7. Again go to package explorer in the left hand side. Select the project Ex_No_6.
8. Go to src folder. Double click the MainActivity.java file.
9. In java file write the activities done by the application such as actions of buttons.
10. Get the following permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
11. Finally run the android application.

PROGRAM:

Activity_main.xml:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:orientation="vertical">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textSize="30dp" />

<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Write Data"
android:textSize="30dp" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Read data"
android:textSize="30dp" />
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


28

android:layout_margin="10dp"
android:text="Clear"
android:textSize="30dp" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.exno9" >
<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" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity></application></manifest>

MainActivity.java:
package com.example.sdcard;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
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;
public class MainActivity extends AppCompatActivity
{
EditText e1;
Button write,read,clear;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1= (EditText) findViewById(R.id.editText);
write= (Button) findViewById(R.id.button);
read= (Button) findViewById(R.id.button2);
clear= (Button) findViewById(R.id.button3);
write.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String message=e1.getText().toString();
try
{
File f=new File("/sdcard/myfile.txt");

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


29

f.createNewFile();
FileOutputStream fout=new FileOutputStream(f);
fout.write(message.getBytes());
fout.close();
Toast.makeText(getBaseContext(),"Data Written in SDCARD",Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}}});
read.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String message;
String buf = "";
try
{
File f = new File("/sdcard/myfile.txt");
FileInputStream fin = new FileInputStream(f);
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
while ((message = br.readLine()) != null)
{
buf += message;
}
e1.setText(buf);
br.close();
fin.close();
Toast.makeText(getBaseContext(),"Data Recived from SDCARD",Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
clear.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
e1.setText("");
}
});
}}
OUTPUT:

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


30

RESULT:
Thus the application that writes data to the SD card has been implemented and the output was verified.

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


31

8. Write a mobile application that creates alarm clock

AIM:
To implement an application that creates alarm clock.
PROCEDURE:
1. Open Android Studio IDE.
2. Create the project Ex_No_11.
3. Go to package explorer in the left hand side. Select the project Ex_No_11.
4. Go to res folder and select layout. Double click the activity_main.xml file.
5. Now you can see the Graphical layout window.
6. Drag and drop the following components:
a. DatePicker
b. TimePicker
c. Button with labeled as SET ALARM
7. Again go to package explorer in the left hand side. Select the project Ex_No_11.
8. Go to src folder. Double click the MainActivity.java file.
9. In java file write the activities done by the application such as notify the alarm.
10. Get the following permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.WAKE_LOCK"/>
11. Add Alarm class as a receiver in AndroidManifest.xml file.
12. Finally run the android application.

PROGRAM:

activity_main.xml:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="20dp"
android:checked="false"
android:onClick="OnToggleClicked" />
</LinearLayout>

AndroidManifest.xml:

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.exno11" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


32

android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver" >
</receiver>
</application>
</manifest>

MainActivity.java:

package com.example.alarm;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity
{
TimePicker alarmTimePicker;
PendingIntent pendingIntent;
AlarmManager alarmManager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmTimePicker = (TimePicker) findViewById(R.id.timePicker);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
}
public void OnToggleClicked(View view)
{
long time;
if (((ToggleButton) view).isChecked())
{
Toast.makeText(MainActivity.this, "ALARM ON", Toast.LENGTH_SHORT).show();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
Intent intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
time=(calendar.getTimeInMillis()-(calendar.getTimeInMillis()%60000));
if(System.currentTimeMillis()>time)
{
if (calendar.AM_PM == 0)
time = time + (1000*60*60*12);
else
time = time + (1000*60*60*24);
}

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


33

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 10000, pendingIntent);


}
else
{
alarmManager.cancel(pendingIntent);
Toast.makeText(MainActivity.this, "ALARM OFF", Toast.LENGTH_SHORT).show();
}
}
}

AlarmReceiver.java:

package com.example.alarm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Alarm! Wake up! Wake up!", Toast.LENGTH_LONG).show();
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null)
{
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
}
}

OUTPUT:

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


34

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


35

RESULT:
Thus the application that creates an alert upon receiving a message has been developed and the output was verified.

9. Develop an application that makes use of RSS Feed

AIM:
To develop an application that makes use of RSS Feed.
PROCEDURE:
1. Open Android Studio IDE.
2. Create the project Ex_No_8.
3. Go to package explorer in the left hand side. Select the project Ex_No_8.
4. Go to res folder and select layout. Double click the activity_main.xml file.
5. Now you can see the Graphical layout window.
6. Create the FrameLayout.
7. Create a new layout named as fragment_layout.xml which has following components:
a. ListView
b. ProgressBar
8. Create another one layout named as rss_item.xml which has only one TextView.
9. Again go to package explorer in the left hand side. Select the project Ex_No_7.
10. Go to src folder. Double click the MainActivity.java file.

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


36

11. In java file write the activities done by the application.


12. Create the following additional classes for this application:
a. Constants.java
b. PcWorldRssParser.java
c. RssAdapter.java
d. RssFragement.java
e. RssItem.java
f. RssService.java
13. Write appropriate actions for the created additional classes.
14. Get the following permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET" />
15. Finally run the android application.

PROGRAMS:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:id="@+id/fragment_container"
android:layout_height="fill_parent" />
fragement_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=http://schemas.android.com/apk/res/android
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
rss_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/itemTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18dp"
tools:ignore="SpUsage" />

MainActivity.java:
package com.example.ex_no_8;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends FragmentActivity {
@Override

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


37

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
addRssFragment();
}
}
private void addRssFragment() {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
RssFragment fragment = new RssFragment();
transaction.add(R.id.fragment_container, fragment);
transaction.commit();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("fragment_added", true);
}
}
Constants.java
package com.example.ex_no_8;
public class Constants {
public static final String TAG = "RssApp";
}
PcWorldRssParser.java
package com.example.ex_no_8;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;
public class PcWorldRssParser {
// We don't use namespaces
private final String ns = null;
public List<RssItem> parse(InputStream inputStream) throws XmlPullParserException,
IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(inputStream, null);
parser.nextTag();
return readFeed(parser);
} finally {
inputStream.close();
}
}
private List<RssItem> readFeed(XmlPullParser parser) throws XmlPullParserException,
IOException {
parser.require(XmlPullParser.START_TAG, null, "rss");
String title = null;
String link = null;
List<RssItem> items = new ArrayList<RssItem>();
while (parser.next() != XmlPullParser.END_DOCUMENT) {
if (parser.getEventType() != XmlPullParser.START_TAG) {

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


38

continue;
}
String name = parser.getName();
if (name.equals("title")) {
title = readTitle(parser);
} else if (name.equals("link")) {
link = readLink(parser);
}
if (title != null && link != null) {
RssItem item = new RssItem(title, link);
items.add(item);
title = null;
link = null;
}

}
return items;
}
private String readLink(XmlPullParser parser) throws XmlPullParserException, IOException
{
parser.require(XmlPullParser.START_TAG, ns, "link");
String link = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "link");
return link;
}
private String readTitle(XmlPullParser parser) throws XmlPullParserException,
IOException {
parser.require(XmlPullParser.START_TAG, ns, "title");
String title = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "title");
return title;
}
// For the tags title and link, extract their text values.
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException
{
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
}
}
RssAdapter.java
result = parser.getText();
parser.nextTag();
}
return result;
package com.example.ex_no_8;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class RssAdapter extends BaseAdapter {
private final List<RssItem> items;
private final Context context;
public RssAdapter(Context context, List<RssItem> items) {
this.items = items;
this.context = context;

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


39

}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int id) {
return id;
}
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(context, R.layout.rss_item, null);
holder = new ViewHolder();
holder.itemTitle = (TextView) convertView.findViewById(R.id.itemTitle);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.itemTitle.setText(items.get(position).getTitle());
return convertView;
}
static class ViewHolder {
TextView itemTitle;
}
RssFragement.java
package com.example.ex_no_8;
import java.util.List;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class RssFragment extends Fragment implements OnItemClickListener {
private ProgressBar progressBar;
private ListView listView;
private View view;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


40

}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_layout, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
startService();
} else {
ViewGroup parent = (ViewGroup) view.getParent();

parent.removeView(view);
}
return view;
}
private void startService() {
Intent intent = new Intent(getActivity(), RssService.class);
intent.putExtra(RssService.RECEIVER, resultReceiver);
getActivity().startService(intent);
}
private final ResultReceiver resultReceiver = new ResultReceiver(new Handler()) {
@SuppressWarnings("unchecked")
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
progressBar.setVisibility(View.GONE);
List<RssItem> items = (List<RssItem>)
resultData.getSerializable(RssService.ITEMS);
if (items != null) {
RssAdapter adapter = new RssAdapter(getActivity(), items);
listView.setAdapter(adapter);
} else {
Toast.makeText(getActivity(), "An error occured while downloading
the rss feed.",
Toast.LENGTH_LONG).show();
}
}
}
};
};
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RssItem.java
RssAdapter adapter = (RssAdapter) parent.getAdapter();
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getLink());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
package com.example.ex_no_8;
public class RssItem {
}
private final String title;
private final String link;
public RssItem(String title, String link) {
this.title = title;
this.link = link;

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


41

}
public String getTitle() {
return title;
}
public String getLink() {
return link;
}
RssService.java
package com.example.ex_no_8;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.List;
import org.xmlpull.v1.XmlPullParserException;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
public class RssService extends IntentService {
}
private static final String RSS_LINK = "http://www.pcworld.com/index.rss";
public static final String ITEMS = "items";
public static final String RECEIVER = "receiver";
public RssService() {
super("RssService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try {
PcWorldRssParser parser = new PcWorldRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
} catch (XmlPullParserException e) {
Log.w(e.getMessage(), e);
} catch (IOException e) {
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
public InputStream getInputStream(String link) {
}
}
try {
URL url = new URL(link);
return url.openConnection().getInputStream();
} catch (IOException e) {
Log.w(Constants.TAG, "Exception while retrieving the input stream", e);
return null;

OUTPUT:

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


42

RESULT:
Thus the application that makes use of RSS Feed has been developed and the output was verified.

10. Develop a native calculator application

AIM:
To develop a native calculator application.
PROCEDURE:

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


43

1. Open Android Studio IDE.


2. Create the project Ex_No_3.
3. Go to package explorer in the left hand side. Select the project Ex_No_3.
4. Go to res folder and select layout. Double click the activity_main.xml file.
5. Now you can see the Graphical layout window.
6. Drag and drop the following components:
a. Two EditTexts with hints Enter the first number and Enter the second number
b. Four Buttons with labeled as ADD, SUB, MUL and DIV
7. Again go to package explorer in the left hand side. Select the project Ex_No_3.
8. Go to src folder. Double click the MainActivity.java file.
9. In java file write the activities done by the application such as, actions of button.
10. Finally run the android application.

PROGRAM:

activity_main.xml:

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp">

<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp">

<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="numberDecimal"
android:textSize="20sp" />

<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="numberDecimal"
android:textSize="20sp" />
</LinearLayout>

<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp">

<Button
android:id="@+id/Add"
android:layout_width="match_parent"

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


44

android:layout_height="wrap_content"
android:layout_weight="1"
android:text="+"
android:textSize="30sp"/>

<Button
android:id="@+id/Sub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="-"
android:textSize="30sp"/>

<Button
android:id="@+id/Mul"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="*"
android:textSize="30sp"/>

<Button
android:id="@+id/Div"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="/"
android:textSize="30sp"/>

</LinearLayout>

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Answer is"
android:textSize="30sp"
android:gravity="center"/>

</LinearLayout>

MainActivity.java:

package com.example.sreer.calc;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements OnClickListener


{
EditText Num1;

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


45

EditText Num2;
Button Add;
Button Sub;
Button Mul;
Button Div;
TextView Result;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Num1 = (EditText) findViewById(R.id.editText1);


Num2 = (EditText) findViewById(R.id.editText2);
Add = (Button) findViewById(R.id.Add);
Sub = (Button) findViewById(R.id.Sub);
Mul = (Button) findViewById(R.id.Mul);
Div = (Button) findViewById(R.id.Div);
Result = (TextView) findViewById(R.id.textView);

Add.setOnClickListener(this);
Sub.setOnClickListener(this);
Mul.setOnClickListener(this);
Div.setOnClickListener(this);
}

@Override
public void onClick (View v)
{

float num1 = 0;
float num2 = 0;
float result = 0;
String oper = "";

if (TextUtils.isEmpty(Num1.getText().toString()) || TextUtils.isEmpty(Num2.getText().toString()))
return;
num1 = Float.parseFloat(Num1.getText().toString());
num2 = Float.parseFloat(Num2.getText().toString());

switch (v.getId())
{
case R.id.Add:
oper = "+";
result = num1 + num2;
break;
case R.id.Sub:
oper = "-";
result = num1 - num2;
break;
case R.id.Mul:
oper = "*";
result = num1 * num2;
break;
case R.id.Div:
oper = "/";

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


46

result = num1 / num2;


break;
default:
break;
}

Result.setText(num1 + " " + oper + " " + num2 + " = " + result);
}
}

OUTPUT:

RESULT:
Thus the native calculator application has been developed and the output was verified.

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


47

11. Implement an application that uses Multi-threading


Aim:
To Implement an application that uses Multi-threading
Procedure:
1. Open Android Studio.
2. Create the project Ex_No_11.
3. Go to package explorer in the left hand side. Select the project Ex_No_11.
4. Go to res folder and select layout. Double click the activity_main.xml file.
5. Now you can see the Graphical layout window.
6. Drag and drop only one ImageView
7. Again go to package explorer in the left hand side. Select the project Ex_No_11.
8. Go to src folder. Double click the MainActivity.java file.
9. In java file write the activities done by the application such as drawing the graphical primitives.
10. Finally run the android application.

Program:

Activity main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_margin="50dp"
        android:layout_gravity="center" />
 
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_gravity="center"
        android:text="Load Image 1" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_gravity="center"
        android:text="Load image 2" />
 
</LinearLayout>

Main activity.java
package com.example.exno7;
 

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


48

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity
{
    ImageView img;
    Button bt1,bt2;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        bt1 = (Button)findViewById(R.id.button);
        bt2= (Button) findViewById(R.id.button2);
        img = (ImageView)findViewById(R.id.imageView);
 
        bt1.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                new Thread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        img.post(new Runnable()
                        {
                            @Override
                            public void run()
                            {
                                img.setImageResource(R.drawable.india1);
                            }
                        });
                    }
                }).start();
            }
        });
 
        bt2.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                new Thread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        img.post(new Runnable()
                        {
                            @Override
                            public void run()
                            {

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


49

                                img.setImageResource(R.drawable.india2);
                            }
                        });
                    }
                }).start();
            }
        });
    }
}

RESULT:
Thus the native calculator application has been developed and the output was verified.

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


50

12. Develop a mobile application to send an email.


Aim:
To develop a mobile application to send an email.

Procedure:

1. You will use Android studio to create an Android application and name it as Ex_12 under a package
com.example.Ex_12.
2. Modify src/MainActivity.java file and add required code to take care of sending email.
3. Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I'm adding a simple
button to launch Email Client.
4. Modify res/values/strings.xml to define required constant values
5. Modify AndroidManifest.xml as shown below
6. Run the application to launch Android emulator and verify the result of the changes done in the application.

Program:

MainActivity.java.

package com.example.tutorialspoint;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button startBtn = (Button) findViewById(R.id.sendEmail);


startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendEmail();
}
});
}

protected void sendEmail() {


Log.i("Send email", "");
String[] TO = {""};
String[] CC = {""};

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


51

Intent emailIntent = new Intent(Intent.ACTION_SEND);

emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");

try {
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
finish();
Log.i("Finished sending email...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There is no email client installed.", Toast.LENGTH_SHORT).show();
}
}
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sending Mail Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

<Button
android:id="@+id/sendEmail"

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


52

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/compose_email"/>

</LinearLayout>

strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Tutorialspoint</string>
<string name="compose_email">Compose Email</string>
</resources>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.Tutorialspoint" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.tutorialspoint.MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Output:

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


53

Result:
Thus the project for creating e-mail was executed successfully.

13. Live Wallpaper Android Project


Project Abstract:
As the name indicate Live Wallpaper has been developed to change the background image and color settings of
your android smart phone. There are several types of images and online gadgets which has been integrated within
this live wallpaper android project. Among the many features which are available under this live wallpaper android
project, you will also able to see some exciting features like greetings on special day, automatic wallpaper settings
on the basis of particular celebrations, weather forecasting when your smart phone is online etc.
However, users will get an options to select the wallpaper based on their choice. Apart from these, you can
use its customized settings to browse your own wallpaper and set under this wallpaper gadgets. We have also tried
to give a three dimension look to every images which are available under the live wallpaper project.
Proposed System:
Under this new live wallpaper android project, the first thing which you will get, it’s free and can be used with any
android version. Its automatic adjustment will help to retain the quality of picture over your smart phone. There are
different set of wallpapers which the users can select and set as per their requirements. Sometimes when we don’t
have led light in our smart phone, we need to use in some situations. Keeping in mind such idea, has been
implemented using this unique live wallpaper project. We have
made available the white wallpaper which will act as led light on your smart phone, by which you can see the
objects even in dark environment. Its smart pattern will able to recognized the special day by reading data from
calendar and display the particular occasional wallpaper on particular day with greeting messages.
Benefits:

 Automatic adjustment of images over your smart phone screen.


 3D images to give smart phone screen a digital look.

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


54

 Automatic recognition of special occasions and based on it, displaying special day wallpapers.
 To make your smart screen work similar to flashlight, white wallpapers has been provided.
 Some techniques of Picasa browsing has been implemented to scan images on your system and set as per
your need through its customized settings.
Code:

Create a new project called de.vogella.android.wallpaper. Do not create an activity.

Create the /res/xml folder and create the mywallpaper.xml file.

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


<wallpaper
xmlns:android="http://schemas.android.com/apk/res/android"
android:thumbnail="@drawable/icon"
android:description="@string/wallpaper_description"
android:settingsActivity="de.vogella.android.wallpaper.MyPreferencesActivity"/>

This file contains a description of your wallpaper and a preview graphic. You can also enter a link to an activity
which allow to configure the wallpaper. This resource file will be linked to from the AndroidManifest.xml. You
could also include the "android:thumbnail attribute" which would point to a drawable which gives a smaller image
of the running wallpaper.

Change your AndroidManifest.xml to the following to define your MyWallpaperService service. Also define the
uses-feature.

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.wallpaper"
android:versionCode="1"
android:versionName="1.0" >

<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<service
android:name="MyWallpaperService"
android:enabled="true"
android:label="Wallpaper Example "
android:permission="android.permission.BIND_WALLPAPER" >
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" >
</action>
</intent-filter>

<meta-data
android:name="android.service.wallpaper"
android:resource="@xml/mywallpaper" >
</meta-data>
</service>

<activity
android:name=".MyPreferencesActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@android:style/Theme.Light.WallpaperSettings" >

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


55

</activity>
<activity
android:name=".SetWallpaperActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.Light.WallpaperSettings" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


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

<uses-sdk android:minSdkVersion="10" />

<uses-feature
android:name="android.software.live_wallpaper"
android:required="true" >
</uses-feature>

</manifest>

We create the MyPoint class to save the elements we have drawn.

package de.vogella.android.wallpaper;

public class MyPoint {


String text;
private int x;
private int y;

public MyPoint(String text, int x, int y) {


this.text = text;
this.x = x;
this.y = y;
}
}

Create a new activity. Create the prefs.xml preference file in the res/xml folder.

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


<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference android:key="touch"
android:title="Enable Touch"></CheckBoxPreference>
<EditTextPreference android:key="numberOfCircles"
android:title="Number of Circles"></EditTextPreference>
</PreferenceScreen>

Create a new activity called MyPreferencesActivity and the following class.

package de.vogella.android.wallpaper;

import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


56

import android.widget.Toast;

public class MyPreferencesActivity extends PreferenceActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);

// add a validator to the "numberofCircles" preference so that it only


// accepts numbers
Preference circlePreference = getPreferenceScreen().findPreference(
"numberOfCircles");

// add the validator


circlePreference.setOnPreferenceChangeListener(numberCheckListener);
}

/**
* Checks that a preference is a valid numerical value
*/
Preference.OnPreferenceChangeListener numberCheckListener = new OnPreferenceChangeListener() {

@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// check that the string is an integer
if (newValue != null && newValue.toString().length() > 0
&& newValue.toString().matches("\\d*")) {
return true;
}
// If now create a message to the user
Toast.makeText(MyPreferencesActivity.this, "Invalid Input",
Toast.LENGTH_SHORT).show();
return false;
}
};

Create the following coding for the Wallpaper service.

package de.vogella.android.wallpaper;

import java.util.ArrayList;
import java.util.List;

import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.service.wallpaper.WallpaperService;
import android.view.MotionEvent;
import android.view.SurfaceHolder;

public class MyWallpaperService extends WallpaperService {

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


57

@Override
public Engine onCreateEngine() {
return new MyWallpaperEngine();
}

private class MyWallpaperEngine extends Engine {


private final Handler handler = new Handler();
private final Runnable drawRunner = new Runnable() {
@Override
public void run() {
draw();
}

};
private List<MyPoint> circles;
private Paint paint = new Paint();
private int width;
int height;
private boolean visible = true;
private int maxNumber;
private boolean touchEnabled;

public MyWallpaperEngine() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(MyWallpaperService.this);
maxNumber = Integer
.valueOf(prefs.getString("numberOfCircles", "4"));
touchEnabled = prefs.getBoolean("touch", false);
circles = new ArrayList<MyPoint>();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(10f);
handler.post(drawRunner);
}

@Override
public void onVisibilityChanged(boolean visible) {
this.visible = visible;
if (visible) {
handler.post(drawRunner);
} else {
handler.removeCallbacks(drawRunner);
}
}

}
@Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
super.onSurfaceDestroyed(holder);
this.visible = false;
handler.removeCallbacks(drawRunner);
}

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


58

@Override
public void onSurfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
this.width = width;
this.height = height;
super.onSurfaceChanged(holder, format, width, height);
}

@Override
public void onTouchEvent(MotionEvent event) {
if (touchEnabled) {

float x = event.getX();
float y = event.getY();
SurfaceHolder holder = getSurfaceHolder();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
canvas.drawColor(Color.BLACK);
circles.clear();
circles.add(new MyPoint(
String.valueOf(circles.size() + 1), x, y));
drawCircles(canvas, circles);

}
} finally {
if (canvas != null)
holder.unlockCanvasAndPost(canvas);
}
super.onTouchEvent(event);
}
}

private void draw() {


SurfaceHolder holder = getSurfaceHolder();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
if (circles.size() >= maxNumber) {
circles.clear();
}
int x = (int) (width * Math.random());
int y = (int) (height * Math.random());
circles.add(new MyPoint(String.valueOf(circles.size() + 1),
x, y));
drawCircles(canvas, circles);
}
} finally {
if (canvas != null)
holder.unlockCanvasAndPost(canvas);
}
handler.removeCallbacks(drawRunner);
if (visible) {
handler.postDelayed(drawRunner, 5000);
}

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


59

// Surface view requires that all elements are drawn completely


private void drawCircles(Canvas canvas, List<MyPoint> circles) {
canvas.drawColor(Color.BLACK);
for (MyPoint point : circles) {
canvas.drawCircle(point.x, point.y, 20.0f, paint);
}
}
}

Create the following Activity which should use a layout with one Button included. This Button should use the
onClick property to point to the onClick method.

package de.vogella.android.wallpaper;

import android.app.Activity;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class SetWallpaperActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

public void onClick(View view) {


Intent intent = new Intent(
WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
new ComponentName(this, MyWallpaperService.class));
startActivity(intent);
}
}

If you start your application your application should allow to set the wallpaper. Your background should look
similar to the following screenshot. If you have Touch enabled via the preferences you can click on the screen to
remove the existing circles, also via the settings you can define the number of circles which should be displayed.

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College


60

19CS414 MOBILE APPLICATION DEVELOPMENT LAB MANUAL Saveetha Engineering College

You might also like