Sie sind auf Seite 1von 51

Jerusalem College of Engineering Department of Information Technology

IT6611 Mobile Application Development


Laboratory Record Notebook

Name : __________________________________________
Reg No: __________________________________________
Year : __________________________________________
Branch: __________________________________________

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 1


CONTENTS

Exp Page
Date Name of the Experiment Mark Signature
No No.

2a

2b

10

11
Jerusalem College of Engineering Department of Information Technology

Ex No: 1 GUI components, Fonts and Colors


Date

AIM:
To develop an application using gui components, Fonts and Colors.

ALGORITHM:
1. Create three activities for registration and welcome page.
2. Add the necessary gui components like textbox, label, radio button, checkbox to the
layout page.
3. Set the properties of the gui components by right->click edit text, edit id or modify the
layout.xml file
4. Write the implementation code in java file. Include the necessary packages. Write the
code inside create() function.
5. Get the values entered in the textbox, radio buttons and checkboxes using
findViewById().
6. Invoke putExtra(keyvalue,classname) method to send data from one page to other.
7. Invoke getStringExtra(keyvalue) method to receive data from one page.
8. Write button onclick listener to perform operation when button is clicked

PROGRAM:
MainActivity.java
package com.example.ex1_gui_color_font;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class MainActivity extends Activity {

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

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 3


Jerusalem College of Engineering Department of Information Technology

public void show()


{
Button b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Intent o=getIntent();
EditText t=(EditText)findViewById(R.id.Name);
String data=t.getText().toString();
RadioButton r1;
RadioGroup rg=(RadioGroup)findViewById(R.id.rg1);
CheckBox c1,c2,c3;
c1=(CheckBox)findViewById(R.id.check_d);
c2=(CheckBox)findViewById(R.id.check_r);
c3=(CheckBox)findViewById(R.id.check_p);
final StringBuilder sb=new StringBuilder();
if(c1.isChecked())
{
sb.append("Dancing");
}
if(c2.isChecked())
{
sb.append("Reading");
}
if(c3.isChecked())
{
sb.append("Playing");
}
int rgid=rg.getCheckedRadioButtonId();
r1=(RadioButton)findViewById(rgid);
String rdata=r1.getText().toString();
Intent o1=new Intent(getApplicationContext(),display_rec.class);
o1.putExtra("dis_name",data);
o1.putExtra("dis_gender", rdata.toString());
o1.putExtra("dis_hobb",sb.toString());
startActivity(o1);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 4
Jerusalem College of Engineering Department of Information Technology

}
display_rec.java

package com.example.ex1_gui_color_font;

import android.R.color;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;

public class display_rec extends Activity {


//Context c;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_rec);
Intent o=getIntent();
String data=o.getStringExtra("dis_name");
String data1=o.getStringExtra("dis_gender");
String data2=o.getStringExtra("dis_hobb");
TextView t1=(TextView)findViewById(R.id.d_name);
TextView t2=(TextView)findViewById(R.id.d_gender);
TextView t3=(TextView)findViewById(R.id.d_hobb);
t1.setTextSize(40);
t1.setText("Welcome"+" "+data);
t2.setTextColor(Color.RED);
t2.setTypeface(null, Typeface.BOLD);
t2.setText(data1);
t3.setBackgroundColor(Color.YELLOW);
t3.setText("Your Hobbies are "+data2);

}
}

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 5


Jerusalem College of Engineering Department of Information Technology

Output:
MainAvtivity

display_rec

Result:

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 6


Jerusalem College of Engineering Department of Information Technology

Ex No: 2a Relative Layout


Date

AIM:
To develop an application that displays child views in relative positions.

ALGORITHM:
1. Layout changes the style of the design page.
2. The position of each view can be specified as relative to sibling elements (such as to the
left-of or below another view) or in positions relative to the parent RelativeLayout area
(such as aligned to the bottom, left or center).
3. RelativeLayout lets child views specify their position relative to the parent view or to
each other.
4. The value for each layout property is either a Boolean to enable a layout position relative
to the parent RelativeLayout or an ID that references another view in the layout against
which the view should be positioned.
PROGRAM:

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

<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>

</EditText>

<Spinner
android:id="@+id/dates"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/times" />

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 7


Jerusalem College of Engineering Department of Information Technology

<Spinner
android:id="@id/times"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_alignParentRight="true" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/dates"
android:layout_below="@id/times"
android:layout_marginRight="44dp"
android:layout_marginTop="34dp"
android:text="Submit" />

</RelativeLayout>

Output:

Result:

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 8


Jerusalem College of Engineering Department of Information Technology

Ex No: 2b Event Listener


Date

AIM:
To develop an application that displays child views in relative positions.

ALGORITHM:
1. Events are a useful way to collect data about a user's interaction with interactive
components of Applications.
2. Design a xml with a textview and two buttons, ok and cancel.
3. Declare instance variables for our objects outside onCreate method.
4. The objects are initialized using findViewById method.
5. Create oclBtnOk object which implements View.OnClickListener interface. This object
has onClick method
6. The onClick method will be invoked when the button is pressed.
7. The TextView content change when a button is clicked.

PROGRAM:
package com.example.ex3_eventlistener;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {


TextView t1;
Button ob1;
Button cb2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.dis_txt);
ob1=(Button)findViewById(R.id.ok_button);
cb2=(Button)findViewById(R.id.cancel_button);
ob1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 9
Jerusalem College of Engineering Department of Information Technology

// TODO Auto-generated method stub


t1.setText("Ok Button Clicked");
}
});
cb2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
t1.setText("Cancel Button Clicked");
}
});
}
}
Output:

Result:

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 10


Jerusalem College of Engineering Department of Information Technology

Ex No: 3 Calculator Application


Date

AIM:
To develop a native calculator application to perform operations such as addition, subtraction,
multiplication and division.

ALGORITHM:
1. In the layout create a textbox and buttons for numbers and operators.
2. For each buttons get their id using findviewbyid() and setonclicklistener.
3. Create onclick() method to get the value of each button.
4. Using switch statement compares the ids of the button.
5. Once matched invoke compute function to perform various operations.
PROGRAM:
package com.example.calculator_two;
import android.app.Activity;
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
{
Button nine,eig,sev,six,fiv,four,thr,two,one,zero,dot,plus,mins,div,mul,eq,cl;
EditText et;
String s = "0";
int result = 0;
char lO = ' ';
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nine=(Button)findViewById(R.id.b9);
eig=(Button)findViewById(R.id.b8);
sev=(Button)findViewById(R.id.b7);
six=(Button)findViewById(R.id.b6);
fiv=(Button)findViewById(R.id.b5);
four=(Button)findViewById(R.id.b4);
thr=(Button)findViewById(R.id.b3);
two=(Button)findViewById(R.id.b2);
one=(Button)findViewById(R.id.b1);
zero=(Button)findViewById(R.id.b0);
dot=(Button)findViewById(R.id.bd);
plus=(Button)findViewById(R.id.bpl);
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 11
Jerusalem College of Engineering Department of Information Technology

mins=(Button)findViewById(R.id.bmin);
div=(Button)findViewById(R.id.bdiv);
mul=(Button)findViewById(R.id.bmul);
eq=(Button)findViewById(R.id.beq);
cl=(Button)findViewById(R.id.bcl);
et=(EditText)findViewById(R.id.tv);
nine.setOnClickListener(this);
eig.setOnClickListener(this);
sev.setOnClickListener(this);
six.setOnClickListener(this);
fiv.setOnClickListener(this);
four.setOnClickListener(this);
thr.setOnClickListener(this);
two.setOnClickListener(this);
one.setOnClickListener(this);
dot.setOnClickListener(this);
plus.setOnClickListener(this);
mins.setOnClickListener(this);
div.setOnClickListener(this);
mul.setOnClickListener(this);
eq.setOnClickListener(this);
cl.setOnClickListener(this);
et.setOnClickListener(this);
zero.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.b0:
case R.id.b1:
case R.id.b2:
case R.id.b3:
case R.id.b4:
case R.id.b5:
case R.id.b6:
case R.id.b7:
case R.id.b8:
case R.id.b9:
String inDigit = ((Button) v).getText().toString();
if (s.equals("0"))
{
s= inDigit;
}
else {
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 12
Jerusalem College of Engineering Department of Information Technology

s+=inDigit;
}
et.setText(s);
if(lO == '=')
{
result=0;
lO =' ';
}
break;
case R.id.bpl:
compute();
lO = '+';
break;
case R.id.bmin:
compute();
lO = '-';
break;
case R.id.bdiv:
compute();
lO = '/';
break;
case R.id.bmul:
compute();
lO = '*';
break;
case R.id.beq:
compute();
lO = '=';
break;
case R.id.bcl:
result = 0;
s = "0";
lO = ' ';
et.setText("0");
break;
}
}
private void compute()
{
// TODO Auto-generated method stub
int inNum = Integer.parseInt(s);
s = "0";
if (lO == ' ')
{
result = inNum;
}
else if (lO == '+'){
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 13
Jerusalem College of Engineering Department of Information Technology

result += inNum;
}
else if (lO == '-')
{
result -= inNum;
}
else if (lO == '*')
{
result *= inNum;
}
else if (lO == '/')
{
result /= inNum;
}
else if (lO == '=')
{
}
et.setText(String.valueOf(result));
}
}
OUTPUT :

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 14


Jerusalem College of Engineering Department of Information Technology

RESULT:

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 15


Jerusalem College of Engineering Department of Information Technology

Ex No: 4 Graphical Primitives


Date

AIM:
To develop an application that draws basic graphical primitives like circle, rectangle, line and
oval on the screen.
ALGORITHM:
1. Import graphics package to use the classes.
2. Create onDraw() method .
3. Create object for paint class, set style for the window and color.
4. Set the color for the circle. Then to draw circle invoke drawcircle() method.
5. Using canvas object invoke drawLine(),drawRectF(),drawOval() method to draw line,
Rectangle and oval shape.
6. Use rotate function to rotate the text.
PROGRAM:
package com.example.user.graphicsdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;
public class MainActivity extends Activity {
DemoView demoview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
demoview = new DemoView(this);
setContentView(demoview);
}
private class DemoView extends View{
public DemoView(Context context){
super(context);
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// custom drawing code here
Paint ob = new Paint();
ob.setStyle(Paint.Style.FILL);
// make the entire canvas white
ob.setColor(Color.WHITE);
canvas.drawPaint(ob);
// draw blue circle with anti aliasing turned off
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 16
Jerusalem College of Engineering Department of Information Technology

ob.setAntiAlias(false);
ob.setColor(Color.GREEN);
canvas.drawCircle(20, 20, 20, ob);
// draw green circle with anti aliasing turned on
ob.setAntiAlias(true);
ob.setColor(Color.CYAN);
canvas.drawCircle(60, 20, 30, ob);
ob.setColor(Color.BLUE);
RectF oval3 = new RectF(250, 50, 350, 400);
canvas.drawOval(oval3, ob);
// draw red rectangle with anti aliasing turned off
ob.setAntiAlias(false);
ob.setColor(Color.MAGENTA);
canvas.drawRect(100, 5, 200, 40, ob);
ob.setAntiAlias(false);
ob.setColor(Color.RED);
canvas.drawLine(250, 50, 350, 400,ob);
// draw the rotated text
canvas.rotate(-45);
ob.setStyle(Paint.Style.FILL);
canvas.drawText("FDP Training MAD", 50, 180, ob);
//undo the rotate
canvas.restore();
}}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.main, menu);
return true;
}}

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 17


Jerusalem College of Engineering Department of Information Technology

OUTPUT:

RESULT:

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 18


Jerusalem College of Engineering Department of Information Technology

Ex No: 5 Database Application


Date
AIM:
To develop an application that make use of database to perform insertion, deletion, update and
selection of data from the database.
ALGORITHM:
1. Create a DBAdapter class. Declare the fields of the database-id,name,email id.
2. Assign id as the primary key.
3. Create a table and assign into string DATABASE_CREATE.
4. Create object for DatabaseHelper ,SQLiteDatabase classes.
5. Create oncreate() methods to start the SQLdatabase.
6. Create onupgrade()method to upgrade the version of database from older to new.
7. Define the operations for insert, select, selectall, delete, update inside DBAdapter class.
8. In the design page add three textfields and five buttons.
9. In mainactivity java file invokes the queries inside onclicklistener of each button.
PROGRAM:
DBAdapter java class
package com.example.sqlapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "MyDB";
private static final String DATABASE_TABLE = "contacts";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table contacts (_id integer primary key , " + "name text not null, email text not
null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 19
Jerusalem College of Engineering Department of Information Technology

DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "+
newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a contact into the database---
public long insertContact(long id,String name, String email)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ROWID, id);
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_EMAIL, email);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular contact---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
} //---retrieves all the contacts---
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 20
Jerusalem College of Engineering Department of Information Technology

public Cursor getAllContacts()


{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME,KEY_EMAIL},null, null, null, null, null);
}
//---retrieves a particular contact---
public Cursor getContact(long rowId) throws SQLException
{
Cursor mCursor =db.query(true, DATABASE_TABLE, new String[]
{KEY_ROWID,KEY_NAME, KEY_EMAIL}, KEY_ROWID + "=" + rowId, null,null, null,
null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a contact---
public boolean updateContact(long rowId, String name, String email)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_EMAIL, email);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
Main activity java
package com.example.sqlapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.database.Cursor;
import android.view.*;
import android.widget.*;;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button b1=(Button) findViewById(R.id.insert);
final Button b2=(Button) findViewById(R.id.selectall);
final Button b3=(Button) findViewById(R.id.select);
final Button b4=(Button) findViewById(R.id.update);
final Button b5=(Button) findViewById(R.id.delete);
final EditText et1=(EditText)findViewById(R.id.id);
final EditText et2=(EditText)findViewById(R.id.name);
final EditText et3=(EditText)findViewById(R.id.email);
final DBAdapter db = new DBAdapter(MainActivity.this); //---Insert Contact---
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 21
Jerusalem College of Engineering Department of Information Technology

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.open();
db.insertContact(Integer.parseInt(et1.getText().toString()),et2.getText().toString(),
et3.getText().toString());
db.close();
Toast.makeText(getBaseContext(), "Inserted",Toast.LENGTH_SHORT).show();
}
});
//---Select All contacts---
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.open();
Cursor c = db.getAllContacts();
if (c.moveToFirst())
{
do {
DisplayContact(c);
} while (c.moveToNext());
}
db.close();
}
private void DisplayContact(Cursor c)
{
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),"id: " + c.getString(0) +"Name: " + c.getString(1) +
"\n" + "Email: " + c.getString(2),Toast.LENGTH_LONG).show();
}
});
//---Select a contact---
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.open();
Cursor c = db.getContact(Integer.parseInt (et1.getText().toString()));
if (c.moveToFirst())
DisplayContact(c);
else
Toast.makeText(getBaseContext(), "No contact
found",Toast.LENGTH_LONG).show();
db.close();
} private void DisplayContact(Cursor c) {
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 22
Jerusalem College of Engineering Department of Information Technology

// TODO Auto-generated method stub


Toast.makeText(getBaseContext(),"id: " + c.getString(0) + "\n" +"Name: " +
c.getString(1) + "\n" + "Email: " + c.getString(2),Toast.LENGTH_LONG).show();
}
}) ;
//---updates a contact---
b4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.open();
if(db.updateContact(Integer.parseInt(et1.getText().toString()),et2.getText().toString(),
et3.getText().toString()))
Toast.makeText(getBaseContext(),"Update successful.",
Toast.LENGTH_LONG).show();
else
Toast.makeText(getBaseContext(), "Update
failed.",Toast.LENGTH_LONG).show();
db.close();
}
});
//---delete a contact---
b5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.open();
db.deleteContact(Integer.parseInt(et1.getText().toString()));
Toast.makeText(getBaseContext(), "Deleted",Toast.LENGTH_SHORT).show();
db.close();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 23


Jerusalem College of Engineering Department of Information Technology

OUTPUT:
Insert

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 24


Jerusalem College of Engineering Department of Information Technology

Display

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 25


Jerusalem College of Engineering Department of Information Technology

Update

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 26


Jerusalem College of Engineering Department of Information Technology

Delete

RESULT:

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 27


Jerusalem College of Engineering Department of Information Technology

Ex No: 6 RSS Feed


Date
AIM:
To develop an application that makes use of RSS feed.
ALGORITHM:
1. In activity_main layout add three textboxes and two buttons.
2. In activity_second layout add webview.
3. In the manifest file add permission to access the internet
4. <uses-permission android:name="android.permission.INTERNET"/>
5. Create HandleXML java file.
(i)Create object for XmlPullParserFactory.
(ii)Define methods for getTitle(), getdescription(),and getlink() which returns title,
description and link.
(iii)Define parseXMLAndStoreIt method.using parser object get the name of the
document. Check whether it is START_TAG, TEXT, END_TAG.
6. Define method fetchXML(),which fetches the title, description ,link from the given URL
(i)Create a thread.
(ii)Inside run() method establish URL connection.
(iii)Start the thread.
7. In main activity java file write the code for button action listener. Create object for
HandlXML class and pass the URL string. Also create object for fetchXML().After
fetching the page move to another activity
8. Create second activity. Create object for webview, then load the URL.
PROGRAM:
HandleXML.java
package com.example.rssfeed;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.util.Log;
public class HandleXML
{
private String title = "title";
private String link = "link";
private String description = "description";
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;
public HandleXML(String url)
{
this.urlString = url;
}
public String getTitle()
{
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 28
Jerusalem College of Engineering Department of Information Technology

return title;
}
public String getLink()
{
return link;
}
public String getDescription()
{
return description;
}
public void parseXMLAndStoreIt(XmlPullParser myParser)
{
int event;
String text=null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT)
{
String name=myParser.getName();
switch (event)
{
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if(name.equals("title"))
{
title = text;
}
else if(name.equals("link"))
{
link = text;
}
else if(name.equals("description"))
{
description = text;
}
else
{
}
break;
}
event = myParser.next();
}
parsingComplete = false; }
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 29
Jerusalem College of Engineering Department of Information Technology

catch (Exception e)
{
e.printStackTrace();
}
}
public void fetchXML()
{
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
}
catch (Exception e)
{
} }
});
thread.start();
}
}
MainActivity.java
package com.example.rssfeed;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 30
Jerusalem College of Engineering Department of Information Technology

import android.widget.EditText;
import android.widget.TextView;
import java.util.Set;
public class MainActivity extends Activity
{
EditText title,link,description;
Button b1,b2;
private String finalUrl="http://tutorialspoint.com/android/sampleXML.xml";
private HandleXML obj;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = (EditText) findViewById(R.id.editText);
link = (EditText) findViewById(R.id.editText2);
description = (EditText) findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
obj = new HandleXML(finalUrl);
obj.fetchXML();
while(obj.parsingComplete);
title.setText(obj.getTitle());
link.setText(obj.getLink());
description.setText(obj.getDescription());
}
});
b2.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View v)
{
Intent in=new Intent(MainActivity.this,Second.class);
startActivity(in);
}
});
}
@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;
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 31
Jerusalem College of Engineering Department of Information Technology

}
@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);
}
}
Second.java
package com.example.rssfeed;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class Second extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
WebView w1=(WebView)findViewById(R.id.webView);
w1.loadUrl("http://tutorialspoint.com/android/sampleXML.xml");
}
}
Manifest file
<uses-permission android:name="android.permission.INTERNET"/>

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 32


Jerusalem College of Engineering Department of Information Technology

OUTPUT:

RESULT:

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 33


Jerusalem College of Engineering Department of Information Technology

Ex No: 7 Multithreading
Date
AIM:
To implement an application that implements Multithreading.
ALGORITHM:
1. In the design layout add two textviews and a button.
2. In mainactivity java file, create object for handler class.
3. using handler object invoke postDelayedfuntion.
4. Create object for runnable class.
5. Inside run method call a userdefined function. This function has an explicit intent to
invoke a webpage.
6. Oncreate thread starts followed by runnable thread.
PROGRAM:
package com.example.multithread;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Handler hand = new Handler();
Button clickme;
TextView timer;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = (TextView) findViewById(R.id.timer);
clickme = (Button) findViewById(R.id.clickme);
hand.postDelayed(run, 1000);
}
Runnable run = new Runnable()
{
@Override
public void run()
{
updateTime();
}
};
public void updateTime()
{
timer.setText("" + (Integer.parseInt(timer.getText().toString()) - 1));

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 34


Jerusalem College of Engineering Department of Information Technology

if (Integer.parseInt(timer.getText().toString()) == 0)
{
Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse("http://google.com/"));
startActivity(browserIntent);
}
else {
hand.postDelayed(run, 1000);
} } }
OUTPUT:

RESULT:

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 35


Jerusalem College of Engineering Department of Information Technology

Ex No: 8 GPS Location Information


Date
AIM:
To develop a native application that uses GPS location information.
ALGORITHM:
1. In the design layout add button.
2. In manifest file include permission to access internet and location
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
3. Create a java class GPSTracker.
4. Create object for locationmanager.
5. Getting GPS status using getSystemService() and network status using
isProviderEnabled().
6. First get location from Network Provider using
getLastKnownLocation(LocationManager.NETWORK_PROVIDER) get the latitude and
longitude.
7. if GPS Enabled get lat/long using GPS Services get the latitude and longitude using
getLastKnownLocation(LocationManager.GPS_PROVIDER);
8. In main activity create object for GPSTracker class and display the latitude and longitude
using Toast message.
PROGRAM:
Manifestfile
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
GPSTracker.class
package com.example.gpsdemo;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener
{
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 36
Jerusalem College of Engineering Department of Information Technology

boolean canGetLocation = false;


Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.mContext = context;
getLocation();
}
public Location getLocation() {
try
{
locationManager = (LocationManager)
mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
// no network provider is enabled
} else
{
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
{
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 37
Jerusalem College of Engineering Department of Information Technology

}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e)
{
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS()
{
if(locationManager != null)
{
locationManager.removeUpdates(GPSTracker.this);
} }
/**
* Function to get latitude
* */
public double getLatitude()
{
if(location != null)
{
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 38
Jerusalem College of Engineering Department of Information Technology

latitude = location.getLatitude();
} return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude()
{
if(location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation()
{
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 39
Jerusalem College of Engineering Department of Information Technology

} @Override
public void onLocationChanged(Location location) {
} @Override
public void onProviderDisabled(String provider) {
} @Override
public void onProviderEnabled(String provider) {
} @Override
public void onStatusChanged(String provider, int status, Bundle extras) {
} @Override
public IBinder onBind(Intent arg0) {
return null;
}}
MainActivity.java
package com.example.gpsdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.location.*;
import android.content.Context;
import android.widget.*;
public class MainActivity extends Activity
{
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.button1);
btnShowLocation.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View arg0)
{
// create class object
gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude +
"\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else
{
// can't get location
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 40
Jerusalem College of Engineering Department of Information Technology

// GPS or Network is not enabled


// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
} } });
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}}

OUTPUT

RESULT:
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 41
Jerusalem College of Engineering Department of Information Technology

Ex No: 9 Application to write data to SD card


Date

AIM:
To implement an application that writes data to the SD card.
ALGORITHM:
1. In the design layout add two text fields and two buttons.
2. In manifest file include permission to access sdcard
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
3. To write data ,create a new file using createNewFile();
4. Pass new file object to FileOutputStream.
5. Then using OutputStreamWriter object append data into the file .
6. To read data from the file
7. Pass file object to FileInputStream
8. Then using BufferedReader object and readline() method, read the content from the file.
PROGRAM:
Manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Activity java
package com.example.user.sdcardapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.*;
import android.view.*;
import android.widget.*;
public class MainActivityextends AppCompatActivity {
Button save,read;
EditTextt1,t2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(EditText)findViewById(R.id.editText);
t2=(EditText)findViewById(R.id.editText2);
save=(Button)findViewById(R.id.button);
read=(Button)findViewById(R.id.button2);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String fname=t1.getText().toString();
String data=t2.getText().toString();
FileOutputStream fos;
try
{
File myfile=new File("/sdcard/"+fname);
myfile.createNewFile();
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 42
Jerusalem College of Engineering Department of Information Technology

FileOutputStream fout=new FileOutputStream(myfile);


OutputStreamWriter myoutwriter=new OutputStreamWriter(fout);
myoutwriter.append(data);
myoutwriter.close();
fout.close();

Toast.makeText(getApplicationContext(),fname+"saved",Toast.LENGTH_LONG).show();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String filename = t1.getText().toString();
StringBuffersbuffer = new StringBuffer();
String adatarow = "";
String aBuffer = "";
try {
File myfile = new File("/sdcard/" + filename);
FileInputStream in = new FileInputStream(myfile);
BufferedReadermyreader = new BufferedReader(new InputStreamReader(in));
while ((adatarow = myreader.readLine()) != null) {
aBuffer += adatarow + "\n";
}
myreader.close();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), aBuffer, Toast.LENGTH_LONG).show();
}
});
}
}

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 43


Jerusalem College of Engineering Department of Information Technology

OUTPUT:

RESULT:

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 44


Jerusalem College of Engineering Department of Information Technology

Ex No: 10 Message Alert Application


Date

AIM:
To implement an application that creates an alert upon receiving a message.
ALGORITHM:
1. Create a textview to display a message in design layout.
2. In manifest file include the following permissions
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-
permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
3. Create IncomingSms.java file
4. Make the class to extend BroadcastReciever.
5. Get the object of SmsManager.
6. Retrieve the phone number of the sender and content of the message
7. Broadcast it to the receiver and display it as toast message.
PROGRAM:
Manifest file
?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidexample.broadcastreceiver"
android:versionCode="1"
android:versionName="1.0" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.androidexample.broadcastreceiver.BroadcastNewSms"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.androidexample.broadcastreceiver.IncomingSms">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 45
Jerusalem College of Engineering Department of Information Technology

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


<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
</manifest>
IncomingSms.java
package com.androidexample.broadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.*;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class IncomingSms extends BroadcastReceiver{
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[])
pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " +
message, duration);
toast.show();
} } // bundle is null
} catch (Exception e){
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}}}

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 46


Jerusalem College of Engineering Department of Information Technology

OUTPUT:

RESULT:

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 47


Jerusalem College of Engineering Department of Information Technology

Ex No: 11 Alarm Clock Application


Date

AIM:
To write a mobile application that creates alarm clock
ALGORITHM:
1. In Activity_alarmreciver.XML create a button to stop the alarm
2. In Activity_main.xml create a textview to display hello message
3. In AlarmReceiverActivity.java Create an object for MediaPlayer class. Inside onCreate
method, write onTouchListener for stop button, which invokes stop() method to stop the
alarm
4. Create another function playSound(),in which alarm tone is set and media player is
started.
5. In MainActivity.java Create an offset from the current time in which the alarm will go
off.
6. Create a new PendingIntent and add it to the AlarmManager.
PROGRAM:
AlarmReceiverActivity.java
package com.example.alarm_final;
import java.io.IOException;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
//import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class AlarmReceiverActivity extends Activity
{
private MediaPlayer mMediaPlayer;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.alarm);
Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
stopAlarm.setOnTouchListener(new OnTouchListener()
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 48
Jerusalem College of Engineering Department of Information Technology

{
public boolean onTouch(View arg0, MotionEvent arg1)
{
mMediaPlayer.stop();
finish();
return false;
}
});
playSound(this, getAlarmUri());
}
private void playSound(Context context, Uri alert)
{
mMediaPlayer = new MediaPlayer();
try
{
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0)
{
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
} }
catch (IOException e)
{
System.out.println("OOPS");
} }
//Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri()
{
Uri alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null)
{
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null)
{
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}}

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 49


Jerusalem College of Engineering Department of Information Technology

MainActivity.java
package com.example.alarm_final;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
//import android.view.Menu;
import android.view.Window;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//Create an offset from the current time in which the alarm will go off.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 5);
//Create a new PendingIntent and add it to the AlarmManager
Intent intent = new Intent(this, AlarmReceiverActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am =
(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
pendingIntent);
}
}
Layout
Activity_alarmreciver
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center" >
<Button
android:id="@+id/stopAlarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="stop_alarm" />
</RelativeLayout>
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 50
Jerusalem College of Engineering Department of Information Technology

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<TextView
android:id="@+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="alarm_hello" />
</RelativeLayout>

RESULT:

IT6611 MOBILE APPLICATION DEVELOPMENT LAB 51

Das könnte Ihnen auch gefallen