• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps SMS Receiver Application

dilith

Lurker
package com.dilith.smstrackr;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver{

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String sDate= dateFormat.format(date);

@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){

Bundle extras = intent.getExtras();
if(extras != null){
Object[] pdus = (Object[])extras.get("pdus");
if (pdus.length < 1) return;
StringBuilder sb = new StringBuilder();
String sender = null;
String text = null;
for (int i = 0; i < pdus.length; i++) {
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus);
if (sender == null){
sender = message.getOriginatingAddress(); //get the sender
}
text = message.getMessageBody(); //get the message body
if (text != null){
sb.append(text);
}
}

//text message
String textMessage = sDate + " | " + sender + " | " + text;
Toast.makeText(context, sender + " says " + text, Toast.LENGTH_LONG).show();

//write to SD card
String filePath = "/sdcard/Android/mysdfile.txt";
writeToFile(textMessage, filePath);
}
}
}

public void writeToFile(String textMessage, String filePath){
BufferedWriter bw = null;

try {
bw = new BufferedWriter(new FileWriter(filePath, true));
bw.write(textMessage);
bw.newLine();
bw.flush();
//Toast.makeText(context,"Done writing SD 'mysdfile.txt'",Toast.LENGTH_SHORT).show();
} catch (IOException ioe) {
//Toast.makeText(context,ioe.getMessage(),Toast.LENGTH_SHORT).show();
} finally { // always close the file

if (bw != null) {
try {
bw.close();
} catch (IOException ioe2) {
// just ignore it
}
}
}
}

}

This doesn't work in ICS Android 4.0 and above. But this works with Gingerbread Android 2.3
 
Back
Top Bottom