安卓开发:接收与发送短信

本文介绍了如何在Android应用中实现短信的接收与发送功能,涉及到使用广播接收器这一核心组件。通过示例代码,展示了权限申请、ListView显示短信、界面布局以及关键的Activity和BroadcastReceiver的使用。在跳转界面时需注意控件重新获取、取消广播注册等要点。

接收与发送短信都需要用到安卓的四大组件:广播接收器。如果不太了解广播,可以参考此文:点击参考

实现的效果如下:
这里写图片描述

整个工程目录如下:
这里写图片描述

利用了ListView控件来显示短信,对ListView不太了解,可以参考此文:点击参考

首先,为我们的app在AndroidMainfest.xml中申请权力:

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/>

用于读取与接收短信。

显示短信:
item.xml:

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

    <TextView
        android:id="@+id/from"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="15sp" />

    <TextView
        android:id="@+id/blank"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#000000"
        android:textSize="1sp" />

</LinearLayout>

activity_read.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.aiden.myapplication.MainActivity">

    <Button
        android:id="@+id/send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送短信" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>
</LinearLayout>

发送短信:
activity_send.xml:

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

    <Button
        android:id="@+id/read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查看短信" />

    <EditText
        android:id="@+id/to"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="to"
        android:textSize="20sp" />

    <EditText
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="content" />

    <Button
        android:id="@+id/dosend"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送短信"
        android:textSize="15sp" />
</LinearLayout>

上述的三个xml界面都很好理解。
我们写显示短信的类,包括了两个属性:from【发送者】和content【内容】

/**
 * Created by Aiden on 2016/2/24.
 */
public class Detail {
    private String from;
    private String content;

    public Detail(String from, String content) {
        this.from = from;
        this.content = content;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getFrom() {
        return from;
    }

    public String getContent() {
        return content;
    }
}

也就是定义了from和content的get和set方法。

MainActivity.java:

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.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements View.OnClickListener {
    // 用于查看短信
    private List<Detail> list = new ArrayList<Detail>();
    private ListView listView;
    private MyAdapter myAdapter;
    private IntentFilter reveiceFilter;
    private MessageReceiver messageReceiver;

    private Button send; // 跳转到发送短信的按钮
    private Button read; // 跳转到查看短信的按钮


    // 用于发送短信
    private EditText content;
    private EditText to;
    private Button dosend;
    private IntentFilter sendFilter;
    private SendReceiver sendReceiver;

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

        send = (Button) this.findViewById(R.id.send); // 用于跳转到发送短信的界面
        send.setOnClickListener(this);

        // 获得适配器
        myAdapter = new MyAdapter(this, R.layout.item, list);
        // 为ListView设置适配器
        listView = (ListView) this.findViewById(R.id.listView);
        listView.setAdapter(myAdapter);

        reveiceFilter = new IntentFilter(); // 接收短信的广播
        reveiceFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        messageReceiver = new MessageReceiver();
        this.registerReceiver(messageReceiver, reveiceFilter);

        sendFilter = new IntentFilter(); // 发送短信的广播
        sendFilter.addAction("SENT_SMS_ACTION");
        sendReceiver = new SendReceiver();
        this.registerReceiver(sendReceiver, sendFilter);
    }

    class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 得到短信的内容
            Bundle bundle = intent.getExtras();
            Object[] objects = (Object[]) bundle.get("pdus");
            SmsMessage[] smsMessages = new SmsMessage[objects.length];
            for (int i = 0; i < smsMessages.length; i++)
                smsMessages[i] = SmsMessage.createFromPdu((byte[]) objects[i]);
            String from = smsMessages[0].getOriginatingAddress();
            String content = new String();
            for (SmsMessage smsMessage : smsMessages)
                content += smsMessage.getMessageBody();
            // 刷新视图
            Detail detail = new Detail(from, content);
            list.add(detail);
            myAdapter.notifyDataSetChanged();
        }
    }

    class SendReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 得到发送短信的结果
            int result = this.getResultCode();
            if (result == RESULT_OK)
                Toast.makeText(MainActivity.this, "发送短信成功", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(MainActivity.this, "发送短信失败", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onClick(View v) {
        if (v == send) { // 跳转到发送短信的界面
            // 重新得到控件
            this.setContentView(R.layout.activity_send);
            read = (Button) this.findViewById(R.id.read);
            read.setOnClickListener(this);
            to = (EditText) this.findViewById(R.id.to);
            content = (EditText) this.findViewById(R.id.content);
            dosend = (Button) this.findViewById(R.id.dosend);
            dosend.setOnClickListener(this);

            this.registerReceiver(sendReceiver, sendFilter);
            this.unregisterReceiver(messageReceiver);
        } else if (v == read) { // 跳转到短信列表
            this.setContentView(R.layout.activity_read);
            send = (Button) this.findViewById(R.id.send);
            send.setOnClickListener(this);

            // 获得适配器
            myAdapter = new MyAdapter(this, R.layout.item, list);
            // 为ListView设置适配器
            listView = (ListView) this.findViewById(R.id.listView);
            listView.setAdapter(myAdapter);

            this.registerReceiver(messageReceiver, reveiceFilter);
            this.unregisterReceiver(sendReceiver);
        } else if (v == dosend) { // 发送短信
            Intent intent = new Intent("SENT_SMS_ACTION");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(to.getText().toString(), null, content.getText().toString(), pendingIntent, null);
        }
    }
}

这样一个简单的接收与发送短信的app就形成了。
需要注意的:
1、在界面跳转的时候,是调用了setContentView()方法。也就意味着,之前得到的控件都失效了,我们要重新获取一次
2、在界面跳转的时候,需要调用unregisterReceiver()方法,用于取消接收广播,不然会报“Are you missing a call to unregisterReceiver()?“的错误
3、在注册广播的时候,一定要加上意图(如:SENT_SMS_ACTION或者是android.provider.Telephony.SMS_RECEIVED)界面一定重新布局,要重新注册广播

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值