關於ImagePicker在android調用不起攝像頭的解決辦法

一、起因

app調用了 'react-native-image-crop-picker' ,發現在ios下調起攝像頭/相冊功能正常,但是在安卓下無法調起攝像頭。

react-native 版本:0.60.5

原代碼引入:

import ImagePicker from 'react-native-image-crop-picker';

// 調起攝像頭
ImagePicker.openCamera({
                         width: 300,
                         height: 300,
                         cropping: true
                       }).then(image => {
                         if (image && image.path) {
                           this.uploadHeadIcon(image.path); //上傳頭像的函數
                          };
                       }).catch(e => console.log(e));

// 調起相冊
ImagePicker.openPicker({
                         width: 300,
                         height: 300,
                         cropping: true
                       }).then(image => {
                         if (image && image.path) {
                            this.uploadHeadIcon(image.path)
                         }
                       }).catch(e => console.log(e));

ios直接像上面這樣引入就沒有問題(當然yarn和pod install 是必須做的),但安卓會出現攝像頭無法調起的情況

二、解決方法

1. 檢查android/build.gradle 文件,是否有下面代碼。

allprojects {
    repositories {
      mavenLocal()
      jcenter()
      maven { url "$rootDir/../node_modules/react-native/android" }
 
      // ADD THIS
      maven { url 'https://maven.google.com' }
 
      // ADD THIS
      maven { url "https://jitpack.io" }
    }
}

2. 增加useSupportLibrary權限,檢查android/app/build.gradle

android {
    ...
 
    defaultConfig {
        ...
        vectorDrawables.useSupportLibrary = true
        ...
    }
    ...
}

3. 檢查 Android SDK >= 26 (android/app/build.gradle)

4. 如果要調起攝像頭,檢查 app\src\main\AndroidManifest.xml

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

5. 如果要用前置攝像頭

<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />

6. 到這裏,上面的配置都正確,就可以調起安卓攝像頭了。其實上面步驟npm包都有寫,但是導入的時候不會仔細去檢查每一步,所以寫篇文章記錄一下。

參考:https://www.npmjs.com/package/react-native-image-crop-picker

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章