Android开发:如何实现收发短信

1、收发短信代码如下:

public class MsmUtils extends BroadcastReceiver {

    /**
     * 发送 MSM
     * @param activity
     * @param targetNumber
     * @param content
     */
    public static void sendMsm(Activity activity, String targetNumber, String content) {
        //创建一个PendingIntent对象
        PendingIntent pi = PendingIntent.getActivity(activity, 0, new Intent(), 0);
        //获取SmsManager
        SmsManager sManager = SmsManager.getDefault();
        //发送短信
        sManager.sendTextMessage(targetNumber, null, content, pi, null);
    }

    /**
     * 接收到新MSM
     * @param context
     * @param intent
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        SmsMessage smsMessage;
        if (null != bundle) {
            Object[] smsObj = (Object[]) bundle.get("pdus");
            for (Object object : smsObj) {
                smsMessage = SmsMessage.createFromPdu((byte[]) object);
                String content = smsMessage.getDisplayMessageBody();
                String from = smsMessage.getOriginatingAddress();
                //Do your coding here
            }
        }
    }
}

2、在AndroidManifest.xml中声明以下权限:

<!-- 授予发送短信的权限 -->
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 授予接收短信的权限 -->
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />

3、若在AndroidManifest.xml中声明权限后,运行时仍出现缺少权限的错误,则可在Activity中动态请求权限(如果只需要发送短信,则只需要请求发送所需的权限,其他同理),如下:

ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.SEND_SMS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.RECEIVE_SMS}, 1);
展开阅读全文

没有更多推荐了,返回首页