React Native Bridge从React Native应用程序发送短信

React Native Bridge从React Native应用程序发送短信

这是 React Native Bridge 示例,用于从 React Native 应用程序发送直接短信。 我们会看到

  • 什么是 React Native Bridge?
  • 如何创建一个桥梁来使用您的本机代码?

为了理解这个概念,我们将创建一个短信发送应用程序,它将触发本机代码直接发送消息。 我们已经创建了一个在单击按钮时发送文本短信的示例,但它之间有一个手动干预来发送许多读者不想要的消息。 因此,我一直在寻找任何无需用户交互或无需打开手机消息应用程序即可发送消息的解决方案。

最后,我们决定通过使用原生 Android 功能来发送直接消息来做到这一点。 考虑一下,在 iOS 上,如果没有用户交互,您就无法发送短信。

推荐:如何在Debian 12/11 Linux中安装Podman

什么是 React Native Bridge?

要使用原生 Android 功能,我们必须使用 React Native Bridge 概念。 React Native 的开发方式使得我们可以在 Native 语言和 JavaScript 代码之间建立一座桥梁。 桥只不过是在本机平台和 React Native 之间建立通信的一种方式。

为什么我们需要 React Native Bridge?

如果我们想重用一些现有的 Java 代码或库,而不必在 JavaScript 中重新实现它,或者我们想要一个只能在本机代码中实现的自定义功能,那么我们必须使用 React Native Bridge。 在我过去的 React Native 开发经验中,我多次使用过这个 React Native Bridge,作为一名 React Native 开发人员,你在某个时候也会需要这种东西。 那么让我们看看如何将本机代码集成到 React Native 应用程序中。

在 React Native 中构建应用程序时,我们可以使用属性和回调来驱动我们的应用程序。 但是,当我们混合使用 React Native 和原生组件时,我们需要一些特定的跨语言机制来允许我们在它们之间传递信息。 React Native 提供了 原生模块 对于相同的。

什么是本机模块?

本机模块只是一组针对各个平台本机实现的 JavaScript 函数。 当 React Native 还没有所需的模块,或者本机性能明显更好时,可以使用本机模块。

为了更好地理解这个概念,我们将实施一些东西。 正如我所说,很多人问我如何从 React Native 应用程序发送直接消息,因此我决定在 React Native 桥接概念中包含相同的内容。

从 React Native 应用程序发送直接短信

在此示例中,我们将编写一些本机 Java 代码来从 Android 应用程序发送短信,并从 React Native 触发相同的短信。 示例将有一个简单的屏幕,有 2 个输入,一个用于手机号码,一个用于短信正文。 一旦您在插入手机号码(包括零(0))和短信正文后点击“发送消息”,我们将传递本机代码中的值,并触发本机代码直接发送短信。 希望你会喜欢。

制作 React Native 应用程序

React Native 入门将帮助您更多地了解如何制作 React Native 项目。 我们将使用 React Native 命令行界面来制作我们的 React Native 应用程序。

如果您之前安装了全局的react-native-cli软件包,请将其删除,因为它可能会导致意外问题:

npm uninstall -g react-native-cli @react-native-community/cli

运行以下命令创建一个新的 React Native 项目

npx react-native init ProjectName

如果你想使用特定的 React Native 版本启动一个新项目,你可以使用 –version 参数:

npx react-native init ProjectName --version X.XX.X

注意如果上述命令失败,您可能使用的是旧版本 react-native 或者 react-native-cli 在您的电脑上全局安装。 尝试卸载 cli 并使用 npx 运行 cli。

这将在项目目录中创建一个带有名为 App.js 的索引文件的项目结构。

Java 本机代码

1.创建MySendSmsModule.java

android/app/src/main/java/com/yourProject 旁边的 MainActivity.java 创建一个扩展 ReactContextBaseJavaModule 类的 java 类并粘贴以下代码。 请记住将包名称“com.basebridgingexample”更改为您的包名称。 您可以在顶部找到包名称 MainActivity.java

package com.basebridgingexample;
 
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;

public class MySendSmsModule extends ReactContextBaseJavaModule {
 
    public MySendSmsModule(ReactApplicationContext reactContext) {
        //required by React Native
        super(reactContext);
    }
 
    @Override
    //getName is required to define the name of the module
    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
            );
        } catch (Exception ex) {
            System.out.println("couldn't send message.");
        } 
    }
}

ReactContextBaseJava模块 需要一个名为 获取名称 其目的是返回在 javascript 中表示此类的 NativeModule 的字符串名称。

@ReactMethod 用于在 javascript 中公开函数,因为所有函数都不会显式地公开给 JavaScript。 这些方法有 空白 返回类型。

发送直接短信 是我们将在react-native javascript代码中调用的函数来发送直接短信。

2.创建MySendSmsPackage.java

Java 的下一步是注册模块,如果模块未注册,则 JavaScript 将无法使用该模块。 为了注册创建的模块,在 MySendSmsModule.java 旁边创建一个新类,名称为 MySendSmsPackage.java 并粘贴以下代码。 请记住将包名称“com.basebridgingexample”更改为您的包名称。

package com.basebridgingexample;
 
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.basebridgingexample.MySendSmsModule;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class MySendSmsPackage 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 MySendSmsModule(reactContext));
        return modules;
    }
}

我们重写 创建NativeModule 功能并添加 我的短信发送模块 对象到模块数组。 需要在此处添加它才能在 javascript 中使用。

3. 在中注册MySendSmsPackage 主应用程序.java

多于 我的发送短信套餐 需要提供在 获取包 的方法 主应用程序.java 文件。 只需导入 我的发送短信套餐 并添加 反应包。 请查看下面示例中的“// Add This Line”注释。

package com.basebridgingexample;

import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import com.basebridgingexample.MySendSmsPackage;  // Add This Line

public class MainApplication extends
  Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost =
      new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        @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 MySendSmsPackage()); // Add This Line
          return packages;
        }

        @Override
        protected String getJSMainModuleName() {
          return "index";
        }
      };
    .........
    .........
    .........
    .........
}

安卓权限

要从 Android 发送短信,您需要添加以下权限 AndroidManifest.xml

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

遵循上述步骤后,您将获得以下结构。

React Native Bridge从React Native应用程序发送短信

反应本机代码

如果一切顺利,那么您就可以使用本机模块了。 要在 React Native 中使用此本机代码,只需导入 原生模块 组件形式反应原生

import { NativeModules } from 'react-native';

初始化您的自定义本机组件

let DirectSms = NativeModules.DirectSms;

并使用它

DirectSms.sendDirectSms(mobileNumber, bodySMS);

让我们看看 React Native 代码来触发我们的本机代码。

现在在任何代码编辑器中打开 App.js 并将代码替换为以下代码

应用程序.js

// React Native Bridge Example to Send Direct SMS from React Native App
// https://aboutreact.com/react-native-bridge-send-direct-sms-from-react-native-app/

// import React in our code
import React, {useState} from 'react';

// import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  TextInput,
  NativeModules,
  PermissionsAndroid,
} from 'react-native';

var DirectSms = NativeModules.DirectSms;

const App = () => {
  // Setting up States
  const (mobileNumber, setMobileNumber) = useState('');
  const (bodySMS, setBodySMS) = useState(
    'Please follow https://aboutreact.com',
  );

  // async function to call the Java native method
  const sendDirectSms = async () => {
    if (mobileNumber) {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.SEND_SMS,
          {
            title: 'Send SMS App Sms Permission',
            message:
              'Send SMS 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(mobileNumber, bodySMS);
          alert('SMS sent');
        } else {
          alert('SMS permission denied');
        }
      } catch (error) {
        console.warn(error);
        alert(error);
      }
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.container}>
        <Text style={styles.titleText}>
          React Native Bridge Example for Android to Send Direct SMS
        </Text>
        <Text style={styles.titleTextsmall}>
          Enter Recipients Number
        </Text>
        <TextInput
          value={mobileNumber}
          onChangeText={
            (mobileNumber) => setMobileNumber(mobileNumber)
          }
          placeholder={'Enter Conatct Number to Call'}
          keyboardType="numeric"
          style={styles.textInput}
        />
        <Text style={styles.titleTextsmall}>
          Enter SMS Body
        </Text>
        <TextInput
          value={bodySMS}
          onChangeText={(bodySMS) => setBodySMS(bodySMS)}
          placeholder={'Enter SMS body'}
          style={styles.textInput}
        />
        <TouchableOpacity
          activeOpacity={0.7}
          style={styles.buttonStyle}
          onPress={sendDirectSms}>
          <Text style={styles.buttonTextStyle}>
            Send Message
          </Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    padding: 10,
    textAlign: 'center',
  },
  titleText: {
    fontSize: 22,
    textAlign: 'center',
    fontWeight: 'bold',
    marginBottom: 16,
  },
  titleTextsmall: {
    marginVertical: 8,
    fontSize: 16,
  },
  buttonStyle: {
    justifyContent: 'center',
    marginTop: 15,
    padding: 10,
    backgroundColor: '#8ad24e',
  },
  buttonTextStyle: {
    color: '#fff',
    textAlign: 'center',
  },
  textInput: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    width: '100%',
    paddingHorizontal: 10,
  },
});

export default App;

运行 React Native 应用程序

再次打开终端并使用跳转到您的项目。

cd ProjectName

1. 启动 Metro Bundler

首先,您需要启动 Metro,React Native 附带的 JavaScript 捆绑器。 要启动 Metro 捆绑程序,请运行以下命令

npx react-native start

一旦您启动 Metro Bundler,它将永远在您的终端上运行,直到您将其关闭。 让 Metro Bundler 在自己的终端中运行。 打开一个新终端并运行该应用程序。

2.启动React Native应用程序

在 Android 虚拟设备或真实调试设备上运行项目

npx react-native run-android

或在 iOS 模拟器上运行(仅限 macOS)

npx react-native run-ios

输出截图

ReactNativeBridgeDirectSMS1 ReactNativeBridgeDirectSMS2 ReactNativeBridgeDirectSMS3 ReactNativeBridgeDirectSMS4

这是从 React Native 应用程序发送直接短信的 React Native Bridge 示例。 如果您有任何疑问或想分享有关该主题的内容,您可以在下面发表评论或在此处联系我们。 

推荐:修复Windows 10/11 PlayerUnknown’s Battlegrounds TslGame.exe错误


发表评论