【问题标题】:How to send SMS programatically in React Native with phone credit如何在 React Native 中使用电话信用以编程方式发送 SMS
【发布时间】:2021-06-03 10:06:21
【问题描述】:

我正在寻找一种在 React Native 中以编程方式发送 SMS 而不使用 Twilio 或 Firebase 等 3rd 方 API 的方法。我的目的是在我的 中使用电话积分/可用通话时间>SIM 卡

【问题讨论】:

    标签: react-native smsmanager


    【解决方案1】:

    我从以下链接中找到了解决方案,但由于原始 wa 在编译期间出现错误,因此对其进行了一些编辑:

    注意:此解决方案要求您使用 Native Java 代码模块扩展您当前的 React Native 代码库。但不要让这吓到你。

    链接:Sending Direct SMS In React-Native Android by Fateme Fazli

    第 1 步:创建 SendSMSModule.java

    进入您的 android/app/src/main/java/com/your_project_name 文件夹以创建 DirectSmsModule.java 模块,使用以下 Java 代码。

    //DirectSmsModule.java  : This is the name of the Java Class/File   
    package com.your_project_name; //make sure to change to your project's actual name.
    
    import com.facebook.react.bridge.ReactApplicationContext;
    import com.facebook.react.bridge.ReactContextBaseJavaModule;
    import com.facebook.react.bridge.Callback;
    import com.facebook.react.bridge.ReactMethod;
    import com.facebook.react.uimanager.IllegalViewOperationException;
    import android.telephony.SmsManager;  //++ make sure this package is available always
     
    public class DirectSmsModule extends ReactContextBaseJavaModule {
     
        public DirectSmsModule(ReactApplicationContext reactContext) {
            super(reactContext); //required by React Native
        }
     
        @Override
        //getName is required to define the name of the module represented in JavaScript
        public String getName() { 
            return "DirectSms";
        }
     
        @ReactMethod
        public void sendDirectSms(String phoneNumber, String msg) {
            try {      
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(phoneNumber, null, msg, null, null);    
                System.out.println("message sent successfully.");
            } catch (Exception ex) {
                System.out.println("couldn't send message.");
            } 
        }
    }
    

    第 2 步:创建 DirectSmsPackage.java 模块

    在同一个文件夹 android/app/src/main/java/com/your_project_name 中,您现在可能有 3 个 Java 文件,添加第 4 个:DirectSmsPackage.java

    //DirectSmsPackage.java
    package com.your_project_name;
    
    import com.facebook.react.ReactPackage;
    import com.facebook.react.bridge.NativeModule;
    import com.facebook.react.bridge.ReactApplicationContext;
    import com.facebook.react.uimanager.ViewManager;
    import com.enoxscanner.DirectSmsModule; // enoxscanner should be replaced with your own package name
     
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
     
    public class DirectSmsPackage implements ReactPackage {
     
        @Override
        public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
            return Collections.emptyList();
        }
     
        @Override
        public List<NativeModule> createNativeModules(
                ReactApplicationContext reactContext) {
            List<NativeModule> modules = new ArrayList<>();
            //this is where you register the module
            modules.add(new DirectSmsModule(reactContext));
            return modules;
        }
    }
    

    第 3 步:注册 DirectSmsPackage

    现在注册我们刚刚在上面创建的模块。这与添加或安装后必须手动链接的软件包几乎相同。

    在同一文件夹中,找到您的 MainApplication.java 文件并找到以下代码部分,然后添加突出显示为 添加此行的行:注意,您正在编辑getPackages() function

    @Override
            protected List<ReactPackage> getPackages() {
              @SuppressWarnings("UnnecessaryLocalVariable")
              List<ReactPackage> packages = new PackageList(this).getPackages();
              // Packages that cannot be autolinked yet can be added manually here, for example:
              // packages.add(new MyReactNativePackage());
    
              packages.add(new DirectSmsPackage()); //++ add this line here ++
              return packages;
            }
    

    第 4 步:在您的 RN 脚本中调用 sendDirectSMS

    import React, { Component } from 'react';
    import { NativeModules, PermissionsAndroid } from 'react-native'; 
    
    //++ import NativeModules since we are using a Native external module
    ...
    
    const DirectSms = NativeModules.DirectSms;
    
    export class SMSScreen extends Component {
    
    sendDirectSms = async () => {
            try {
                const granted = await PermissionsAndroid.request(
                    PermissionsAndroid.PERMISSIONS.SEND_SMS,
                    {
                        title: 'Tadiwanashe App Sms Permission',
                        message:
                            'Tadiwanashe App needs access to your inbox ' +
                            'so you can send messages in background.',
                        buttonNeutral: 'Ask Me Later',
                        buttonNegative: 'Cancel',
                        buttonPositive: 'OK',
                    },
                );
                if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                    DirectSms.sendDirectSms('0772......', 'This is a direct message from your app.');
                } else {
                    console.log('SMS permission denied');
                }
            } catch (err) {
                console.warn(err);
            }
        }
    
        render() {
            return (
                <View style={styles.mother_container}>
                    <View style={styles.container}>
                        <TextInput secureTextEntry={true} style={styles.input}
                            underlineColorAndroid="transparent"
                            placeholder="Enter PIN."
                            placeholderTextColor="black"
                            autoCapitalize="none"
                            onChangeText={this.handlePIN}
                            textAlign={'center'}
                        />
                        <TouchableOpacity
                            style={styles.button}
                            onPress={() => this.sendDirectSms()}>
                            <Text style={styles.submitButtonText} selectTextOnFocus={true}> Submit </Text>
                        </TouchableOpacity>
                    </View>
                    <AppFooter bgColor='#fff' textColor='grey' />
                </View>
            )
        }
    }
    
    export default SMSScreen ;
    

    注意:

    • Google 可能不允许此类自动发送 SMS 的应用程序。
    • 在您的应用程序获得授权之前,您不会收到短信 用户,因此我们导入了 PermissionsAndroid。
    • 上面的链接将为您提供对大部分内容的正确解释 细节,这不完全是我的工作,而是简单地进行了相应的编辑 在意识到文章的原始代码有一些 错误,以及文章驻留在一个平台上 与 SO 相比,很难做出适当的贡献。

    【讨论】:

    • 感谢 Huey 的参考 ;)
    • 请问你用的是哪个安卓版本?它对我不起作用,根本没有错误。只是不工作
    • 我试过了,它正在工作,但是当我尝试使用冗长的消息时它不起作用。知道如何解决吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    相关资源
    最近更新 更多