Android 中发送和接收短信

来源:互联网 发布:淘宝靠谱的男装韩代 编辑:程序博客网 时间:2024/05/02 02:23
在做Android开发中经常要用到短信的发送和短信的接收,调用Android提供的api实现起来很简单,今天要用到这个功能研究了一下顺便写下来加强一下记忆。

1.首先创建一个Android Project

2.设计一个main Activity作为发短信的操作界面,设计好的界面图如下:

Android 中发送和接收短信_25944
image_2.png(48.88 K)
5/16/2010 9:44:41 PM


界面布局的文件内容如下:
  1.   1: <?xml version="1.0" encoding="utf-8"?>

  2.   2: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  3.   3:    android:orientation="vertical"

  4.   4:    android:layout_width="fill_parent"

  5.   5:    android:layout_height="fill_parent"

  6.   6:    android:padding="10sp" 

  7.   7:    >

  8.   8: <TextView 

  9.   9:    android:layout_width="fill_parent"

  10.   10:    android:layout_height="wrap_content"

  11.   11:    android:text="@string/mobile_label"

  12.   12:   

  13.   13:    />

  14.   14: <EditText

  15.   15:    android:layout_width="fill_parent"

  16.   16:    android:layout_height="wrap_content"

  17.   17:    android:id="@+id/txt_from"

  18.   18:    android:hint="请输入电话号码"

  19.   19:   

  20.   20: />

  21.   21: <TextView 

  22.   22:    android:layout_width="fill_parent"

  23.   23:    android:layout_height="wrap_content"

  24.   24:    android:text="@string/content_label"

  25.   25:    />

  26.   26: <EditText

  27.   27:    android:layout_width="fill_parent"

  28.   28:    android:layout_height="wrap_content"

  29.   29:    android:id="@+id/txt_content"

  30.   30:    android:hint="请输入短信内容"

  31.   31:    android:lines="3"

  32.   32: />

  33.   33: <TextView android:layout_width="fill_parent"

  34.   34: android:layout_height="wrap_content"

  35.   35: ></TextView>

  36.   36: <Button   

  37.   37:    android:text="发送短信"

  38.   38:    android:layout_width="fill_parent"

  39.   39:    android:layout_height="wrap_content"

  40.   40:    android:gravity="center"

  41.   41:    android:id="@+id/btnSend"

  42.   42:    android:paddingTop="20sp"

  43.   43: />

  44.   44: </LinearLayout>
复制代码
3.创建一个Java类文件,导入以下包:
  1.   1: import java.util.regex.Matcher;

  2.   2: import java.util.regex.Pattern;

  3.   3: import com.eshore.smsManagers.R;

  4.   4: import android.app.Activity;

  5.   5: import android.telephony.gsm.*;

  6.   6: import android.view.View;

  7.   7: import android.view.View.OnClickListener;

  8.   8: import android.widget.Button;

  9.   9: import android.widget.EditText;

  10.   10: import android.widget.Toast;

  11.   11: import android.os.Bundle;
复制代码
4.重写onCreate方:
  1.   1: txtFrom=(EditText)this.findViewById(R.id.txt_from);

  2.   2:        txtContent=(EditText)this.findViewById(R.id.txt_content);

  3.   3:        btnSend=(Button)this.findViewById(R.id.btnSend);

  4.   4:        btnSend.setOnClickListener(new OnClickListener() {           

  5.   5:            public void onClick(View v) {

  6.   6:                if(!validate())

  7.   7:                    return;

  8.   8:                SmsManager.getDefault().sendTextMessage(txtFrom.getText().toString().trim(),null,txtContent.getText().toString(),null,null);

  9.   9:                txtFrom.setText("");

  10.   10:                txtContent.setText("");

  11.   11:                Toast toast=Toast.makeText(main.this, "短信发送成功!",Toast.LENGTH_LONG);

  12.   12:                toast.show();

  13.   13:            }

  14.   14:        });
复制代码
相关的辅助方法有手机的合法性验证和短信内容不可为空:
  1.   1: //合法性验证

  2.   2:    private boolean validate(){

  3.   3:        String mobile=txtFrom.getText().toString().trim();

  4.   4:        String content=txtContent.getText().toString();

  5.   5:        if(mobile.equals("")){

  6.   6:            Toast toast=Toast.makeText(this, "手机号码不能为空!",Toast.LENGTH_LONG);

  7.   7:            toast.show();

  8.   8:            return false;

  9.   9:        }

  10.   10:        else if(!checkMobile(mobile)){

  11.   11:            Toast toast=Toast.makeText(this, "您输入的电话号码不正确请重新输入!",Toast.LENGTH_LONG);

  12.   12:            toast.show();

  13.   13:            return false;

  14.   14:        }

  15.   15:        else if(content.equals("")){

  16.   16:            Toast toast=Toast.makeText(this, "短信内容不能为空请重新输入!",Toast.LENGTH_LONG);

  17.   17:            toast.show();

  18.   18:            return false;

  19.   19:        }

  20.   20:        else{

  21.   21:            return true;

  22.   22:        }

  23.   23:       

  24.   24:    }

  25.   25:    /*

  26.   26:      * 中国移动134.135.136.137.138.139.150.151.152.157.158.159.187.188 ,147(数据卡不验证)

  27.   27:            中国联通130.131.132.155.156.185.186

  28.   28:            中国电信133.153.180.189

  29.   29:        CDMA  133,153

  30.   30:            手机号码验证 适合目前所有的手机

  31.   31:      */

  32.   32:    public boolean checkMobile(String mobile){

  33.   33:        String regex="^1(3[0-9]|5[012356789]|8[0789])\\d{8}[        DISCUZ_CODE_10        ]quot;;

  34.   34:        Pattern  p  =  Pattern.compile(regex); 

  35.   35:        Matcher  m  =  p.matcher(mobile); 

  36.   36:        return m.find(); 

  37.   37:    }
复制代码
经过上面的几个步骤发短信的功能基本就完成了,但是现在运行程序是无法工作的,主要是配置文件AndroidManifest.xml中的权限没有配置,要发送短信就要配置,发送短信的权限这样Android才会发送信息,否则发不出去信息,同样接收信息也需要有相应的接收短信的权限,在后面还要做接收短信的内容,所以在这里顺便将接收和发送短信的权限都配置好,配置代买如下:
  1.   1: <uses-permission android:name="android.permission.SEND_SMS"/>

  2.   2: <uses-permission android:name="android.permission.RECEIVE_SMS"/>
复制代码
可以看出来第一行是发送短信的权限,第二行是接收短信的权限

运行程序,填写正确的手机号和短信内容点击发送就可以将短信内容发送到相应的手机号上。

5、接收短信,接收短信稍有点复杂,首先创建一个接收短信的Java类文件“ReceiverDemo.java”并继承”BroadcastReceiver”

6.重写下面的方法:
  1.   1: public void onReceive(Context context, Intent intent)
复制代码
重写内容如下:
  1.   1: private static final String strRes = "android.provider.Telephony.SMS_RECEIVED";

  2.   2:    @Override

  3.   3:    public void onReceive(Context context, Intent intent) {

  4.   4:        /*

  5.   5:          * 判断是否是SMS_RECEIVED事件被触发

  6.   6:          */

  7.   7:        if (intent.getAction().equals(strRes)) {

  8.   8:            StringBuilder sb = new StringBuilder();

  9.   9:            Bundle bundle = intent.getExtras();

  10.   10:            if (bundle != null) {

  11.   11:                Object[] pdus = (Object[]) bundle.get("pdus");

  12.   12:                SmsMessage[] msg = new SmsMessage[pdus.length];

  13.   13:                for (int i = 0; i < pdus.length; i++) {

  14.   14:                    msg = SmsMessage.createFromPdu((byte[]) pdus);

  15.   15:                }

  16.   16:                for (SmsMessage currMsg : msg) {

  17.   17:                    sb.append("您收到了来自:【");

  18.   18:                    sb.append(currMsg.getDisplayOriginatingAddress());

  19.   19:                    sb.append("】\n的信息,内容:");

  20.   20:                    sb.append(currMsg.getDisplayMessageBody());

  21.   21:                }

  22.   22:                Toast toast = Toast.makeText(context, "收到了短消息: " + sb.toString(),Toast.LENGTH_LONG); 

  23.   23:                toast.show(); 

  24.   24:            }

  25.   25:        }

  26.   26:    }
复制代码
注意:

    A:第7行代码用于判断当前监听的是否是接收短信这个事件,如果是则进行下面的处理,否则不做处理

    B:12到22行解析出发信人的号码和短信内容并组成一个可读的字符串

    C:22和23行将上面组成的字符串显示给用户

7.在AndroidManifest.xml中配置一个Receiver如下:
  1.   1: <receiver android:name=".ReceiverDemo" android:enabled="true">

  2.   2:              <intent-filter>

  3.   3:                  <action android:name="android.provider.Telephony.SMS_RECEIVED" />

  4.   4:              </intent-filter>

  5.   5:      </receiver>
复制代码
原创粉丝点击