/[projects]/android/SmsSend/src/dk/thoerup/smssend/SmsSend.java
ViewVC logotype

Contents of /android/SmsSend/src/dk/thoerup/smssend/SmsSend.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 751 - (show annotations) (download)
Wed May 26 07:44:39 2010 UTC (13 years, 11 months ago) by torben
File size: 11600 byte(s)
CoolSms, switch to POST and analyse the result
1 package dk.thoerup.smssend;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.OutputStream;
7 import java.net.HttpURLConnection;
8 import java.net.URL;
9 import java.net.URLConnection;
10 import java.net.URLDecoder;
11 import java.net.URLEncoder;
12 import java.util.ArrayList;
13
14 import android.app.Activity;
15 import android.app.ProgressDialog;
16 import android.content.Intent;
17 import android.content.SharedPreferences;
18 import android.os.AsyncTask;
19 import android.os.Bundle;
20 import android.provider.ContactsContract;
21 import android.telephony.SmsManager;
22 import android.util.Log;
23 import android.view.Menu;
24 import android.view.MenuItem;
25 import android.view.View;
26 import android.view.View.OnClickListener;
27 import android.widget.AdapterView;
28 import android.widget.ArrayAdapter;
29 import android.widget.Button;
30 import android.widget.EditText;
31 import android.widget.Spinner;
32 import android.widget.Toast;
33 import android.widget.AdapterView.OnItemSelectedListener;
34
35 public class SmsSend extends Activity {
36 /** Called when the activity is first created. */
37
38 final int MAXCOUNT = 25;
39 final String SMSDAEMON = "42407617";
40
41 final int OPTIONS_SETTINGS = 1000;
42
43 final int LOOKUP_PHONENR = 2000;
44
45
46 @Override
47 public void onCreate(Bundle savedInstanceState) {
48 super.onCreate(savedInstanceState);
49 setContentView(R.layout.main);
50
51 Button select = (Button) findViewById(R.id.selectNumber);
52 select.setOnClickListener( selectListener );
53
54 Button send = (Button) findViewById(R.id.send);
55 send.setOnClickListener(sendListener);
56
57
58
59 Spinner method = (Spinner) findViewById(R.id.method);
60 ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(this, R.array.methods, android.R.layout.simple_spinner_item);
61 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
62 method.setOnItemSelectedListener(methodSelected);
63 method.setAdapter(adapter);
64 method.setSelection(0);
65
66 }
67
68 @Override
69 public boolean onCreateOptionsMenu(Menu menu) {
70 MenuItem item;
71
72 item = menu.add(0, OPTIONS_SETTINGS, 0, "Settings");
73 item.setIcon(android.R.drawable.ic_menu_edit);
74
75 return true;
76 }
77
78 @Override
79 public boolean onOptionsItemSelected(MenuItem item) {
80 boolean retval = true;
81
82 //TODO: Cleanup
83 switch (item.getItemId()) {
84 case OPTIONS_SETTINGS:
85 Intent i = new Intent(this, dk.thoerup.smssend.SmsConfig.class);
86 startActivity(i);
87 break;
88 default:
89 retval = super.onOptionsItemSelected(item);
90 }
91 return retval;
92
93 }
94
95
96
97 @Override
98 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
99 super.onActivityResult(requestCode, resultCode, data);
100
101 switch(requestCode) {
102 case LOOKUP_PHONENR:
103 if (resultCode == Activity.RESULT_OK) {
104 String phone = data.getStringExtra("phone");
105 EditText dest = (EditText) findViewById(R.id.destination);
106 dest.setText(phone);
107 }
108 break;
109 }
110 }
111
112 void lookup() {
113
114 Intent intent = new Intent(Intent.ACTION_PICK);
115 intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
116
117 startActivityForResult(intent, LOOKUP_PHONENR);
118
119
120
121 /*
122 Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
123 null, null, null, null);
124 while (cursor.moveToNext()) {
125 String contactId = cursor.getString(cursor.getColumnIndex(
126 ContactsContract.Contacts._ID));
127 String hasPhone = cursor.getString(cursor.getColumnIndex(
128 ContactsContract.Contacts.HAS_PHONE_NUMBER));
129 String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
130
131 Log.v("contact", name + " : " + hasPhone);
132
133
134
135 if (Integer.parseInt(hasPhone) > 0) {
136 // You know have the number so now query it like this
137 Cursor phones = getContentResolver().query(
138 ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
139 null,
140 ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,
141 null, null);
142 while (phones.moveToNext()) {
143 int phoneIdx = phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER);
144 String phoneNumber = phones.getString( phoneIdx );
145 Log.v("phone", phoneNumber);
146
147 }
148 phones.close();
149 }
150
151 }
152 cursor.close();
153 */
154
155 }
156
157 OnClickListener selectListener = new OnClickListener() {
158 @Override
159 public void onClick(View v) {
160 lookup();
161 }
162 };
163
164
165 OnClickListener sendListener = new OnClickListener() {
166 @Override
167 public void onClick(View v) {
168 SendWorker worker = new SendWorker();
169 worker.execute();
170 }
171 };
172
173 int getCount() {
174 EditText countView = (EditText) findViewById(R.id.count);
175 String strCount = countView.getText().toString();
176
177 int count = Integer.parseInt(strCount);
178
179 return Math.min(count, MAXCOUNT); //limit to MAXCOUNT
180 }
181
182 int getInterval() {
183 EditText intView = (EditText) findViewById(R.id.interval);
184 String strInt = intView.getText().toString();
185
186 return Integer.parseInt(strInt);
187 }
188
189 String getFrom() {
190 EditText origin = (EditText) findViewById(R.id.origin);
191 return origin.getText().toString().trim();
192 }
193
194 String getTo() {
195 EditText destination = (EditText) findViewById(R.id.destination);
196 String to = destination.getText().toString().trim();
197
198 to = to.replace("+", "");
199 if (to.length() < 10) {
200 to = "45" + to;
201 }
202 return to;
203 }
204
205 String getMessage() {
206 EditText message = (EditText) findViewById(R.id.message);
207 return message.getText().toString().trim();
208 }
209
210 boolean sendInternal() {
211 int count = getCount();
212 String to = getTo();
213
214 SmsManager sms = SmsManager.getDefault();
215 ArrayList<String> parts = sms.divideMessage(getMessage() );
216
217 for (int i=0; i<count; i++) {
218 sms.sendMultipartTextMessage(to, null, parts, null, null);
219 sleep(5000); //give the phone some time to send the message
220 }
221
222 return true;
223 }
224
225 void sleep(int s) {
226 try {
227 Thread.sleep(s);
228 } catch (InterruptedException e) {
229 Log.e("SmsSend", "Sleep interrupted", e);
230 }
231 }
232
233 boolean isNumeric(String str) {
234 for (int i=0; i<str.length(); i++) {
235 char c = str.charAt(i);
236 if (! Character.isDigit(c) )
237 return false;
238 }
239
240 return true;
241 }
242
243 String encode(String url) {
244 try {
245 return URLEncoder.encode(url, "UTF-8");
246 } catch (Exception e) {
247 return url;
248 }
249 }
250
251 boolean sendCoolSms() {
252 SharedPreferences prefs = this.getSharedPreferences("SmsSend", MODE_PRIVATE);
253 String user = prefs.getString("cooluser", "");
254 String pass = prefs.getString("coolpass", "");
255
256 if (user.equals("") || pass.equals("")) {
257 Toast.makeText(this, "No username or password set!", Toast.LENGTH_LONG).show();
258 return false;
259 }
260
261 if ( isNumeric(getFrom()) ) {
262 Toast.makeText(this, "Can not send when 'from' equals a number\nmust add letters", Toast.LENGTH_LONG).show();
263 return false;
264 }
265
266 //"http://sms.coolsmsc.dk:8080/?username=%s&password=%s&to=%s&from=SMS+HTTP+GW&message=hello+world"
267
268 String url = "http://sms.coolsmsc.dk:8080/";
269
270 StringBuilder sb = new StringBuilder();
271 sb.append("username=").append(user);
272 sb.append("&password=").append(pass);
273 sb.append("&to=").append( getTo() );
274 sb.append("&from=").append( encode(getFrom()) );
275 sb.append("&message=").append( encode(getMessage()) );
276 sb.append("&resulttype=urlencoded");
277 sb.append("&lang=en");
278
279 Log.v("SmsSend", sb.toString());
280
281
282 boolean success = false;
283 String msg = "";
284 try {
285 byte bytes[] = postContent(url, sb.toString(), 2500 );
286 String res = new String(bytes);
287 String parts[] = res.split("&");
288
289 for (String part : parts) {
290 String pair[] = part.split("=");
291 if (pair[0].equals("status")) {
292 if (pair[1].equals("success")) {
293 success = true;
294 } else {
295 success = false;
296 }
297 }
298
299 if (pair[0].equals("result")) {
300 msg = URLDecoder.decode(pair[1]);
301 }
302 }
303
304
305
306 } catch (Exception e) {
307 Log.e("SmsSend", "sendCoolSms", e);
308 success = false;
309 }
310
311 return success;
312 }
313
314 boolean sendSmsDaemon() {
315
316 int count = getCount();
317 int interval = getInterval();
318 String to = getTo();
319
320 String msg = "spam " + to + " " + count + " " + interval + " " + getMessage();
321
322 SmsManager sms = SmsManager.getDefault();
323 ArrayList<String> parts = sms.divideMessage(msg);
324
325
326 sms.sendMultipartTextMessage(SMSDAEMON, null, parts, null, null);
327
328 return true;
329 }
330
331
332 public static byte[] getContent(String uri, int timeout) throws IOException {
333 byte buffer[] = new byte[256];
334
335 ByteArrayOutputStream baos = new ByteArrayOutputStream(32768); //start buffer size - instead of default 32bytes
336
337 URL url = new URL(uri);
338 URLConnection connection = url.openConnection();
339 HttpURLConnection c;
340 connection.setConnectTimeout(timeout);
341 InputStream is = connection.getInputStream();
342
343 try {
344 int count;
345 while ( (count = is.read(buffer)) != -1) {
346 baos.write(buffer, 0, count);
347 }
348 } finally {
349 try {
350 is.close();
351 baos.close();
352 } catch (Exception e) {} //never mind if close throws an exception
353 }
354
355 return baos.toByteArray();
356 }
357
358 public static byte[] postContent(String uri, String data, int timeout) throws IOException {
359 byte buffer[] = new byte[256];
360
361 ByteArrayOutputStream baos = new ByteArrayOutputStream(32768); //start buffer size - instead of default 32bytes
362
363 URL url = new URL(uri);
364 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
365 connection.setDoOutput(true);
366 connection.setRequestMethod("POST");
367 connection.setConnectTimeout(timeout);
368
369 OutputStream os = connection.getOutputStream();
370 os.write( data.getBytes() );
371
372 InputStream is = connection.getInputStream();
373
374 try {
375 int count;
376 while ( (count = is.read(buffer)) != -1) {
377 baos.write(buffer, 0, count);
378 }
379 } finally {
380 try {
381 is.close();
382 baos.close();
383 } catch (Exception e) {} //never mind if close throws an exception
384 }
385
386 return baos.toByteArray();
387 }
388
389 OnItemSelectedListener methodSelected = new OnItemSelectedListener() {
390 public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
391 switch (pos) {
392 case 0:
393 findViewById(R.id.interval).setEnabled(false);
394 findViewById(R.id.origin).setEnabled(false);
395 findViewById(R.id.count).setEnabled(true);
396 break;
397 case 1:
398 findViewById(R.id.interval).setEnabled(false);
399 findViewById(R.id.origin).setEnabled(true);
400 findViewById(R.id.count).setEnabled(false);
401 break;
402 case 2:
403 findViewById(R.id.interval).setEnabled(true);
404 findViewById(R.id.origin).setEnabled(false);
405 findViewById(R.id.count).setEnabled(true);
406 break;
407 }
408 }
409
410 @Override
411 public void onNothingSelected(AdapterView<?> arg0) {
412
413 }
414 };
415
416 class SendWorker extends AsyncTask<Void, Void, Void> {
417
418 boolean ret;
419 ProgressDialog dlg;
420
421 @Override
422 protected void onPreExecute() {
423 super.onPreExecute();
424
425 dlg = new ProgressDialog(SmsSend.this);
426 dlg.setMessage( "Sending" );
427 dlg.setCancelable(true);
428 dlg.show();
429
430 ret = false;
431 }
432
433 @Override
434 protected Void doInBackground(Void... params) {
435 Spinner method = (Spinner) findViewById(R.id.method);
436 int sel = method.getSelectedItemPosition();
437
438
439 switch (sel) {
440 case 0:
441 ret = sendInternal();
442 break;
443 case 1:
444 ret = sendCoolSms();
445 break;
446 case 2:
447 ret = sendSmsDaemon();
448 break;
449
450 }
451
452 return null;
453 }
454
455 @Override
456 protected void onPostExecute(Void result) {
457 dlg.dismiss();
458 dlg = null;
459
460 String msg = "Done!";
461 if (ret == false)
462 msg = "failed!";
463
464 Toast.makeText(SmsSend.this, msg, Toast.LENGTH_LONG).show();
465 }
466
467 }
468
469 }

  ViewVC Help
Powered by ViewVC 1.1.20