Flutter:我们如何使用内置消息应用程序使用包发送消息?

时间:2018-03-22 03:01:45

标签: android ios dart flutter

我想从内置的默认消息应用程序发送消息,但我不知道如何使用 dart代码发送消息[ flutter ]

1 个答案:

答案 0 :(得分:1)

实际上,要以编程方式发送短信,您需要实施平台频道并使用SMSManager发送短信。

示例:

Android部分:

首先向AndroidManifest.xml添加适当的权限。

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

然后在MainActivity.java

  public class MainActivity extends FlutterActivity {
  private static final String CHANNEL = "sendSms";

  private MethodChannel.Result callResult;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);
    new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
            new MethodChannel.MethodCallHandler() {
              @Override
              public void onMethodCall(MethodCall call, MethodChannel.Result result) {
                if(call.method.equals("send")){
                   String num = call.argument("phone");
                   String msg = call.argument("msg");
                   sendSMS(num,msg,result);
                }else{
                  result.notImplemented();
                }
              }
            });
  }

  private void sendSMS(String phoneNo, String msg,MethodChannel.Result result) {
      try {
          SmsManager smsManager = SmsManager.getDefault();
          smsManager.sendTextMessage(phoneNo, null, msg, null, null);
          result.success("SMS Sent");
      } catch (Exception ex) {
          ex.printStackTrace();
          result.error("Err","Sms Not Sent","");
      }
  }

}

飞镖码:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(new MaterialApp(
    title: "Rotation Demo",
    home: new SendSms(),
  ));
}


class SendSms extends StatefulWidget {
  @override
  _SendSmsState createState() => new _SendSmsState();
}

class _SendSmsState extends State<SendSms> {
  static const platform = const MethodChannel('sendSms');

  Future<Null> sendSms()async {
    print("SendSMS");
    try {
      final String result = await platform.invokeMethod('send',<String,dynamic>{"phone":"+91XXXXXXXXXX","msg":"Hello! I'm sent programatically."}); //Replace a 'X' with 10 digit phone number
      print(result);
    } on PlatformException catch (e) {
      print(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      child: new Container(
        alignment: Alignment.center,
        child: new FlatButton(onPressed: () => sendSms(), child: const Text("Send SMS")),
      ),
    );
  }
}

refrence link for more detail