Android
Upcoming SlideShare
Loading in...5
×
 

Android

on

  • 1,387 views

 

Statistics

Views

Total Views
1,387
Views on SlideShare
1,387
Embed Views
0

Actions

Likes
0
Downloads
136
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Android Android Presentation Transcript

    • 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
    • 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
    • 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
    • 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 packageName 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 dont need to restart the emulator when you have a new version of your application
    • Source code Auto-generated code String constants UI layoutConfiguration
    • 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 }
    • 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 <action13 android:name="android.intent.action.MAIN" />14 <category15android: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 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(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 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];
    • 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 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;
    • 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 databaseDBManager 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 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" />
    • 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;}
    • @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 classimport 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;
    • @Overridepublic 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() { @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();
    • 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(); } }); adb.show();}}); }}
    • 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(); } } });
    • 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>