I am receiving sms using Broadcast Receiver.It is working fine. Now I want to read sms from inbox using service, (which is received by broadcast receiver).
I want to retreive sms from inbox using SERVICE. SMS retreival must be happen in background not in main thread.No any Activity should be used. //Broadcast receiver to receive sms and starting a service via intent public class SMSReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] message = null;
String str = "";
if(bundle != null){
Object[] pdus = (Object[])bundle.get("pdus");
message = new SmsMessage[pdus.length];
for(int i = 0; i<message.length; i++){
message[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "New SMS from cloudy contacts " + message[i].getOriginatingAddress();
}
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
Intent intent1 = new Intent(context,MyService.class);
context.startService(intent1);
}
}
}
Servie public class MyService extends Service{ ReadSMS readSMS;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
public void onCreate(Bundle savedInstanceState){
Log.d("Service","inside onCreate of service");
}
public void onDestroy(){
Log.d("Service", "destroyed");
}
public void onStart(){
Log.d("Service","starting service to read sms from inbox");
Toast.makeText(this,"Reading sms from inbox",Toast.LENGTH_LONG).show();
readSMS = new ReadSMS();
ArrayList list = readSMS.readSms("inbox");
}
public class ReadSMS{
public ArrayList readSms(String inbox){
ArrayList sms = new ArrayList();
Uri uri = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uri, new String[]{"_id","address","date","body"},null,null,null);
cursor.moveToLast();
String address = cursor.getString(1);
String body = cursor.getString(3);
sms.add(address+" "+body);
return sms;
}
}
}