android广播监听接收和发送短信

来源:互联网 发布:怎么删除淘宝评价管理 编辑:程序博客网 时间:2024/04/30 01:02

源码下载地址:http://download.csdn.net/detail/kwunyamshan/9699158

接收短信

效果图

这里写图片描述

1.接收广播

/** * @author idulc */public class ReceiverSms extends BroadcastReceiver {    /**     * 以BroadcastReceiver接收SMS短信     */    public static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";    @Override    public void onReceive(Context context, Intent intent) {        if (ACTION.equals(intent.getAction())) {            Intent i = new Intent(context, MainActivity.class);            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);            SmsMessage[] msgs = getMessageFromIntent(intent);            StringBuilder sBuilder = new StringBuilder();            if (msgs != null && msgs.length > 0) {                for (SmsMessage msg : msgs) {                    sBuilder.append("接收到了短信:\n发件人是:");                    sBuilder.append(msg.getDisplayOriginatingAddress());                    sBuilder.append("\n------短信内容-------\n");                    sBuilder.append(msg.getDisplayMessageBody());                    i.putExtra("sms_address", msg.getDisplayOriginatingAddress());                    i.putExtra("sms_body", msg.getDisplayMessageBody());                }            }            Toast.makeText(context, sBuilder.toString(), Toast.LENGTH_SHORT).show();            context.startActivity(i);        }    }    public static SmsMessage[] getMessageFromIntent(Intent intent) {        SmsMessage retmeMessage[] = null;        Bundle bundle = intent.getExtras();        Object pdus[] = (Object[]) bundle.get("pdus");        retmeMessage = new SmsMessage[pdus.length];        for (int i = 0; i < pdus.length; i++) {            byte[] bytedata = (byte[]) pdus[i];            retmeMessage[i] = SmsMessage.createFromPdu(bytedata);        }        return retmeMessage;    }}

2.清单文件

 <!--接收短信权限-->    <uses-permission android:name="android.permission.RECEIVE_SMS"/>  <!--接收短信的广播-->        <receiver android:name="receiver.ReceiverSms">            <intent-filter >                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>            </intent-filter>        </receiver>

3.页面展示

/** * @author idulc */public class MainActivity extends Activity {    private TextView textView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView = (TextView) findViewById(R.id.textView1);        Intent intent = getIntent();        if (intent != null) {            String address = intent.getStringExtra("sms_address");            if (address != null) {                textView.append("发件人:\n" + address);                String bodyString = intent.getStringExtra("sms_body");                if (bodyString != null) {                    textView.append("\n短信内容:\n" + bodyString);                }            }        }    }}

4.layout

<?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"    android:background="@mipmap/bg"    android:padding="15dp">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="vertical" >        <TextView            android:background="@drawable/item_bg"            android:id="@+id/textView1"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:singleLine="false"            android:paddingLeft="30dip"            android:paddingTop="20dip"            android:paddingBottom="20dip"            android:paddingRight="20dip"            android:hint="短信内容:"            android:textSize="20sp"            android:textColor="#000" />    </LinearLayout></LinearLayout>

发送短信两种方式

效果图

这里写图片描述

  1. ui:
/** * @author idulc */public class SendSmsActivity extends Activity {    private static final String TAG = "SendSmsActivity";    //your phone    private String phone = "5554";    private String message = "Good things come to those who smile. Have you smiled today? Keep smiling. --好事情总是发生在那些微笑着的人身上。你今天微笑了么?保持微笑哦";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_sendsms);    }    /**     * 点击直接发送短信     *     * @param view     */    public void sendSmsAuto(View view) {        sendSms1(phone, message);    }    /**     * 点击调用系统短信     *     * @param view     */    public void sendSmsNoAuto(View view) {        sendSms2(phone, message);    }    /**     * 直接调用短信接口发短信     *     * @param phoneNumber     * @param message     */    public void sendSms1(String phoneNumber, String message) {        if (phoneNumber != null) {            //获取短信管理器            SmsManager smsManager = SmsManager.getDefault();            //拆分短信内容(手机短信长度限制)            List<String> divideContents = smsManager.divideMessage(message);            Log.i(TAG, divideContents.size() + "");            for (String text : divideContents) {                //destinationAddress:目标电话号码                //scAddress:短信中心号码,测试可以不填                //text: 短信内容                //sentIntent:发送 -->中国移动 --> 中国移动发送失败 --> 返回发送成功或失败信号 --> 后续处理   即,这个意图包装了短信发送状态的信息                //处理返回的发送状态                String SENT_SMS_ACTION = "SENT_SMS_ACTION";                Intent sentIntent = new Intent(SENT_SMS_ACTION);                PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sentIntent,                        0);                //deliveryIntent: 发送 -->中国移动 --> 中国移动发送成功 --> 返回对方是否收到这个信息 --> 后续处理  即:这个意图包装了短信是否被对方收到的状态信息(供应商已经发送成功,但是对方没有收到)。                String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";                Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);                PendingIntent deliverPI = PendingIntent.getBroadcast(this, 0,                        deliverIntent, 0);                /* 如果不需要广播监听成功发送的事件 sentPI 和 deliverPI 可传null  ,可以注释掉76行-86行  */                smsManager.sendTextMessage(phoneNumber, null, text, sentPI, deliverPI);            }        } else {            Toast.makeText(this, "联系人号码不能为空", Toast.LENGTH_SHORT).show();        }    }    /**     * 调起系统发短信功能     *     * @param phoneNumber     * @param message     */    public void sendSms2(String phoneNumber, String message) {        if (PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)) {            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));            intent.putExtra("sms_body", message);            startActivity(intent);        }    }}

2.layout

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:padding="20dip"    android:background="@mipmap/bg"    android:layout_height="match_parent">    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="第一种方式"        android:onClick="sendSmsAuto"        />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="第二种方式"        android:onClick="sendSmsNoAuto"        /></LinearLayout>

3.注册广播

/** * @author idulc */public class SendSms extends BroadcastReceiver {    private static final String TAG = "SendSms";    @Override    public void onReceive(Context context, Intent intent) {        try {    /* android.content.BroadcastReceiver.getResultCode()方法 */            switch (getResultCode()) {                /* 发送短信成功 */                case Activity.RESULT_OK:                    Log.d(TAG,  "发送短信成功");                    break;                /* 表示普通错误 */                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:                /*表示无线广播被明确地关闭*/                case SmsManager.RESULT_ERROR_RADIO_OFF:                /*表示没有提供pdu*/                case SmsManager.RESULT_ERROR_NULL_PDU:                default:                    Log.d(TAG,  "发送短信失败");                    break;            }        } catch (Exception e) {            e.getStackTrace();        }    }}

4.清单文件

<!--发短信权限-->    <uses-permission android:name="android.permission.SEND_SMS"/>    <uses-permission android:name="android.permission.READ_SMS"/><!--发送短信的广播-->        <receiver android:name=".receiver.SendSms">            <intent-filter >                <action android:name="SENT_SMS_ACTION"/>                <action android:name="DELIVERED_SMS_ACTION"/>            </intent-filter>        </receiver>
包目录结构:

这里写图片描述

2 0