A Guide to Mobile and Web Technology(LAMP)

The following code shows how to register and event and observe changes made to the sms folder for send sms.
Most of the people states that the code may not work in future versions. Currently it works pretty with 2.1 and 2.2 and 2.3

public class SmsObserver extends ContentObserver {
	
    private Context mContext;
    
    private String contactId = "", contactName = "";
    private String smsBodyStr = "", phoneNoStr = "";
    private long smsDatTime = System.currentTimeMillis();
    static final Uri SMS_STATUS_URI = Uri.parse("content://sms");
    
	public SmsObserver(Handler handler, Context ctx) {
		super(handler);
		mContext = ctx;
	}

	public boolean deliverSelfNotifications() {
		return true;
	}

	public void onChange(boolean selfChange) {
		try{
			Log.e("Info","Notification on SMS observer");
			Cursor sms_sent_cursor = mContext.getContentResolver().query(SMS_STATUS_URI, null, null, null, null);
			if (sms_sent_cursor != null) {
				if (sms_sent_cursor.moveToFirst()) {
					String protocol = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("protocol"));
					Log.e("Info","protocol : " + protocol);
					//for send  protocol is null
					if(protocol == null){
						/*
						String[] colNames = sms_sent_cursor.getColumnNames();		        		
						if(colNames != null){
							for(int k=0; k<colNames.length; k++){
								Log.e("Info","colNames["+k+"] : " + colNames[k]);
							}
						}
						*/
						int type = sms_sent_cursor.getInt(sms_sent_cursor.getColumnIndex("type"));
						Log.e("Info","SMS Type : " + type);
						// for actual state type=2
						if(type == 2){
							Log.e("Info","Id : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("_id")));
							Log.e("Info","Thread Id : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("thread_id")));
							Log.e("Info","Address : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("address")));
							Log.e("Info","Person : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("person")));
							Log.e("Info","Date : " + sms_sent_cursor.getLong(sms_sent_cursor.getColumnIndex("date")));
							Log.e("Info","Read : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("read")));
							Log.e("Info","Status : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("status")));
							Log.e("Info","Type : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("type")));
							Log.e("Info","Rep Path Present : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("reply_path_present")));
							Log.e("Info","Subject : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("subject")));
							Log.e("Info","Body : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("body")));
							Log.e("Info","Err Code : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("error_code")));
							
							smsBodyStr = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("body")).trim();
							phoneNoStr = sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("address")).trim();
							smsDatTime = sms_sent_cursor.getLong(sms_sent_cursor.getColumnIndex("date"));
							
							Log.e("Info","SMS Content : "+smsBodyStr);
							Log.e("Info","SMS Phone No : "+phoneNoStr);
							Log.e("Info","SMS Time : "+smsDatTime);
						}
					}
				}
			}
			else
				Log.e("Info","Send Cursor is Empty");
		}
		catch(Exception sggh){
			Log.e("Error", "Error on onChange : "+sggh.toString());
		}
		super.onChange(selfChange);
	}//fn onChange
	
}//End of class SmsObserver

To register the content observer the following code lines are essential

static final Uri SMS_STATUS_URI = Uri.parse("content://sms");
SmsObserver smsSentObserver = new SmsObserver(new Handler(), this);
this.getContentResolver().registerContentObserver(SMS_STATUS_URI, true, smsSentObserver);

For code please download from
https://sites.google.com/site/katharnavas/android/SMSTracker.zip

The following code allows to retrieve the contact details using phone number

String contactId = "";
String contactName = "";

private void retrieveContactRecord(String phoneNo) {
	try{
		Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNo));
		String[] projection = new String[] { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.DISPLAY_NAME };
		String selection = null;
		String[] selectionArgs = null;
		String sortOrder = ContactsContract.PhoneLookup.DISPLAY_NAME+ " COLLATE LOCALIZED ASC";
		ContentResolver cr = mContext.getContentResolver();
		if(cr != null){
			Cursor resultCur = cr.query(uri, projection, selection, selectionArgs, sortOrder);
			if(resultCur != null){
				while (resultCur.moveToNext()) {
					contactId = resultCur.getString(resultCur.getColumnIndex(ContactsContract.PhoneLookup._ID));
					contactName = resultCur.getString(resultCur.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME));
					Log.e("Info","Contact Id : "+contactId);
					Log.e("Info","Contact Display Name : "+contactName);
					break;
				}
				resultCur.close();
			}
		}
	}
	catch(Exception sfg){
		Log.e("Error", "Error in loadContactRecord : "+sfg.toString());
	}
}//fn retrieveContactRecord

The following code block allows you to listen for all the incoming sms in Android

public class SmsReceiver  extends BroadcastReceiver {
	
    private Context mContext;
    private Bundle mBundle;
    
    private String smsBodyStr = "", phoneNoStr = "";
    private long smsDatTime = System.currentTimeMillis();
    
    public void onReceive(Context context, Intent intent) {
		try{
			mContext = context;
			mBundle = intent.getExtras();  
			
		    if (mBundle != null){
		    	getSMSDetails();
		    }
		    else
		    	Log.e("Info","Bundle is Empty!");
		}
		catch(Exception sgh){
			Log.e("ERROR", "Error in Init : "+sgh.toString());
		}
	}//fn onReceive

	private void getSMSDetails(){	     
	    SmsMessage[] msgs = null;
		try{
			Object[] pdus = (Object[]) mBundle.get("pdus");
			if(pdus != null){
				msgs = new SmsMessage[pdus.length];
				Log.e("Info","pdus length : "+pdus.length);
				for(int k=0; k<msgs.length; k++){
					msgs[k] = SmsMessage.createFromPdu((byte[])pdus[k]);  
					
					Log.e("Info","getDisplayMessageBody : "+msgs[k].getDisplayMessageBody());
					Log.e("Info","getDisplayOriginatingAddress : "+msgs[k].getDisplayOriginatingAddress());
					Log.e("Info","getMessageBody : "+msgs[k].getMessageBody());
					Log.e("Info","getOriginatingAddress : "+msgs[k].getOriginatingAddress());
					Log.e("Info","getProtocolIdentifier : "+msgs[k].getProtocolIdentifier());
					Log.e("Info","getStatus : "+msgs[k].getStatus());
					Log.e("Info","getStatusOnIcc : "+msgs[k].getStatusOnIcc());
					Log.e("Info","getStatusOnSim : "+msgs[k].getStatusOnSim());
					
					smsBodyStr = msgs[k].getMessageBody().trim();
					phoneNoStr = msgs[k].getOriginatingAddress().trim();
					smsDatTime = msgs[k].getTimestampMillis();
					
					Log.e("Info","SMS Content : "+smsBodyStr);
					Log.e("Info","SMS Phone No : "+phoneNoStr);
					Log.e("Info","SMS Time : "+smsDatTime);
				}
			}
		}
		catch(Exception sfgh){
			Log.e("ERROR", "Error in getSMSDetails : "+sfgh.toString());
		}
	}//fn getSMSDetails
	
}//End of class SmsReceiver

What is Android?
Android is a software stack for mobile devices that includes an operating system, middleware and key applications.

Explain the Architecture of android ?
Top -> Applications (Contacts, Browser, Phone, etc)

Below Applications -> Application Framework(Activity Manager, Window Manager, Content Providers, View System, Package manager,
Telephony manager, Resource, Notification, Location managers)

Below Application Framework -> System Libraries(Like Sqlite, webkit, SSL, OpenGL, Media Framework etc) & Android Runtime( Core Libraries and DVM)

Atlast Last -> Linux Kernel (which composed of drivers like display, camera etc.)

Describe the APK format.
The APK file is compressed the AndroidManifest.xml file, application code (.dex files), resource files, and other files.
A project is compiled into a single .apk file.

What is an action?
A description of something that an Intent sender desires.

What is an activity?
A single screen in an application, with supporting Java code.
An activity presents a visual user interface for one focused endeavor the user can undertake.
For example, an activity might present a list of menu items users can choose from or it might display photographs along with their captions.
Each one is implemented as a subclass of the Activity base class.

What is a service?
A service doesn’t have a visual user interface, but rather runs in the background for an indefinite period of time.
For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate
something and provide the result to activities that need it.
Each service extends the Service base class.

What is a Broadcast receivers?
A broadcast receiver is a component that does nothing but receive and react to broadcast announcements.
For example, announcements that the timezone has changed, that the battery is low or that the user changed a language preference.
All receivers extend the BroadcastReceiver base class.
Broadcast receivers do not display a user interface. However, they may start an activity in response to the information they receive,
or they may use the NotificationManager to alert the user like(flashing the backlight, vibrating the device, playing a sound)

What is a content provider?
A content provider makes a specific set of the application’s data available to other applications.The content provider extends the ContentProvider
base class to implement a standard set of methods that enable other applications to retrieve and store data of the type it controls.
However, applications do not call these methods directly. Rather they use a ContentResolver object and call its methods instead.

What is intent?
A class (Intent) describes what a caller desires to do. The caller sends this intent to Android’s intent resolver, which finds the most suitable activity for the intent.

How is nine-patch image different from a regular bitmap?
It is a resizable bitmap resource that can be used for backgrounds or other images on the device. The NinePatch class permits drawing a bitmap in nine sections. The four corners are unscaled; the four edges are scaled in one axis, and the middle is scaled in both axes.

What languages does Android support for application development?
Android applications are written using the Java programming language.

What is a resource?
A user-supplied XML, bitmap, or other file, injected into the application build process, which can later be loaded from code.

What Virtual Machine Android runs on?
Dalvik virtual machine

Android Latest Version?
Android 3.0

How do you define the user interface?
XML Format is the best.

Code Snippets:
————————
How to start a browser instance with some url ?

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse("http://google.com");
intent.setData(u);
startActivity(intent);

//Function called when return from a sub activity.

protected void onActivityResult(int requestCode, int resultCode, String data, Bundle extras) {
}

//How to retrieve the device IMEI Number

TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imei = mTelephonyMgr.getDeviceId(); 

How to call a subactivity?

Intent intent = new Intent(this, SubActivity.class);
//to pass data
addintent.putExtra(name, value);
startActivityForResult(intent, int);

The following code block shows how to split a string in to array of strings in blackberry.

private String[] split(String strString, String strDelimiter) {
        String[] strArray;
        int iOccurrences = 0;
        int iIndexOfInnerString = 0;
        int iIndexOfDelimiter = 0;
        int iCounter = 0;
    
        //Check for null input strings.
        if (strString == null) {
            throw new IllegalArgumentException("Input string cannot be null.");
        }
        //Check for null or empty delimiter strings.
        if (strDelimiter.length() <= 0 || strDelimiter == null) {
            throw new IllegalArgumentException("Delimeter cannot be null or empty.");
        }
    
        if (strString.startsWith(strDelimiter)) {
            strString = strString.substring(strDelimiter.length());
        }
    
        //If strString does not end with the delimiter then add it
        //to the string in order to comply with the desired format.
        if (!strString.endsWith(strDelimiter)) {
            strString += strDelimiter;
        }
    
        //Count occurrences of the delimiter in the string.
        //Occurrences should be the same amount of inner strings.
        while((iIndexOfDelimiter = strString.indexOf(strDelimiter,
            iIndexOfInnerString)) != -1) {
            iOccurrences += 1;
            iIndexOfInnerString = iIndexOfDelimiter +
                strDelimiter.length();
        }
    
        //Declare the array with the correct size.
        strArray = new String[iOccurrences];
    
        //Reset the indices.
        iIndexOfInnerString = 0;
        iIndexOfDelimiter = 0;
    
        //Walk across the string again and this time add the
        //strings to the array.
        while((iIndexOfDelimiter = strString.indexOf(strDelimiter,
            iIndexOfInnerString)) != -1) {
    
            //Add string to array.
            strArray[iCounter] = strString.substring(iIndexOfInnerString,iIndexOfDelimiter);
    
            //Increment the index to the next character after
            //the next delimiter.
            iIndexOfInnerString = iIndexOfDelimiter +
                strDelimiter.length();
    
            //Inc the counter.
            iCounter += 1;
        }
    
        return strArray;
    }//fn split

To make the function call

String delimit = ",";
String mainStr = "apple, banana, orange, pineapple, cherry";
String[] fruits = split(mainStr , delimit); 

The following code block shows how to convert a byte array in to base64 string

private String encodeBase64( byte[] toEncode, int offset, int length ) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(length);
        Base64OutputStream base64OutputStream = new Base64OutputStream( byteArrayOutputStream );
        try{
            base64OutputStream.write( toEncode, offset, length );
            base64OutputStream.flush();
            base64OutputStream.close(); 
        }
        catch (IOException ioe){
            System.out.println("Error in encodeBase64() : "+ioe.toString());
            return null;
        }
        return byteArrayOutputStream.toString();
}//fn encodeBase64

The following code shows how how to convert base64 encoded string to bytes

byte[] decoded = Base64InputStream.decode(base64str);

The following code block helps you to convert a byte array to hex string format.

private String byteArrayToHexString(byte in[]){
        byte ch = 0x00;
        int i = 0;
        if (in == null || in.length <= 0){
            return null;
        }
        String pseudo[] = {"0", "1", "2","3", "4", "5", "6", "7", "8","9", "A", "B", "C", "D", "E", "F"};
        StringBuffer out_str_buf = new StringBuffer(in.length * 2);
        while (i < in.length){
            ch = (byte) (in[i] & 0xF0); // Strip off high nibble
            ch = (byte) (ch >>> 4);     // shift the bits down
            ch = (byte) (ch & 0x0F);    // must do this is high order bit is on!
            out_str_buf.append(pseudo[ (int) ch]); // convert the nibble to a String Character
            ch = (byte) (in[i] & 0x0F); // Strip off low nibble
            out_str_buf.append(pseudo[ (int) ch]); // convert the nibble to a String Character
            i++;
        }
        String rslt = new String(out_str_buf);
        return rslt;
    }
Follow

Get every new post delivered to your Inbox.

Join 38 other followers