在本教程中,我分享了如何在没有用户交互的情况下发送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”)),
),
);
}
}