在本教程中,我分享了如何在没有用户交互的情况下发送SMS。实际上,要以编程方式发送SMS,您需要实现一个平台通道并使用SMSManager发送SMS。
首先,向AndroidManifest.xml添加适当的权限。
1
|
<uses–permission android:name=“android.permission.SEND_SMS” />
|
然后在您的MainActivity.java中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
package com.yourcompany.example;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
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”,“”);
}
}
}
|
飞镖代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
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”)),
),
);
}
}
|