A Guide to Mobile and Web Technology(LAMP)

Posts tagged ‘Android’

Listening for outgoing sms or send sms in Android

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) {
		mContext = ctx;

	public boolean deliverSelfNotifications() {
		return true;

	public void onChange(boolean selfChange) {
			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);
				Log.e("Info","Send Cursor is Empty");
		catch(Exception sggh){
			Log.e("Error", "Error on onChange : "+sggh.toString());
	}//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

How to search for a contact using phone number in Android

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

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

private void retrieveContactRecord(String phoneNo) {
		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);
	catch(Exception sfg){
		Log.e("Error", "Error in loadContactRecord : "+sfg.toString());
}//fn retrieveContactRecord

Listener for Incoming SMS in Android

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) {
			mContext = context;
			mBundle = intent.getExtras();  
		    if (mBundle != null){
		    	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;
			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

Android Interview Questions and Answers (Basic)

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");

//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);

How to convert a byte Array to Base64 String in Blackberry

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 );
            base64OutputStream.write( toEncode, offset, length );
        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);