Skip to content

Instantly share code, notes, and snippets.

@sansagara
Created April 25, 2015 00:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sansagara/9297848bee421676a001 to your computer and use it in GitHub Desktop.
Save sansagara/9297848bee421676a001 to your computer and use it in GitHub Desktop.
Java Class for Android App: Premium SMS service using Parse.com
package com.leonelatencio.mysms;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.List;
/**
* Created by Leonel on 18-04-2015.
*/
public class SmsListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
final String messageBody = smsMessage.getMessageBody();
final String messageFrom = smsMessage.getOriginatingAddress();
//Log Received SMS
Log.d("SMS", "Message received: " + messageBody + " From: " + messageFrom);
//Save received SMS to Parse
ParseObject testObject = new ParseObject("SMSRec");
testObject.put("From", messageFrom);
testObject.put("Message", messageBody);
testObject.saveInBackground();
//Query Reply Message in Parse
ParseQuery<ParseObject> query = ParseQuery.getQuery("SMSContent");
query.whereEqualTo("keyWord", messageBody);
query.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("SMS", "Cant find a response.");
} else {
String responseBody = object.getString("responseText");
Log.d("SMS", "Found a response to" + messageBody + ":/n" + responseBody);
//Finally, try to send SMS.
sendSMS(messageFrom, responseBody);
}
}
});
}
}
}
public void sendSMS(String replyTo, String replyBody){
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(replyTo, null, replyBody, null, null);
//Log sent message.
Log.d("SMS", "Sending message: " + replyBody + " To: " + replyTo);
} catch (Exception ex) {
//Log failed SMS.
Log.d("SMS", "Sending failed: " + replyBody + " To: " + replyTo);
}
}
}
@sansagara
Copy link
Author

This is a Java Class for listening incoming SMS, checking its content, looking the keyword in parse.com class and aswering the SMS with the matching response.

You will need to include Parse.com JAR and initialize the app with your unique key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment