1. What is Android?
An open source Linux-based operating system
intended for mobile computing platforms
It is not a device or product
Application Building Blocks
• Activity
• Intents
• Broadcast Receivers
• Service
• ContentProvider
2. Activities
Typically correspond to one UI screen
Intents
Think of Intents as a verb and object, a description
of what you want done E.g. VIEW, CALL, PLAY etc..
Broadcast Receivers
Receive and react to broadcast announcements
3. Services
Faceless components that run in the background
E.g. music player, network download etc…
ContentProviders
Enables sharing of data across applications
E.g. address book, photo gallery
4. Set Up Your Android Environment
http://developer.android.com/sdk
Install Eclipse
Install Android SDK (Android libraries)
Install ADT plugin (Android development
tools)
Create AVD (Android virtual device)
5. Create an Android Project in Eclipse
File → New → Project
Select “Android Project”
Fill in Project details...
6. Directory
name
Android
version
Java package
Name that appears
on device
Class to
automatically
create
7. Run the Android Application
Run → Run (or click the “Run” button)
Select “Android Application”
The emulator may take a few minutes to
start, so be patient!
You don't need to restart the emulator when
you have a new version of your application
10. HelloAndroid.java
1 public class HelloAndroid extends Activity {
2 /** Called when the activity is first created. */
3 @Override
4 public void onCreate(Bundle savedInstanceState)
5 {
6 super.onCreate(savedInstanceState);
7 setContentView(R.layout.main);
8 }
9 }
13. SMS Sending
•Step 1 Add permissions to AndroidManifest.xml
<uses-permission android:name="android.permission.SEND_SMS " />
<uses-permission android:name=" android.permission.RECEIVE_SMS “/>
•Step 2
•In the main.xml, add Text view to
display “Number“ and "Message“
•EditText with id txtPhoneNo and
txtMessage
•Add the button ID "Send SMS“ and
“Inbox”
16. Step 4
Write the SendSms class
public class SendSms extends Activity {
Button btnSendSMS,btnInbox;
EditText txtPhoneNo;
EditText txtMessage;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
btnInbox = (Button) findViewById(R.id.btnInbox);
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtMessage = (EditText) findViewById(R.id.txtMessage);
btnSendSMS.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString();
Input from the user
if (phoneNo.length()>0 && message.length()>0) (i.e., the phone no, text
sendSMS(phoneNo, message);
else message and sendSMS
Toast.makeText(getBaseContext(), is implemented).
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
});
17. Step 5
◦ To send an SMS message, you use the SmsManager class. And to
instantiate this class call getDefault() static method.
private void sendSMS(String phoneNumber, String message) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, nu
ll);
}
In the AndroidManifest.xml file add <activity android:name=".SendSms" />
18. Receiving SMS
•Step 1
In the AndroidManifest.xml file add the <receiver> element so that incoming SMS
messages can be intercepted by the SmsReceiver class.
<receiver android:name=".SmsReceiver">
<intent-filter>
<action android:name=
"android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
•Step 2
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
19. public String getSmsNumber() {
Write the Sms class return smsNumber;
}
public class Sms { public void setSmsNumber(String smsNumber) {
this.smsNumber = smsNumber;
private int smsId; }
private String smsNumber; public String getSmsMessage() {
private String smsMessage; return smsMessage;
private long smsTime; }
public void setSmsMessage(String smsMessage) {
public Sms(int smsid, String message, this.smsMessage = smsMessage;
String number,long time) }
{ public String getSmsTime() {
smsId=smsid; DateFormat formatter = new
smsNumber = number; SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
smsMessage = message; Calendar calendar = Calendar.getInstance();
smsTime = time; calendar.setTimeInMillis(smsTime);
} String time = formatter.format(calendar.getTime());
public Sms() return time;
{ }
} public long getLongSmsTime() {
public int getSmsID() { return smsTime;
return smsId; }
} public void setSmsTime(long smsTime) {
public void setSmsID(int smsId) { this.smsTime = smsTime;
this.smsId = smsId; }
} }
20. Step 3
Write the Broadcast Receiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
In the SmsReceiver
import android.widget.Toast; class, extend the
BroadcastReceiver class
public class SmsReceiver extends BroadcastReceiver { and override the
onReceive() method. The
message is attached to the
@Override Intent
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
Sms s = new Sms();
if (bundle != null){
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
21. The messages are stored
for (int i=0; i<msgs.length; i++) { in a object array PDU
format. To extract each
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); message, you use the
static createFromPdu()
s.setSmsNumber(msgs[i].getOriginatingAddress());
method from the
s.setSmsTime(msgs[i].getTimestampMillis()); SmsMessage class. The
s.setSmsMessage( msgs[i].getMessageBody().toString()); SMS message is then
} displayed using the Toast
class
Toast.makeText(context, "From: "+s.getSmsNumber()+"n"+ "Message:
"+s.getSmsMessage()+"n"+ "Time: "+s.getSmsTime(), Toast.LENGTH_SHORT).show();
}
}
}
22.
23. Storing SMS
Write the DB Manager Class
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;
public class DBManager {
SQLiteDatabase db;
24. private void open_Database() {
try{
db= SQLiteDatabase.openDatabase( "/data/data/com.arsalan/smsDB",
null,SQLiteDatabase.CREATE_IF_NECESSARY);
db.execSQL("Create table IF NOT EXISTS smstable" + To open or create a
"( smsid integer primary key autoincrement," + database in your local
Android’s data space and
“ time long," + create table with name
" message Text," + “smstable” having columns
" phonenumber text)"); to store time message and
} phone number.
catch(SQLiteException e) {
Log.d("SQLDatabase", e.getMessage());
}
}
private void close_Database() {
db.close();
}
25. public void insert_into_Database(String messagebody , String phoneNo,long time )
{
open_Database();
String sql="Insert into smstable (time,message,phonenumber) values('" + time+"','" +
messagebody+"','"+phoneNo + " ')"; Inserting values in the
db.execSQL(sql); database.
Close_Database();
}
public void deleteSms(int smsId)
{ Deleting Sms from the
database.
open_Database();
db.execSQL("DELETE FROM smstable WHERE smsid='"+smsId+"'");
close_Database();
}
26. public List getAllSms() {
Cursor c1 = null;
List smsList = new ArrayList();
Sms s;
open_Database();
try
{
c1 = db.rawQuery("SELECT * FROM smstable", null);
}
catch(Exception ex)
{
Log.d("error",ex.getMessage());
}
while (c1.moveToNext()) To get the list of all the sms
stored in the database.
{
s=new Sms(c1.getInt(0),c1.getString(2),c1.getString(3),c1.getLong(1));
smsList.add(s);
}
c1.close();
close_Database();
return smsList;
}
}
27. Add the following code to the SmsReceiver class
to store the received message into the database
DBManager db = new DBManager();
db.insert_into_Database( s.getSmsMessage(),
s.getSmsNumber(),s.getLongSmsTime());
28. Create a new layout “sms_list” to show the list of all the sms in inbox
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/listSms"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#FFCC00"
android:dividerHeight="4px"/>
/>
</LinearLayout>
29. Create a layout “sms_row” which will be the template for
each individual row in the ListView
Add the following code to the xml file
<TextView <TextView
android:id="@+id/SmsNumber" android:id="@+id/SmsTime"
android:layout_marginTop="1dip" android:layout_marginTop="1dip"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:textSize="20sp" android:textSize="20sp"
android:textColor="#FFFF00" android:textColor="#83c8f9"
android:textStyle="bold" /> android:textStyle="bold" />
<TextView
android:id="@+id/SmsMessage"
android:layout_marginTop="1dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="#83c8f9"
android:textStyle="bold" />
30. Write the SmsAdapter Class which acts as a bridge between
Lists (UI Component) and the datasource that fill data into
UI Component.
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SmsAdapter extends BaseAdapter {
private Context mContext;
private List<Sms> mListSms;
public SmsAdapter(Context context, List<Sms> list) {
mContext = context;
mListSms = list;
}
31. @Override
public int getCount() {
return mListSms.size(); Methods to
getCount, Remove
} items, etc from the
@Override list
public Object getItem(int pos) {
return mListSms.get(pos);
}
public Object removeItem(int pos) {
return mListSms.remove(pos);
}
@Override
public long getItemId(int pos) {
return pos;
}
32. @Override
public View getView(int pos, View convertView, ViewGroup parent) {
Sms entry = mListSms.get(pos);
To populate the
if(convertView == null) { view with the data
LayoutInflater inflater = LayoutInflater.from(mContext); from the database.
convertView = inflater.inflate(R.layout.sms_row, null);
}
TextView tvNumber = (TextView)convertView.findViewById(R.id.SmsNumber);
tvNumber.setText("Number: "+entry.getSmsNumber());
TextView tvMessage = (TextView)convertView.findViewById(R.id.SmsMessage);
tvMessage.setText("Message: "+entry.getSmsMessage());
TextView tvTime = (TextView)convertView.findViewById(R.id.SmsTime);
tvTime.setText("Time: "+entry.getSmsTime());
return convertView;
}
}
33. Write the SmsList class
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
In the AndroidManifest.xml file add <activity android:name=".SmsList" />
public class SmsList extends Activity {
private ListView lvSms;
DBManager db = new DBManager();
SmsAdapter adapter;
Sms s;
34. @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sms_list); Passing the list of
lvSms = (ListView)findViewById(R.id.listSms);
messages to the
adapter = new SmsAdapter(this, db.getAllSms());
lvSms.setAdapter(adapter);
adapter
lvSms.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
s = (Sms) parent.getItemAtPosition(position);
String from = "From: "+s.getSmsNumber() ;
String message = "Message: "+s.getSmsMessage();
String time = "Time: "+s.getSmsTime();
36. Add the following code to the sendSMS class to call the new
SmsList activity to show the list of all the messages store in
the database when the inbox button is clicked.
btnInbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent();
i.setClassName("com.arsalan", "com.arsalan.SmsList");
try {
startActivity(i);
} catch (Exception ex) {
ex.getMessage();
}
}
});