A Guide to Mobile and Web Technology(LAMP)

Archive for the ‘J2ME’ Category

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) {
		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

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) {
	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

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) {
		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

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

How to convert a Byte Array to Hex String

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