Android Tutorial - Network : SMS
SMS Intent
package app.test; import java.io.File; import java.util.ArrayList; import android.app.Activity; import android.app.SearchManager; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.Contacts; import android.view.Menu; public class Test extends Activity { private Intent browserIntent, phoneIntent, mapIntent, mailIntent, contactIntent, marketIntent, smsIntent; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); smsIntent = new Intent(); smsIntent.setAction(Intent.ACTION_VIEW); smsIntent.setType("vnd.android-dir/mms-sms"); smsIntent.putExtra("address", "8888888888"); smsIntent.putExtra("sms_body", "SMS Body"); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add("Browser").setIntent(browserIntent); menu.add("Phone").setIntent(phoneIntent); menu.add("Map").setIntent(mapIntent); menu.add("Mail").setIntent(Intent.createChooser(mailIntent, "Mail Client")); menu.add("SMS").setIntent(smsIntent); menu.add("Contacts").setIntent(contactIntent); menu.add("Market").setIntent(marketIntent); return true; } }
Sends an SMS message to another device
package app.test; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Test extends Activity { Button btnSendEmail; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnSendEmail = (Button) findViewById(R.id.btnSendEmail); btnSendEmail.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String[] to = {"w@l.net", "w@g.com"}; String[] cc = {"c@l.net"}; sendEmail(to, cc, "Hello", "Hello my friends!"); } }); } //---sends an SMS message to another device--- private void sendEmail(String[] emailAddresses, String[] carbonCopies, String subject, String message) { Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.setData(Uri.parse("mailto:")); String[] to = emailAddresses; String[] cc = carbonCopies; emailIntent.putExtra(Intent.EXTRA_EMAIL, to); emailIntent.putExtra(Intent.EXTRA_CC, cc); emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject); emailIntent.putExtra(Intent.EXTRA_TEXT, message); emailIntent.setType("message/rfc822"); startActivity(Intent.createChooser(emailIntent, "Email")); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/btnSendEmail" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Send Email" /> </LinearLayout>
extends BroadcastReceiver to create SMS Receiver
package app.test; import android.app.Activity; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.telephony.SmsManager; import android.telephony.SmsMessage; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; class SMSReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String str = ""; if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i = 0; i < msgs.length; i++) { msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); str += "SMS from " + msgs[i].getOriginatingAddress(); str += " :"; str += msgs[i].getMessageBody().toString(); str += "\n"; } Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); Intent mainActivityIntent = new Intent(context, Test.class); mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(mainActivityIntent); Intent broadcastIntent = new Intent(); broadcastIntent.setAction("SMS_RECEIVED_ACTION"); broadcastIntent.putExtra("sms", str); context.sendBroadcast(broadcastIntent); } } } public class Test extends Activity { Button btnSendSMS; IntentFilter intentFilter; private BroadcastReceiver intentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { TextView SMSes = (TextView) findViewById(R.id.textView1); SMSes.setText(intent.getExtras().getString("sms")); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); intentFilter = new IntentFilter(); intentFilter.addAction("SMS_RECEIVED_ACTION"); registerReceiver(intentReceiver, intentFilter); btnSendSMS = (Button) findViewById(R.id.btnSendSMS); btnSendSMS.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { sendSMS("5554", "Hello my friends!"); Intent i = new Intent(android.content.Intent.ACTION_VIEW); i.putExtra("address", "5556; 5558; 5560"); i.putExtra("sms_body", "Hello my friends!"); i.setType("vnd.android-dir/mms-sms"); startActivity(i); } }); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } @Override protected void onDestroy() { unregisterReceiver(intentReceiver); super.onPause(); } private void sendSMS(String phoneNumber, String message) { String SENT = "SMS_SENT"; String DELIVERED = "SMS_DELIVERED"; PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent( SENT), 0); PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0); registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent arg1) { switch (getResultCode()) { case Activity.RESULT_OK: Toast.makeText(getBaseContext(), "SMS sent", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: Toast.makeText(getBaseContext(), "Generic failure", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NO_SERVICE: Toast.makeText(getBaseContext(), "No service", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NULL_PDU: Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_RADIO_OFF: Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show(); break; } } }, new IntentFilter(SENT)); registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent arg1) { switch (getResultCode()) { case Activity.RESULT_OK: Toast.makeText(getBaseContext(), "SMS delivered", Toast.LENGTH_SHORT).show(); break; case Activity.RESULT_CANCELED: Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show(); break; } } }, new IntentFilter(DELIVERED)); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/btnSendSMS" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Send SMS" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
SMS Inbox Demo
package app.test; import android.app.ListActivity; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.widget.ListAdapter; import android.widget.SimpleCursorAdapter; public class SMSInboxDemo extends ListActivity { private ListAdapter adapter; private static final Uri SMS_INBOX = Uri.parse("content://sms/inbox"); @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); Cursor c = getContentResolver() .query(SMS_INBOX, null, null, null, null); startManagingCursor(c); String[] columns = new String[] { "body" }; int[] names = new int[] { R.id.row }; adapter = new SimpleCursorAdapter(this, R.layout.main, c, columns, names); setListAdapter(adapter); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is /res/layout/sms_inbox.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/row" android:layout_width="fill_parent" android:layout_height="fill_parent"/> </LinearLayout>
SmsMessage Demo
package app.test; import android.app.Activity; import android.os.Bundle; import android.telephony.SmsManager; import android.view.View; import android.widget.EditText; import android.widget.Toast; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.SmsMessage; import android.util.Log; class MySMSMonitor extends BroadcastReceiver { private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED"; @Override public void onReceive(Context context, Intent intent) { if(intent!=null && intent.getAction()!=null && ACTION.compareToIgnoreCase(intent.getAction())==0) { Object[]pduArray = (Object[]) intent.getExtras().get("pdus"); SmsMessage[] messages = new SmsMessage[pduArray.length]; for (int i = 0; i<pduArray.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[])pduArray [i]); Log.d("MySMSMonitor", "From: " + messages[i].getOriginatingAddress()); Log.d("MySMSMonitor", "Msg: " + messages[i].getMessageBody()); } Log.d("MySMSMonitor","SMS Message Received."); } } } public class Test extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void doSend(View view) { EditText addrTxt = (EditText)findViewById(R.id.addrEditText); EditText msgTxt = (EditText)findViewById(R.id.msgEditText); try { sendSmsMessage( addrTxt.getText().toString(), msgTxt.getText().toString()); Toast.makeText(this, "SMS Sent", Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(this, "Failed to send SMS", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } @Override protected void onDestroy() { super.onDestroy(); } private void sendSmsMessage(String address,String message)throws Exception { SmsManager smsMgr = SmsManager.getDefault(); smsMgr.sendTextMessage(address, null, message, null, null); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is /res/layout/main.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Destination Address:" /> <EditText android:id="@+id/addrEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:phoneNumber="true" android:text="9045551212" /> </LinearLayout> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Text Message:" /> <EditText android:id="@+id/msgEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="hello sms" /> </LinearLayout> <Button android:id="@+id/sendSmsBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send Text Message" android:onClick="doSend" /> </LinearLayout>
Sms Messaging Demo
package com.example.android.apis.os; import java.util.List; import android.app.Activity; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.graphics.Color; import android.os.Bundle; import android.telephony.SmsManager; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.widget.CompoundButton.OnCheckedChangeListener; public class SmsMessagingDemo extends Activity { /** Tag string for our debug logs */ private static final String TAG = "SmsMessagingDemo"; public static final String SMS_RECIPIENT_EXTRA = "com.example.android.apis.os.SMS_RECIPIENT"; public static final String ACTION_SMS_SENT = "com.example.android.apis.os.SMS_SENT_ACTION"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); if (getIntent().hasExtra(SMS_RECIPIENT_EXTRA)) { ((TextView) findViewById(R.id.sms_recipient)).setText(getIntent().getExtras() .getString(SMS_RECIPIENT_EXTRA)); ((TextView) findViewById(R.id.sms_content)).requestFocus(); } // Enable or disable the broadcast receiver depending on the checked // state of the checkbox. CheckBox enableCheckBox = (CheckBox) findViewById(R.id.sms_enable_receiver); final PackageManager pm = this.getPackageManager(); final ComponentName componentName = new ComponentName("com.example.android.apis", "com.example.android.apis.os.SmsMessageReceiver"); enableCheckBox.setChecked(pm.getComponentEnabledSetting(componentName) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED); enableCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Log.d(TAG, (isChecked ? "Enabling" : "Disabling") + " SMS receiver"); pm.setComponentEnabledSetting(componentName, isChecked ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } }); final EditText recipientTextEdit = (EditText) SmsMessagingDemo.this .findViewById(R.id.sms_recipient); final EditText contentTextEdit = (EditText) SmsMessagingDemo.this .findViewById(R.id.sms_content); final TextView statusView = (TextView) SmsMessagingDemo.this.findViewById(R.id.sms_status); // Watch for send button clicks and send text messages. Button sendButton = (Button) findViewById(R.id.sms_send_message); sendButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (TextUtils.isEmpty(recipientTextEdit.getText())) { Toast.makeText(SmsMessagingDemo.this, "Please enter a message recipient.", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(contentTextEdit.getText())) { Toast.makeText(SmsMessagingDemo.this, "Please enter a message body.", Toast.LENGTH_SHORT).show(); return; } recipientTextEdit.setEnabled(false); contentTextEdit.setEnabled(false); SmsManager sms = SmsManager.getDefault(); List<String> messages = sms.divideMessage(contentTextEdit.getText().toString()); String recipient = recipientTextEdit.getText().toString(); for (String message : messages) { sms.sendTextMessage(recipient, null, message, PendingIntent.getBroadcast( SmsMessagingDemo.this, 0, new Intent(ACTION_SMS_SENT), 0), null); } } }); // Register broadcast receivers for SMS sent and delivered intents registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String message = null; boolean error = true; switch (getResultCode()) { case Activity.RESULT_OK: message = "Message sent!"; error = false; break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: message = "Error."; break; case SmsManager.RESULT_ERROR_NO_SERVICE: message = "Error: No service."; break; case SmsManager.RESULT_ERROR_NULL_PDU: message = "Error: Null PDU."; break; case SmsManager.RESULT_ERROR_RADIO_OFF: message = "Error: Radio off."; break; } recipientTextEdit.setEnabled(true); contentTextEdit.setEnabled(true); contentTextEdit.setText(""); statusView.setText(message); statusView.setTextColor(error ? Color.RED : Color.GREEN); } }, new IntentFilter(ACTION_SMS_SENT)); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2010 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- Demonstrates sending and receiving SMS messages. See corresponding Java code SmsMessagingDemo.java --> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="6dip"> <TextView android:textColor="#ff0000" android:textStyle="bold" android:text="sms_warning" android:layout_width="match_parent" android:layout_height="wrap_content" /> <CheckBox android:id="@+id/sms_enable_receiver" android:text="sms_enable_receiver" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TableLayout android:padding="6dip" android:layout_width="match_parent" android:layout_height="wrap_content" android:stretchColumns="1"> <TableRow android:layout_width="match_parent"> <TextView android:text="sms_recipient_label" /> <EditText android:id="@+id/sms_recipient" /> </TableRow> <TableRow> <TextView android:text="sms_content_label" /> <EditText android:id="@+id/sms_content" /> </TableRow> <TableRow> <Button android:id="@+id/sms_send_message" android:text="sms_send_message" android:layout_column="1" /> </TableRow> <TableRow> <TextView android:id="@+id/sms_status" android:layout_column="1" /> </TableRow> </TableLayout> </LinearLayout> </ScrollView>
start SMS Intent
import android.content.Context; import android.content.Intent; import android.text.Html; class UIHelper { public static void startSMSIntent(final Context ctx, final String subject, final String source, final String url) { final StringBuilder body = new StringBuilder(); if (subject != null && !"".equals(subject.trim())) body.append(subject); body.append("\n\nRead on:\n ").append(url); final Intent sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.putExtra("sms_body", body.toString()); sendIntent.setType("vnd.android-dir/mms-sms"); ctx.startActivity(sendIntent); } }