当前位置:编程学习 > uniapp >>

Uni-App X 短信发送实现方案 安卓发送短信源码

在 Uni-App X 中发送短信可以通过以下几种方式实现,包括调用原生 Android/iOS 能力、使用 Intent 方式以及第三方短信服务。


1. 使用原生能力发送短信 (Android/iOS)
Android 实现
typescript
// 在 uni-app x 中调用原生 Android 短信发送
export function sendSMS(phoneNumber: string, message: string): Promise<boolean> {
  return new Promise((resolve, reject) => {
    if (plus.os.name === 'Android') {
      const main = plus.android.runtimeMainActivity()
      const SmsManager = plus.android.importClass('android.telephony.SmsManager')
      const smsManager = SmsManager.getDefault()
      
      try {
        plus.android.invoke(smsManager, 'sendTextMessage', 
          phoneNumber, null, message, null, null)
        resolve(true)
      } catch (e) {
        reject(e)
      }
    } else {
      reject(new Error('Only supported on Android'))
    }
  })
}
iOS 实现
typescript
// 在 uni-app x 中调用原生 iOS 短信发送
export function sendSMS_iOS(phoneNumber: string, message: string): Promise<boolean> {
  return new Promise((resolve, reject) => {
    if (plus.os.name === 'iOS') {
      const MFMessageComposeViewController = plus.ios.importClass('MFMessageComposeViewController')
      if (MFMessageComposeViewController.canSendText()) {
        const controller = MFMessageComposeViewController.alloc().init()
        controller.recipients = [phoneNumber]
        controller.body = message
        
        const delegate = plus.ios.implement('MFMessageComposeViewControllerDelegate', {
          'messageComposeViewController:didFinishWithResult:': (controller, result) => {
            plus.ios.deleteObject(controller)
            if (result === 1) { // MessageComposeResultSent
              resolve(true)
            } else {
              reject(new Error('Message not sent'))
            }
          }
        })
        
        controller.setMessageComposeDelegate(delegate)
        
        const rootViewController = plus.ios.invoke(
          plus.ios.invoke('UIApplication', 'sharedApplication'),
          'keyWindow',
          'rootViewController'
        )
        
        rootViewController.presentViewControllerAnimatedCompletion(controller, true, null)
      } else {
        reject(new Error('Device cannot send SMS'))
      }
    } else {
      reject(new Error('Only supported on iOS'))
    }
  })

}

节日里朋友之间祝福短信批量发送,如果自己不想撸代码,可以试试这款现成的app,不需要注册码,无限使用!
QQ 7477118 例如我有300多个好友,每次单独发送太麻烦了,就用这个软件自动发,轻松!

qq7477118祝福短信批量发送APP不需要注册码


2. 使用 Intent 方式发送短信 (Android)

typescript
// 使用 Intent 方式发送短信
export function sendSMSViaIntent(phoneNumber: string, message: string): void {
  if (plus.os.name === 'Android') {
    const Intent = plus.android.importClass('android.content.Intent')
    const Uri = plus.android.importClass('android.net.Uri')
    
    const intent = new Intent(Intent.ACTION_SENDTO)
    intent.setData(Uri.parse('smsto:' + phoneNumber))
    intent.putExtra('sms_body', message)
    
    const main = plus.android.runtimeMainActivity()
    main.startActivity(intent)
  } else {
    console.error('Only supported on Android')
  }
}
3. 使用 uni-app 官方 API (仅打开短信界面)
typescript
// 使用 uni-app 官方 API 打开短信界面
export function openSMSApp(phoneNumber: string, message: string): void {
  uni.makePhoneCall({
    phoneNumber: phoneNumber,
    success: () => {
      // 在通话界面可以切换到短信
    },
    fail: (err) => {
      console.error('Failed to open SMS app:', err)
    }
  })
  
  // 或者使用 URL scheme
  // location.href = `sms:${phoneNumber}?body=${encodeURIComponent(message)}`
}
4. 使用第三方短信服务 API
typescript
// 调用第三方短信服务 API
export async function sendSMSViaAPI(phoneNumber: string, message: string): Promise<boolean> {
  try {
    const response = await uni.request({
      url: 'https://your-sms-api-endpoint.com/send',
      method: 'POST',
      data: {
        phone: phoneNumber,
        message: message,
        api_key: 'your_api_key'
      }
    })
    
    return response.statusCode === 200
  } catch (e) {
    console.error('SMS API error:', e)
    return false
  }
}
5. 完整封装示例
typescript
class SMSService {
  /**
   * 发送短信(自动选择最佳方式)
   * @param phoneNumber 手机号码
   * @param message 短信内容
   * @param useIntent 是否使用Intent方式(仅Android)
   */
  static async send(phoneNumber: string, message: string, useIntent: boolean = false): Promise<boolean> {
    if (useIntent && plus.os.name === 'Android') {
      this.sendSMSViaIntent(phoneNumber, message)
      return true
    }
    
    if (plus.os.name === 'Android') {
      return this.sendSMS(phoneNumber, message)
    } else if (plus.os.name === 'iOS') {
      return this.sendSMS_iOS(phoneNumber, message)
    } else {
      // 其他平台使用API或URL scheme
      this.openSMSApp(phoneNumber, message)
      return true
    }
  }
  
  // 包含上面所有方法的静态实现...
}

// 使用示例
SMSService.send('13800138000', '您的验证码是1234').then(success => {
  console.log('短信发送结果:', success)
})
注意事项
Android 权限:需要在 manifest.json 中配置权限

json
{
  "app-plus": {
    "distribute": {
      "android": {
        "permissions": [
          "android.permission.SEND_SMS",
          "android.permission.READ_PHONE_STATE"
        ]
      }
    }
  }
}
iOS 限制:只能通过 MFMessageComposeViewController 发送,需要用户确认

群发限制:Android 系统会限制短时间内大量发送短信,建议:

每条间隔 3-5 秒

每分钟不超过 15 条

大批量发送使用短信 API 服务

厂商适配:部分国产 ROM 可能需要额外权限设置

以上代码提供了在 Uni-App X 中实现短信发送的多种方案,您可以根据实际需求选择最适合的方式。
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,