android 无法使用Flutter上的电话包发送SMS

sbdsn5lh  于 2023-01-28  发布在  Android
关注(0)|答案(2)|浏览(146)

我一直在尝试写一个简单的flutter代码,并尝试使用电话发送短信。通过默认的短信应用程序发送短信可以工作(telephony. sendSmsByDefaultApp()),但不能直接从应用程序发送。
我的代码如下:

import 'package:flutter/material.dart';
import 'package:telephony/telephony.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              sendSMS();
            },
            child: Text("Send SMS"),
          ),
        ),
      ),
    );
  }

  void sendSMS() async {
    final Telephony telephony = Telephony.instance;
    bool? permissionsGranted = await telephony.requestPhoneAndSmsPermissions;
    print(permissionsGranted);

    await telephony.sendSms(to: "+92xxxxxxxxxx", message: "Hello, this is a test message.");
    print("SMS Sent");
  }
}

我已添加以下必需权限

<uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
mqkwyuun

mqkwyuun2#

您是否尝试过将ElevatedButton()中的onPressed()函数更改为async函数:

ElevatedButton(
    onPressed: () async {
      await sendSMS();
    },
    child: Text("Send SMS"),
  )

然后将sendSMS()函数更改为返回Future<void>,而不是void:

Future<void> sendSMS() async {
    final Telephony telephony = Telephony.instance;
    bool? permissionsGranted = await telephony.requestPhoneAndSmsPermissions;
    print(permissionsGranted);

    await telephony.sendSms(to: "+92xxxxxxxxxx", message: "Hello, this is a test message.");
    print("SMS Sent");
  }
 }

相关问题