Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 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. 2. ActivitiesTypically correspond to one UI screenIntentsThink of Intents as a verb and object, a descriptionof what you want done E.g. VIEW, CALL, PLAY etc..Broadcast ReceiversReceive and react to broadcast announcements
  3. 3. ServicesFaceless components that run in the background E.g. music player, network download etc…ContentProvidersEnables sharing of data across applications E.g. address book, photo gallery
  4. 4. Set Up Your Android Environment Install Eclipse Install Android SDK (Android libraries) Install ADT plugin (Android development tools) Create AVD (Android virtual device)
  5. 5. Create an Android Project in Eclipse File → New → Project Select “Android Project” Fill in Project details...
  6. 6. Directory name Android version Java packageName that appears on device Class to automatically create
  7. 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 dont need to restart the emulator when you have a new version of your application
  8. 8. Source code Auto-generated code String constants UI layoutConfiguration
  9. 9. HelloAndroid.java1 public class HelloAndroid extends Activity {2 /** Called when the activity is first created. */3 @Override4 public void onCreate(Bundle savedInstanceState)5 {6 super.onCreate(savedInstanceState);7 setContentView(R.layout.main);8 }9 }
  10. 10. main.xml 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout 3 xmlns:android="" 4 android:orientation="vertical" 5 android:layout_width="fill_parent" 6 android:layout_height="fill_parent" 7 > 8 <TextView 9 android:layout_width="fill_parent"10 android:layout_height="wrap_content"11 android:text="@string/hello "12 />13 </LinearLayout>
  11. 11. AndroidManifest.xml 1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest 3 xmlns:android="" 4 package="edu.upenn.cis542" 5 android:versionCode="1" 6 android:versionName="1.0"> 7 <application android:icon="@drawable/icon" 8 android:label="@string/app_name"> 9 <activity android:name=".HelloAndroid"10 android:label="@string/app_name">11 <intent-filter>12 <action13 android:name="android.intent.action.MAIN" />14 <category15android:name="android.intent.category.LAUNCHER"/>16 </intent-filter>17 </activity>18 </application>19 </manifest>
  12. 12. 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”
  13. 13. Add following code to main .xml<TextView <EditText android:text=" Enter the phone number : " android:layout_width="fill_parent" android:id="@+id/ txtPhoneNo " android:id="@+id/editText2" android:layout_width="wrap_content" android:inputType="textMultiLine" android:typeface="monospace" android:layout_height="wrap_content" android:layout_height="wrap_content"> android:layout_weight="0.30"> </TextView> </EditText> <EditText <Button android:layout_height="wrap_content" android:id="@+id/btnSendSMS" android:id="@+id/editText1" android:text=" Send SMS " android:layout_width="fill_parent"> android:layout_height="wrap_content" <requestFocus></requestFocus> android:layout_width="fill_parent"></EditText> </Button> <TextView <Button android:text=" Message " android:text="Inbox" android:id="@+id/ txtMessage " android:id="@+id/btnInbox" android:typeface="monospace" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_width="match_parent"> android:layout_height="wrap_content"> </Button> </TextView>
  14. 14. • Step 3 Import Classes and Interfaces import; import; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;
  15. 15.  Step 4 Write the SendSms classpublic 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(; btnInbox = (Button) findViewById(; txtPhoneNo = (EditText) findViewById(; txtMessage = (EditText) findViewById(; 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(); } });
  16. 16.  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" />
  17. 17. 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;
  18. 18. 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; }} }
  19. 19.  Step 3 Write the Broadcast Receiverimport android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.telephony.SmsMessage; In the SmsReceiverimport android.widget.Toast; class, extend the BroadcastReceiver classpublic 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];
  20. 20. 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(); } }}
  21. 21. Storing SMSWrite 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;
  22. 22. 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();}
  23. 23. 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(); }
  24. 24. 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; }}
  25. 25. Add the following code to the SmsReceiver class to store the received message into the databaseDBManager db = new DBManager(); db.insert_into_Database( s.getSmsMessage(),s.getSmsNumber(),s.getLongSmsTime());
  26. 26. 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="" 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>
  27. 27. Create a layout “sms_row” which will be the template foreach 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" />
  28. 28. Write the SmsAdapter Class which acts as a bridge betweenLists (UI Component) and the datasource that fill data intoUI 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;}
  29. 29. @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; }
  30. 30. @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(; tvNumber.setText("Number: "+entry.getSmsNumber()); TextView tvMessage = (TextView)convertView.findViewById(; tvMessage.setText("Message: "+entry.getSmsMessage()); TextView tvTime = (TextView)convertView.findViewById(; tvTime.setText("Time: "+entry.getSmsTime()); return convertView; }}
  31. 31. Write the SmsList classimport;import;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;
  32. 32. @Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sms_list); Passing the list of lvSms = (ListView)findViewById(; messages to the adapter = new SmsAdapter(this, db.getAllSms()); lvSms.setAdapter(adapter); adapter lvSms.setOnItemClickListener(new OnItemClickListener() { @Overridepublic 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();
  33. 33. AlertDialog.Builder adb=new AlertDialog.Builder(SmsList.this);adb.setTitle(from+"n"+time);adb.setMessage(message);adb.setPositiveButton("Delete", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { db.deleteSms(s.getSmsID()); adapter.removeItem(position); To show the dialog adapter.notifyDataSetChanged(); box and delete the } message from the }); database. adb.setNegativeButton("Cancel", newDialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } });;}}); }}
  34. 34. Add the following code to the sendSMS class to call the newSmsList activity to show the list of all the messages store inthe 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(); } } });
  35. 35. Final AndroidManifest.xml file<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="" package="com.arsalan" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.SEND_SMS"> </uses-permission> <uses-permission android:name="android.permission.RECEIVE_SMS"> </uses-permission> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".SendSms" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
  36. 36. <activity android:name=".SmsList" /> <receiver android:name=".SmsReceiver"> <intent-filter android:priority="2147483647"> <action android:name= "android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver> </application></manifest>