5
0
mirror of https://github.com/cwinfo/envayasms.git synced 2024-11-09 10:20:25 +00:00

initial import of polling code

This commit is contained in:
Nir Yariv 2011-01-15 14:42:26 -05:00
parent 4130593f3d
commit aee1061c5a
9 changed files with 226 additions and 205 deletions

View File

@ -4,10 +4,11 @@
android:versionCode="1" android:versionCode="1"
android:versionName="1.0"> android:versionName="1.0">
<uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" /> <uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" /> <uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<application android:icon="@drawable/icon" android:label="@string/app_name"> <application android:icon="@drawable/icon" android:label="@string/app_name">
@ -17,12 +18,15 @@
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<receiver android:name=".SMSReceiver"> <receiver android:name=".SMSReceiver">
<intent-filter> <intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" /> <action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter> </intent-filter>
</receiver> </receiver>
<receiver android:name=".SMSSender">
</receiver>
<activity android:name=".Prefs" <activity android:name=".Prefs"
android:label="@string/app_name"> android:label="@string/app_name">

View File

@ -1,4 +1,4 @@
(Polling branch) (Polling branch - this adds periodic URL polling functionality)
KalSMS is an simple Android SMS gateway application. KalSMS is an simple Android SMS gateway application.

View File

@ -2,6 +2,8 @@
<PreferenceScreen <PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"> xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference android:key="pref_target_url" android:title="Target URL" android:defaultValue="http://qkhack.appspot.com/kalsms_demo" android:summary="URL to load when the SMS is received"></EditTextPreference> <EditTextPreference android:key="pref_target_url" android:title="Target URL" android:summary="URL to load when the SMS is received" android:defaultValue="http://pune.admin.tastykhana.in/admin/index.php/realtime_alerts/smsqueue"></EditTextPreference>
<EditTextPreference android:key="pref_identifier" android:title="SMS Identifier" android:defaultValue="kal " android:summary="Handle only SMS messages starting with this string (leave empty to handle all messages)"></EditTextPreference> <EditTextPreference android:key="pref_identifier" android:title="SMS Identifier" android:defaultValue="TK " android:summary="Handle only SMS messages starting with this string (leave empty to handle all messages)"></EditTextPreference>
<CheckBoxPreference android:key="pref_poll_switch" android:title="Server Polling" android:disableDependentsState="false" android:summaryOff="Polling is disabled" android:summaryOn="Polling is enabled"></CheckBoxPreference>
<EditTextPreference android:key="pref_poll_interval" android:title="Poll interval" android:defaultValue="5000" android:summary="Polling interval time in minutes"></EditTextPreference>
</PreferenceScreen> </PreferenceScreen>

View File

@ -4,8 +4,6 @@ import kalsms.niryariv.itp.R;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.preference.PreferenceActivity;
import android.preference.Preference;
import android.os.Bundle; import android.os.Bundle;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.text.Html; import android.text.Html;

55
src/kalsms/niryariv/itp/Prefs.java Normal file → Executable file
View File

@ -1,31 +1,80 @@
package kalsms.niryariv.itp; package kalsms.niryariv.itp;
import kalsms.niryariv.itp.R; import kalsms.niryariv.itp.R;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle; import android.os.Bundle;
import android.os.SystemClock;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference; import android.preference.EditTextPreference;
import android.preference.Preference; import android.preference.Preference;
import android.preference.PreferenceActivity; import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log; import android.util.Log;
import android.view.Menu;
public class Prefs extends PreferenceActivity { public class Prefs extends PreferenceActivity implements OnSharedPreferenceChangeListener {
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs); addPreferencesFromResource(R.xml.prefs);
} }
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference pref = findPreference(key); Preference pref = findPreference(key);
if (pref instanceof EditTextPreference) { if (pref instanceof EditTextPreference) {
EditTextPreference textPref = (EditTextPreference) pref; EditTextPreference textPref = (EditTextPreference) pref;
pref.setSummary(textPref.getSummary()); pref.setSummary(textPref.getSummary());
Log.d("KALSMS", "textPref.getSummary(): " + textPref.getSummary()); Log.d("KALSMS", "textPref.getSummary(): " + textPref.getSummary());
} }
if(pref instanceof CheckBoxPreference) {
CheckBoxPreference checkbox = (CheckBoxPreference) pref;
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent pintent = new Intent(this, SMSSender.class);
PendingIntent pIntent = PendingIntent.getBroadcast(this,0,pintent, 0);
if(checkbox.isChecked()) {
long interval = 60*Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString("pref_poll_interval", "5000"));//5mins;//5mins
long firstPoll = SystemClock.elapsedRealtime() + 60*Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString("pref_poll_interval", "5000"));
alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstPoll, interval, pIntent);
Log.d("KALSMS", "alarm manager turned on "+interval);
}else {
alarm.cancel(pIntent);
Log.d("SMS_GATEWAY", "alarm manager turned off");
}
}
}
// first time the Menu key is pressed
public boolean onCreateOptionsMenu(Menu menu) {
startActivity(new Intent(this, Prefs.class));
return(true);
}
// any other time the Menu key is pressed
public boolean onPrepareOptionsMenu(Menu menu) {
startActivity(new Intent(this, Prefs.class));
return(true);
} }
} }

View File

@ -1,15 +1,6 @@
package kalsms.niryariv.itp; package kalsms.niryariv.itp;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
@ -22,27 +13,7 @@ import android.telephony.SmsManager;
import android.telephony.SmsMessage; import android.telephony.SmsMessage;
import android.util.Log; import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class SMSReceiver extends BroadcastReceiver { public class SMSReceiver extends BroadcastReceiver {
@Override @Override
// source: http://www.devx.com/wireless/Article/39495/1954 // source: http://www.devx.com/wireless/Article/39495/1954
@ -53,6 +24,7 @@ public class SMSReceiver extends BroadcastReceiver {
// get settings // get settings
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
TargetUrlRequest url = new TargetUrlRequest();
String identifier = settings.getString("pref_identifier", ""); String identifier = settings.getString("pref_identifier", "");
String targetUrl = settings.getString("pref_target_url", ""); String targetUrl = settings.getString("pref_target_url", "");
@ -66,25 +38,21 @@ public class SMSReceiver extends BroadcastReceiver {
if (message != null && message.length() > 0 if (message != null && message.length() > 0
&& (message.toLowerCase().startsWith(identifier) || identifier.trim() == "")) { && (message.toLowerCase().startsWith(identifier) || identifier.trim() == "")) {
Log.d("KALSMS", "MSG RCVD:\"" + message + "\" from: " + sender); Log.d("KALSMS", "MSG RCVD:\"" + message + "\" from: " + sender);
// send the message to the URL // send the message to the URL
String resp = openURL(sender, message, targetUrl).toString(); String resp = url.openURL(sender, message, targetUrl).toString();
Log.d("KALSMS", "RESP:\"" + resp); Log.d("KALSMS", "RESP:\"" + resp);
// SMS back the response // SMS back the response
if (resp.trim().length() > 0) { if (resp.trim().length() > 0) {
ArrayList<ArrayList<String>> items = parseXML(resp); ArrayList<ArrayList<String>> items = url.parseXML(resp);
SmsManager smgr = SmsManager.getDefault(); SmsManager smgr = SmsManager.getDefault();
for (int j = 0; j < items.size(); j++) { for (int j = 0; j < items.size(); j++) {
String sendTo = items.get(j).get(0); String sendTo = items.get(j).get(0);
if (sendTo.toLowerCase() == "sender") sendTo = sender; if (sendTo.toLowerCase() == "sender") sendTo = sender;
String sendMsg = items.get(j).get(1); String sendMsg = items.get(j).get(1);
try { try {
Log.d("KALSMS", "SEND MSG:\"" + sendMsg + "\" TO: " + sendTo); Log.d("KALSMS", "SEND MSG:\"" + sendMsg + "\" TO: " + sendTo);
smgr.sendTextMessage(sendTo, null, sendMsg, null, null); smgr.sendTextMessage(sendTo, null, sendMsg, null, null);
@ -93,21 +61,16 @@ public class SMSReceiver extends BroadcastReceiver {
} }
} }
} }
// delete SMS from inbox, to prevent it from filling up // delete SMS from inbox, to prevent it from filling up
DeleteSMSFromInbox(context, mesg); DeleteSMSFromInbox(context, mesg);
} }
} }
} }
private void DeleteSMSFromInbox(Context context, SmsMessage mesg) { private void DeleteSMSFromInbox(Context context, SmsMessage mesg) {
Log.d("KALSMS", "try to delete SMS"); Log.d("KALSMS", "try to delete SMS");
try { try {
Uri uriSms = Uri.parse("content://sms/inbox"); Uri uriSms = Uri.parse("content://sms/inbox");
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("address='" + mesg.getOriginatingAddress() + "' AND "); sb.append("address='" + mesg.getOriginatingAddress() + "' AND ");
sb.append("body='" + mesg.getMessageBody() + "'"); sb.append("body='" + mesg.getMessageBody() + "'");
@ -138,88 +101,9 @@ public class SMSReceiver extends BroadcastReceiver {
byte[] byteData = (byte[]) pdus[n]; byte[] byteData = (byte[]) pdus[n];
retMsgs[n] = SmsMessage.createFromPdu(byteData); retMsgs[n] = SmsMessage.createFromPdu(byteData);
} }
} catch (Exception e) { } catch (Exception e) {
Log.e("KALSMS", "GetMessages ERROR\n" + e); Log.e("KALSMS", "GetMessages ERROR\n" + e);
} }
return retMsgs; return retMsgs;
} }
}
public String openURL(String sender, String message, String targetUrl) {
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("sender", sender));
qparams.add(new BasicNameValuePair("msg", message));
String url = targetUrl + "?" + URLEncodedUtils.format(qparams, "UTF-8");
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
String resp = EntityUtils.toString(resEntityGet);
Log.e("KALSMS", "HTTP RESP" + resp);
return resp;
}
} catch (Exception e) {
Log.e("KALSMS", "HTTP REQ FAILED:" + url);
e.printStackTrace();
}
return "";
}
public static ArrayList<ArrayList<String>> parseXML(String xml) {
ArrayList<ArrayList<String>> output = new ArrayList<ArrayList<String>>();
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(xml)));
NodeList rnodes = doc.getElementsByTagName("reply");
NodeList nodes = rnodes.item(0).getChildNodes();
for (int i=0; i < nodes.getLength(); i++) {
try {
List<String> item = new ArrayList<String>();
Node node = nodes.item(i);
if (node.getNodeType() != Node.ELEMENT_NODE) continue;
Element e = (Element) node;
String nodeName = e.getNodeName();
if (nodeName.equalsIgnoreCase("sms")) {
if (!e.getAttribute("phone").equals("")) {
item.add(e.getAttribute("phone"));
item.add(e.getFirstChild().getNodeValue());
output.add((ArrayList<String>) item);
}
} else if (nodeName.equalsIgnoreCase("sms-to-sender")) {
item.add("sender");
item.add(e.getFirstChild().getNodeValue());
output.add((ArrayList<String>) item);
} else {
continue;
}
} catch (Exception e){
Log.e("KALSMS", "FAILED PARSING XML NODE# " + i );
}
}
Log.e("KALSMS", "PARSING XML RETURNS " + output );
return (output);
} catch (Exception e) {
Log.e("KALSMS", "PARSING XML FAILED: " + xml );
e.printStackTrace();
return (output);
}
}
}

View File

@ -0,0 +1,53 @@
package kalsms.niryariv.itp;
import java.util.ArrayList;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.util.Log;
public class SMSSender extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// acquiring the wake clock to prevent device from sleeping while request is processed
final PowerManager pm = (PowerManager) context.getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wake = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "http_request");
wake.acquire();
// get settings
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
String targetUrl = settings.getString("pref_target_url", "");
Log.d("KALSMS", "url:\"" + targetUrl);
TargetUrlRequest url = new TargetUrlRequest();
// send the message to the URL
String resp = url.openURL("","",targetUrl).toString();
Log.d("KALSMS", "RESP:\"" + resp);
// SMS back the response
if (resp.trim().length() > 0) {
ArrayList<ArrayList<String>> items = url.parseXML(resp);
SmsManager smgr = SmsManager.getDefault();
for (int j = 0; j < items.size(); j++) {
String sendTo = items.get(j).get(0);
String sendMsg = items.get(j).get(1);
try {
Log.d("KALSMS", "SEND MSG:\"" + sendMsg + "\" TO: " + sendTo);
smgr.sendTextMessage(sendTo, null, sendMsg, null, null);
} catch (Exception ex) {
Log.d("KALSMS", "SMS FAILED");
}
}
}
wake.release();
}
}

View File

@ -0,0 +1,105 @@
package kalsms.niryariv.itp;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.util.Log;
public class TargetUrlRequest {
public String openURL(String sender, String message, String targetUrl) {
String url = targetUrl;
if(sender.trim().length() > 0 && message.trim().length() > 0) {
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("sender", sender));
qparams.add(new BasicNameValuePair("msg", message));
url = targetUrl + "?" + URLEncodedUtils.format(qparams, "UTF-8");
}
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
String resp = EntityUtils.toString(resEntityGet);
Log.e("KALSMS", "HTTP RESP" + resp);
return resp;
}
} catch (Exception e) {
Log.e("KALSMS", "HTTP REQ FAILED:" + url);
e.printStackTrace();
}
return "";
}
public ArrayList<ArrayList<String>> parseXML(String xml) {
ArrayList<ArrayList<String>> output = new ArrayList<ArrayList<String>>();
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(xml)));
NodeList rnodes = doc.getElementsByTagName("reply");
NodeList nodes = rnodes.item(0).getChildNodes();
for (int i=0; i < nodes.getLength(); i++) {
try {
List<String> item = new ArrayList<String>();
Node node = nodes.item(i);
if (node.getNodeType() != Node.ELEMENT_NODE) continue;
Element e = (Element) node;
String nodeName = e.getNodeName();
if (nodeName.equalsIgnoreCase("sms")) {
if (!e.getAttribute("phone").equals("")) {
item.add(e.getAttribute("phone"));
item.add(e.getFirstChild().getNodeValue());
output.add((ArrayList<String>) item);
}
} else if (nodeName.equalsIgnoreCase("sms-to-sender")) {
item.add("sender");
item.add(e.getFirstChild().getNodeValue());
output.add((ArrayList<String>) item);
} else {
continue;
}
} catch (Exception e){
Log.e("KALSMS", "FAILED PARSING XML NODE# " + i );
}
}
Log.e("KALSMS", "PARSING XML RETURNS " + output );
return (output);
} catch (Exception e) {
Log.e("KALSMS", "PARSING XML FAILED: " + xml );
e.printStackTrace();
return (output);
}
}
}

View File

@ -1,74 +0,0 @@
package kalsms.niryariv.itp;
//package txtgate.niryariv.itp;
//
//import java.io.BufferedInputStream;
//import java.io.InputStream;
//import java.net.URL;
//import java.net.URLConnection;
//
//import org.apache.http.util.ByteArrayBuffer;
//
//public class URLopen {
// private Thread checkUpdate = new Thread() {
// public void run() {
// try {
// URL updateURL = new URL("http://iconic.4feets.com/update");
// URLConnection conn = updateURL.openConnection();
// InputStream is = conn.getInputStream();
// BufferedInputStream bis = new BufferedInputStream(is);
// ByteArrayBuffer baf = new ByteArrayBuffer(50);
//
// int current = 0;
// while((current = bis.read()) != -1){
// baf.append((byte)current);
// }
//
// /* Convert the Bytes read to a String. */
// final String s = new String(baf.toByteArray());
//// mHandler.post(showUpdate);
// } catch (Exception e) {
// //
// }
// }
// };
//}
//
////public class Iconic extends Activity {
//// private String html = "";
//// private Handler mHandler;
////
//// public void onCreate(Bundle savedInstanceState) {
//// super.onCreate(savedInstanceState);
//// setContentView(R.layout.main);
//// mHandler = new Handler();
//// checkUpdate.start();
//// }
////
//// private Thread checkUpdate = new Thread() {
//// public void run() {
//// try {
//// URL updateURL = new URL("http://iconic.4feets.com/update");
//// URLConnection conn = updateURL.openConnection();
//// InputStream is = conn.getInputStream();
//// BufferedInputStream bis = new BufferedInputStream(is);
//// ByteArrayBuffer baf = new ByteArrayBuffer(50);
////
//// int current = 0;
//// while((current = bis.read()) != -1){
//// baf.append((byte)current);
//// }
////
//// /* Convert the Bytes read to a String. */
//// html = new String(baf.toByteArray());
//// mHandler.post(showUpdate);
//// } catch (Exception e) {
//// }
//// }
//// };
////
//// private Runnable showUpdate = new Runnable(){
//// public void run(){
//// Toast.makeText(Iconic.this, "HTML Code: " + html, Toast.LENGTH_SHORT).show();
//// }
//// };
////}