美文网首页
React-Native 获取设备信息, Android获取IE

React-Native 获取设备信息, Android获取IE

作者: 有情怀的程序猿 | 来源:发表于2017-04-05 14:59 被阅读0次
简单介绍

获取设备信息, 使用的是 react-native-device-info
获取IMEI码参考了react-native-imei源码

关于引入上面的依赖, 链接中都有说明,
算了还是说一遍吧:

**注意: ** 这里只说 Android 的配置步骤, IOS请去链接中查看

1: 获取设备信息 react-native-device-info (不包括IMEI)
  • 1: 安装依赖:
npm install --save react-native-device-info 
  • 2: 配置文件:
    • 1:在文件 android/app/build.gradle:
      dependencies {
        ...
           compile "com.facebook.react:react-native:+"  // From node_modules
         +   compile project(':react-native-device-info')
      

    }

    - 2: 在文件 `in android/settings.gradle:`
    
    ...
    include ':app'
    + include ':react-native-device-info'
    
    • project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android')
    - 3: 在文件 `android/app/src/main/java/com/XXX(项目名称)/MainApplication.java:`
    
      + import com.learnium.RNDeviceInfo.RNDeviceInfo;
    
      public class MainApplication extends Application implements ReactApplication {
      //......
    
      @Override
      protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
    
    •     new RNDeviceInfo(),
          new MainReactPackage()
      );
      
      }

    ......
    }

    
    - 4: 如果你想获取设备的名字: 在 文件: `android/app/src/main/AndroidManifest.xml`
    
    ...
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    
    
    
    
  • 3: 配置完成,运行

1: 从新 react-native run-android 你的项目, 也许会有点慢,
如果报错为: can not deleted ............., 请重新运行几次 react-native run-android

  • 4: 使用方法:
var DeviceInfo = require('react-native-device-info');
</Text>: {DeviceInfo.getUniqueID()} </Text>
</Text> :{DeviceInfo.getInstanceID()}</Text>

其他方法见 react-native-device-info

获取后的设备信息
2: react-native-imei 获取手机IMEI码
  • 1: 安装依赖:
     npm install --save react-native-imei
    
  • 2: 配置文件
    • 在文件 android/app/src/main/AndroidManifest.xml
      <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    
  • 3: 自动配置:
      react-native link react-native-imei
    
  • 4: 使用:
import { NativeModules, Text, View,} from 'react-native';

export default class TestDeviceInfo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      IMEI: '未获取',
    }
  }

  // 由于是异步获取 , 这里使用 async  ... await更改为同步, 不然获取始终为underfind
  async getIMEI() {
    let IMEI =  await NativeModules.IMEI.getIMEI()
    this.setState({
      IMEI: IMEI,
    })
  }

  componentDidMount() {
    this.getIMEI()
  }
  render() {
      return (
        <View>
              <Text style={styles.instructions}>
                <Text style={{color: '#0366d6'}}> 'IMEI(IMEI码)'</Text>: {this.state.IMEI}
              </Text>
        </View>
      );
    }
}

相关文章

网友评论

      本文标题:React-Native 获取设备信息, Android获取IE

      本文链接:https://www.haomeiwen.com/subject/pmmtattx.html