【Unity】调用安卓相机及相册

2024-04-08 1375阅读

其实网上的文章都很详细比如文章1(http://www.voidcn.com/article/p-ehdfbrsl-nh.html )文章2(http://www.voidcn.com/article/p-ehdfbrsl-nh.html )。 其实实现过程都大同小异,我们主要来看我遇到得的问题,当然这些问题都是在6.0以上的版本出现的问题,之前的都没有。

安卓6.0以上获取摄像机权限

在最开始我们在AndroidManifest.xml文件中添加获取相机权限,如下

 

然后运行程序第一次并没有提示我获得相机权限,然后再点击打开相机闪退,妈耶。然后就查资料说,相机这类权限属于危险级,需要动态请求。所以这里就开始编写动态请求,网上蛮多文章说这个的,大多都需要使用其他什么插件得的。官方给出的代码:

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {
    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {
        // Show an expanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    } else {
        // No explanation needed, we can request the permission.
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);
        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}

更多详细的可以看看官网文档(https://developer.android.com/training/permissions/requesting)。 这里用的ActivityCompat是使用的Android.support.v4的架包。所以导入unity后我们还需要导入这个架包不然的话会报错。看有文章说这个架包在安卓SDK的目录下可以找到,目录: AndroidSDK/extras/android/m2repository/com/android/support/support-v4

里面有很多版本的,移到unity中,没有用,还是报错!!!可能是我用的版本不对。这里我使用的是之前接GooglePlay的SDK里面的架包。加进去了没有报错了。但是·······

【Unity】调用安卓相机及相册

点击打开相机出来了,选择权限框,但是是闪现的。对就是闪现的。

【Unity】调用安卓相机及相册

权限闪现

没办法,查了很久,然后看unity官方文档(Unity - Manual: Android App Manifest ) 中说的是需要再加一个设置到AndroidManifest里,加在Application之间或者Activity即可。

 

因为unity本身是不支持动态权限系统。同时我又看到一个玄学答案,在你的代码里加入这个:

/// 
/// 无用方法,用来打开摄像头权限
/// 
/// 
private IEnumerator OpenCameraPermisson()
{
    yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
    if (!Application.HasUserAuthorization(UserAuthorization.WebCam)) yield break;
    WebCamDevice[] devices = WebCamTexture.devices;
}

这两个是我一起加的好像都有效果,调用webcam时unity会自动提示你打开相机权限。就这样解决了问题。

在动态获取权限那个地方修改了一下写法,不太想使用其他的架包啥的,我的写法是:

//先检测权限
public void OpenTakePhoto() {
    if (Build.VERSION.SDK_INT > 22) {
        if (this.checkSelfPermission(android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //先判断有没有权限 ,没有就在这里进行权限的申请
            this.requestPermissions(
                    new String[]{android.Manifest.permission.CAMERA}, CAMERA_OK);
        } else {
            TakePhoto();
        }
    } else {
        TakePhoto();
    }
}

简单点的说就是把ActivityCompat替换成当前的Activity就可以。这样就可以不使用support.v4架包。

相机打开闪退

对的,你没看错。不过这个很快就解决了。这个问题出现的原因主要是由于在Android 7.0以后,用了Content Uri 替换了原本的File Uri,故在targetSdkVersion=24的时候,部分 “Uri.fromFile()“方法就不适用了。 File Uri 与 Content Uri 的区别 - File Uri 对应的是文件本身的存储路径 - Content Uri 对应的是文件在Content Provider的路径 所以在android 7.0 以上,我们就需要将File Uri转换为 Content Uri。这里写一个转化的方法:

/**
 * 转换 content:// uri
 * 7.0以后使用
 *
 * @param imageFile
 * @return
 */
public Uri getImageContentUri(File imageFile) {
    String filePath = imageFile.getAbsolutePath();
    Cursor cursor = getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            new String[]{MediaStore.Images.Media._ID},
            MediaStore.Images.Media.DATA + "=? ",
            new String[]{filePath}, null);
    if (cursor != null && cursor.moveToFirst()) {
        int id = cursor.getInt(cursor
                .getColumnIndex(MediaStore.MediaColumns._ID));
        Uri baseUri = Uri.parse("content://media/external/images/media");
        return Uri.withAppendedPath(baseUri, "" + id);
    } else {
        if (imageFile.exists()) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, filePath);
            return getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        } else {
            return null;
        }
    }
}

然后再打开相机的地方做一个选择:

//打开相机
private void TakePhoto() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        File outFile = new File(UnityUsePicturePath);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, getImageContentUri(outFile));
    } else {
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(UnityUsePicturePath)));
    }
    startActivityForResult(intent, PHOTOHRAPH);
}

存储权限问题

这里我们需要添加存储的权限

 

我们可以在打开相册的时候检测一下,动态请求一下。

代码

我把java代码写成了Activity类,然后我们直接在unity中的调用传入参数即可:

    //获得照片
    public void GetPhoto(GetPhotoType photoType, bool isCutPicture = false)
    {
        var strType = Enum.GetName(typeof(GetPhotoType), photoType);
        AndroidJavaObject intentObject = new AndroidJavaObject("android.content.Intent", unityActivity, gallerySdk);
        intentObject.Call("putExtra", "type", strType);
        intentObject.Call("putExtra", "UnityPersistentDataPath", Application.persistentDataPath);
        intentObject.Call("putExtra", "isCutPicture", isCutPicture);
        unityActivity.Call("startActivity", intentObject);
        Debug.Log("GetPhoto Android startActivity");
    }

这样我们就可以不需要重新写AndroidManifest了,只需要在其中申明一下Activity即可:

        
        
           
            false
            true
        

其他的看一下源码就可以了。很简单。

java代码

unity 代码

AndroidManifest

示例代码

void OnGUI()
{
    if (GUILayout.Button("Take Photo", GUILayout.Width(200), GUILayout.Height(200)))
    {
        GalleryManager.Instance.GetPhoto(GetPhotoType.Carmera, (texture) => { rawImage.texture = texture; });
    }
    if (GUILayout.Button("Open Gallery", GUILayout.Width(200), GUILayout.Height(200)))
    {
        GalleryManager.Instance.GetPhoto(GetPhotoType.Gallery, (texture) => { rawImage.texture = texture; });
    }
    if (GUILayout.Button("Show Image", GUILayout.Width(200), GUILayout.Height(200)))
    {
        StartCoroutine(GetImageByPath(Application.persistentDataPath + "/UNITY_GALLERY_PICTUER.png"));
    }
}

效果图

【Unity】调用安卓相机及相册

【Unity】调用安卓相机及相册

【Unity】调用安卓相机及相册

参考文章:

http://www.voidcn.com/article/p-ehdfbrsl-nh.html
Unity3D研究院之打开照相机与本地相册进行裁剪显示(三十三) | 雨松MOMO程序研究院
Android 复制单个文件到指定目录,Android copy file-CSDN博客

权限:
android相机权限适配遇到的坑(包含6.0和6.0以下) - 简书
Android6.0动态获取摄像头权限(举一反三)_android 动态获取前置摄像头权限-CSDN博客
Unity - Manual: Android App Manifest
Android7.0及以上打开相机闪退,startActivityForResult报错解决_android startactivityforresult 报anrerror-CSDN博客

【Unity】调用安卓相机及相册

 

VPS购买请点击我

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

目录[+]