React Native 獲取裝置資訊
一、獲取方案
使用開源的第三方元件react-native-device-info,該元件適用於iOS和Android雙平臺。
二、元件使用
在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