SlideShare una empresa de Scribd logo
1 de 38
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
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
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
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)
Create an Android Project in Eclipse
   File → New → Project

   Select “Android Project”

   Fill in Project details...
Directory
                     name




      Android
      version




                       Java package
Name that appears
   on device




    Class to
 automatically
     create
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
Source
                    code


                Auto-generated
                     code




    String
  constants

                          UI
                        layout



Configuration
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   }
main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout
 3   xmlns:android="http://schemas.android.com/apk/res/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>
AndroidManifest.xml
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest
 3    xmlns:android="http://schemas.android.com/apk/res/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              <action
13               android:name="android.intent.action.MAIN" />
14              <category
15
android:name="android.intent.category.LAUNCHER"/>
16           </intent-filter>
17        </activity>
18    </application>
19 </manifest>
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”
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>
•   Step 3
       Import Classes and Interfaces
    import   android.app.Activity;
    import   android.app.PendingIntent;
    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;
 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();
         }
   });
 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" />
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;
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;                          }
}                                        }
 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];
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();
       }
    }
}
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;
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();
}
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();
   }
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;
     }
}
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());
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>
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" />
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;

}
@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;
  }
@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;
    }

}
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;
@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();
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", new
DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
           dialog.cancel();
          }
        }); adb.show();
}
});
  }
}
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();
          }
        }
 });
Final AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/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>
<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>

Más contenido relacionado

Destacado

Destacado (8)

Algo complexity
Algo complexityAlgo complexity
Algo complexity
 
Mobile computing
Mobile computingMobile computing
Mobile computing
 
Android OS Presentation
Android OS PresentationAndroid OS Presentation
Android OS Presentation
 
My presentation on Android in my college
My presentation on Android in my collegeMy presentation on Android in my college
My presentation on Android in my college
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Mobile Computing
Mobile ComputingMobile Computing
Mobile Computing
 
Android seminar-presentation
Android seminar-presentationAndroid seminar-presentation
Android seminar-presentation
 
Android ppt
Android ppt Android ppt
Android ppt
 

Similar a Android

android level 3
android level 3android level 3
android level 3DevMix
 
Android Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAndroid Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAhsanul Karim
 
Exercises broadcast receiver,incoming phone call
Exercises broadcast receiver,incoming phone callExercises broadcast receiver,incoming phone call
Exercises broadcast receiver,incoming phone callmaamir farooq
 
Android Tutorials : Basic widgets
Android Tutorials : Basic widgetsAndroid Tutorials : Basic widgets
Android Tutorials : Basic widgetsPrajyot Mainkar
 
Android Development for Beginners with Sample Project - Day 1
Android Development for Beginners with Sample Project - Day 1Android Development for Beginners with Sample Project - Day 1
Android Development for Beginners with Sample Project - Day 1Joemarie Amparo
 
Android Development Made Easy - With Sample Project
Android Development Made Easy - With Sample ProjectAndroid Development Made Easy - With Sample Project
Android Development Made Easy - With Sample ProjectJoemarie Amparo
 
21 android2 updated
21 android2 updated21 android2 updated
21 android2 updatedGhanaGTUG
 
Android training in mumbai
Android training in mumbaiAndroid training in mumbai
Android training in mumbaiCIBIL
 
Android Workshop
Android WorkshopAndroid Workshop
Android WorkshopJunda Ong
 
Developing for android wear
Developing for android wearDeveloping for android wear
Developing for android wearThomas Oldervoll
 
Android Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_androidAndroid Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_androidDenis Minja
 
ハンズオン資料 電話を作ろう(v1.6用)
ハンズオン資料 電話を作ろう(v1.6用)ハンズオン資料 電話を作ろう(v1.6用)
ハンズオン資料 電話を作ろう(v1.6用)Kenji Sakashita
 
ハンズオン資料 電話を作ろう(v2.x用)
ハンズオン資料 電話を作ろう(v2.x用)ハンズオン資料 電話を作ろう(v2.x用)
ハンズオン資料 電話を作ろう(v2.x用)Kenji Sakashita
 
Android app development basics
Android app development basicsAndroid app development basics
Android app development basicsAnton Narusberg
 

Similar a Android (20)

Android introduction by vidya topa
Android introduction by vidya topaAndroid introduction by vidya topa
Android introduction by vidya topa
 
android level 3
android level 3android level 3
android level 3
 
Android Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAndroid Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver Tutorial
 
Exercises broadcast receiver,incoming phone call
Exercises broadcast receiver,incoming phone callExercises broadcast receiver,incoming phone call
Exercises broadcast receiver,incoming phone call
 
Android Tutorials : Basic widgets
Android Tutorials : Basic widgetsAndroid Tutorials : Basic widgets
Android Tutorials : Basic widgets
 
Broadcast Receiver
Broadcast ReceiverBroadcast Receiver
Broadcast Receiver
 
Android
AndroidAndroid
Android
 
Android Development for Beginners with Sample Project - Day 1
Android Development for Beginners with Sample Project - Day 1Android Development for Beginners with Sample Project - Day 1
Android Development for Beginners with Sample Project - Day 1
 
Android App Dev Manual-1.doc
Android App Dev Manual-1.docAndroid App Dev Manual-1.doc
Android App Dev Manual-1.doc
 
Android Development Made Easy - With Sample Project
Android Development Made Easy - With Sample ProjectAndroid Development Made Easy - With Sample Project
Android Development Made Easy - With Sample Project
 
21 android2 updated
21 android2 updated21 android2 updated
21 android2 updated
 
Android training in mumbai
Android training in mumbaiAndroid training in mumbai
Android training in mumbai
 
Android For All The Things
Android For All The ThingsAndroid For All The Things
Android For All The Things
 
Android - Anatomy of android elements & layouts
Android - Anatomy of android elements & layoutsAndroid - Anatomy of android elements & layouts
Android - Anatomy of android elements & layouts
 
Android Workshop
Android WorkshopAndroid Workshop
Android Workshop
 
Developing for android wear
Developing for android wearDeveloping for android wear
Developing for android wear
 
Android Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_androidAndroid Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_android
 
ハンズオン資料 電話を作ろう(v1.6用)
ハンズオン資料 電話を作ろう(v1.6用)ハンズオン資料 電話を作ろう(v1.6用)
ハンズオン資料 電話を作ろう(v1.6用)
 
ハンズオン資料 電話を作ろう(v2.x用)
ハンズオン資料 電話を作ろう(v2.x用)ハンズオン資料 電話を作ろう(v2.x用)
ハンズオン資料 電話を作ろう(v2.x用)
 
Android app development basics
Android app development basicsAndroid app development basics
Android app development basics
 

Android

  • 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
  • 8.
  • 9. Source code Auto-generated code String constants UI layout Configuration
  • 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 }
  • 11. main.xml 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout 3 xmlns:android="http://schemas.android.com/apk/res/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>
  • 12. AndroidManifest.xml 1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest 3 xmlns:android="http://schemas.android.com/apk/res/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 <action 13 android:name="android.intent.action.MAIN" /> 14 <category 15 android:name="android.intent.category.LAUNCHER"/> 16 </intent-filter> 17 </activity> 18 </application> 19 </manifest>
  • 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”
  • 14. 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>
  • 15. Step 3 Import Classes and Interfaces import android.app.Activity; import android.app.PendingIntent; 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;
  • 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();
  • 35. 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", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); adb.show(); } }); } }
  • 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(); } } });
  • 37. Final AndroidManifest.xml file <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/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>
  • 38. <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>