一、获取方案
使用开源的第三方组件react-native-device-info,该组件适用于iOS和Android双平台。
npm地址:https://www.npmjs.com/package/react-native-device-info
二、组件使用
在ReactNative项目中下载第三方组件依赖包, 我们一般都是使用命令行来执行下载:
进入项目执行:npm install –save react-native-device-info 或者 yarn add react-native-device-info
2.1 iOS端:
(1)首先在xcode中进行初始化
打开xcode,找到自己的项目->Libraries文件夹,选择Add Files to '项目名',然后找到当前项目目录/node_modules/react-native-device-info文件夹,找到'RNDe'viceInfo.xcodeproj'文件,然后点击Add.
(2)再在xcode中加载内库
找到项目名字 ----> Build Phases ---> Link Binary With Libraries, 点击‘+’按钮,添加‘libRNDeviceInfo.a’库。
(2)继续添加环境变量
(SRCROOT)/../react-native/Reactand
(SRCROOT)/../../React
并修改recursive.
2.2 Android端:
(1)首先需要修改下Gradle文件
在项目根目录下运行命令react-native link react-native device-info即可,成功了会增加如下两行代码:
(1)在MainActivity.java文件中进行注册模块(react-native的版本需要>0.18)
import com.learnium.RNDeviceInfo.RNDeviceInfo; // <— import
public class MainActivity extends ReactActivity {
……
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List getPackages() {
return Arrays.asList(
new RNDeviceInfo(), // <—— add here
new MainReactPackage());
}
}
(1)如果你需要在安卓上获取设备的名字,需要修改AndroidMainfest.xml配置文件,来获取权限。
在android设备中获取以下权限: uses-permission android:name=”android.permission.BLUETOOTH”
三、基本用法
Examples
const apiLevel = DeviceInfo.getAPILevel();
// iOS: ?
// Android: 25
// Windows: ?
四、API
参考链接:https://www.npmjs.com/package/react-native-device-info