Android接收和发送短信

每一部手机都具有短信接收和发送功能,下面我们通过代码来实现接收和发送短信功能。

一、接收短信

1、创建内部广播接收器类,接收系统发出的短信广播
2、从获得的内容中解析出短信发送者和短信内容
3、在Activity中注册广播
4、添加接收短信权限

下面放上具体的代码

activity_main.xml文件用于显示短信发送者号码和显示短信内容

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/sms_from"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:text="From" />
    <TextView
        android:id="@+id/sms_from_txt"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:layout_marginLeft="15dp"
        android:layout_toRightOf="@id/sms_from"/>
    <TextView
        android:id="@+id/sms_content"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:layout_below="@id/sms_from"
        android:layout_marginTop="20dp"
        android:text="Content" />
    <TextView
        android:id="@+id/sms_content_txt"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="20dp"
        android:layout_below="@id/sms_from_txt"
        android:layout_toRightOf="@id/sms_content"/>
</RelativeLayout>

MainActivity.java文件

public class MainActivity extends AppCompatActivity {
    private TextView fromTv;
    private TextView contentTv;

    private IntentFilter intentFilter;
    private MessageReceiver messageReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        getSms();
    }

    private void getSms() {
        intentFilter = new IntentFilter();                                 intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        messageReceiver = new MessageReceiver();
        //设置较高的优先级
        intentFilter.setPriority(100);
        registerReceiver(messageReceiver, intentFilter);
    }

    private void initView() {
        fromTv = (TextView) findViewById(R.id.sms_from_txt);
        contentTv = (TextView) findViewById(R.id.sms_content_txt);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(messageReceiver);
    }

    class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            //提取短信消息
            Object[] pdus = (Object[]) bundle.get("pdus");
            SmsMessage[] messages = new SmsMessage[pdus.length];
            for (int i = 0; i < messages.length; i++) {
                messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            }
            //获取发送方号码
            String address = messages[0].getOriginatingAddress();

            String fullMessage = "";
            for (SmsMessage message : messages) {
                //获取短信内容
                fullMessage += message.getMessageBody();
            }
            //截断广播,阻止其继续被Android自带的短信程序接收到
            abortBroadcast();
            fromTv.setText(address);
            contentTv.setText(fullMessage);
        }
    }
}

注:注册的广播接收器,一定要在OnDestroy()方法中取消注册。

由于短信广播是有序广播,如果我们不想让Android自带的短信程序接收到短信,就可以设置我们自身接收器的优先级,同时在我们接受完广播后将广播截断,阻止其被Android自带的短信程序接收到。

二、发送短信

1、获取接收者的号码和短信内容
2、获得短信发送管理实例
3、构造PendingIntent启动短信发送状态监控广播
4、调用发送短信函数,传入参数发送短信
5、构造广播接收器内部类监控短信是否发送成功
6、获得广播接收器实例和IntentFilter实例,注册广播接收器
7、在onDestroy()中取消注册的广播接收器
8、在AndroidManifest.xml文件中加入短信发送权限

下面放上具体的布局文件和代码

activity_send_msg.xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/to_ed"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:hint="to"/>
    <EditText
        android:id="@+id/to_content"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@id/to_ed"
        android:hint="content"/>
    <Button
        android:id="@+id/send_msg"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@id/to_content"
        android:text="@string/send_message"/>
</RelativeLayout>

SendMsgActivity.java文件

public class SendMsgActivity extends AppCompatActivity implements View.OnClickListener {
    private Context context;
    private EditText toEdit;
    private EditText toContent;
    private IntentFilter sendFilter;
    private SendStatusReceiver sendStatusReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_msg);
        context = this;
        initView();
    }

    private void initView() {
        toEdit = (EditText) findViewById(R.id.to_ed);
        toContent = (EditText) findViewById(R.id.to_content);
        //添加发送按钮的点击监听事件
        Button sendMsg = (Button) findViewById(R.id.send_msg);
        sendMsg.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.send_msg:
                sendMessage();
             break;
            default:
                break;
        }
    }

    private void sendMessage() {
        //获取短信接收者号码
        String to = toEdit.getText().toString();
        //获取发送短信内容
        String content = toContent.getText().toString();
        //获得广播接收器实例和IntentFilter实例
        sendStatusReceiver = new SendStatusReceiver();
        sendFilter = new IntentFilter();
        sendFilter.addAction("SENT_SMS_ACTION");
        //注册广播监听
        registerReceiver(sendStatusReceiver, sendFilter);
        //构造PendingIntent启动短信发送状态监控广播
        Intent sendIntent = new Intent("SENT_SMS_ACTION");
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, sendIntent, 0);
        //获得短信管理实例
        SmsManager smsManager = SmsManager.getDefault();

        //调用发送短信函数,传入参数发送短信(第一、三、四参数依次为接收者号码,短信内容,短信发送状态监控的PendingIntent)
        smsManager.sendTextMessage(to, null, content, pi, null);
    }

    /**
     * 构造广播接收器内部类监控短信是否发送成功
     */
    class SendStatusReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if (getResultCode() == RESULT_OK){
                Toast.makeText(context, "successful", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(context, "failed", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册的广播
        unregisterReceiver(sendStatusReceiver);
    }
}

在AndroidManifest.xml文件中加入短信发送权限

<uses-permission android:name="android.permission.SEND_SMS"/>
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Android接收短信,可以使用 BroadcastReceiver。以下是一个简单的示例: 1. 创建一个类来扩展 BroadcastReceiver: ``` public class SmsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // 在此处处理接收到的短信 } } ``` 2. 在 AndroidManifest.xml 文件中注册 BroadcastReceiver: ``` <uses-permission android:name="android.permission.RECEIVE_SMS" /> <application> <receiver android:name=".SmsReceiver"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver> </application> ``` 3. 在 onReceive() 方法中处理接收到的短信: ``` @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) { Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); if (pdus != null) { for (Object pdu : pdus) { SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu); String messageBody = smsMessage.getMessageBody(); String phoneNumber = smsMessage.getOriginatingAddress(); // 在此处处理短信内容和发送者号码 } } } } } ``` 请注意,要接收短信,您需要在 AndroidManifest.xml 文件中声明 RECEIVE_SMS 权限。此外,从 Android 4.4 KitKat 开始,只有默认短信应用程序才能接收到 SMS_RECEIVED 意。如果您的应用程序不是默认短信应用程序,则可以使用 SMS Retriever API 来接收短信

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值