Unity Android Open the album and camera

Source: https://blog.csdn.net/qweewqpkn/article/details/84141614

 

Requirements: To achieve open the phone's camera and photo album, select photos or pictures, in unity.

 

1.android plugins
I use is AndroidStuido to write plug-ins, the following is a step by step introduction process

(1) create android project

 

 

 

 

Note the red box inside things, to modify two places:

1. com.android.application changed com.android.library

2. applicationId "com.niko.myunityplugin" deleted

 

 

Delete these two directories do not need them

 

(2) Join us to rely on the unity of the jar package in its path:

C:\Program Files\Unity5.6.4p3\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\mono\Release\Classes

 

Then he put under the libs directory under our android project, as shown below:

 

At this time also let engineering know it's there, so we have to:

 

 

 

Note: The red box is selected Compile only, rather than Implemetation, reason for this choice is that finally we packed out aar file will not contain this jar package, if Implemetation will put the jar into the final break out of the pack aar we have to manually delete, or we fight Apk time to be wrong, because the unity of the jar with its own package.

 

We removed the following red box of stuff we do not need them:

 

 

At this point we have succeeded in this jar is added to the project, since you can use it inside the interface, and then began to write code

 

(3) write plugin code

package com.niko.myunityplugin;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import static android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION;
import static android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

public class MainActivity extends UnityPlayerActivity {

private static final int TAKE_PHOTO = 1;
private static final int OPEN_GALLERY = 2;
private static final int CROP_PHOTO = 3;
private Uri mPhotoUri;
private Uri mCropPhotoUri;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}

public void TakePhoto(){
mPhotoUri = GetUri(CreateFile("temp.png"));
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
startActivityForResult(intent, TAKE_PHOTO);

}

//调用相册
public void OpenGallery()
{
Intent intent = new Intent(Intent.ACTION_PICK,null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(intent, OPEN_GALLERY);
}

private Uri GetUri(File file)
{
Uri uri;
if(Build.VERSION.SDK_INT >= 24)
{
uri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", file);
}
else
{
uri = Uri.fromFile(file);
}

return uri;
}

private File CreateFile(String name)
{
File file = new File(Environment.getExternalStorageDirectory(), name);
try
{
if(file.exists())
{
file.delete();
}
file.createNewFile();
}catch(IOException e)
{
e.printStackTrace();
}

return file;
}

private void StartCrop(Uri inputUri)
{
mCropPhotoUri = Uri.fromFile(CreateFile("tempCrop.png"));

Intent intent = new Intent("com.android.camera.action.CROP");
intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(FLAG_GRANT_WRITE_URI_PERMISSION);
intent.setDataAndType(inputUri, "image/*");
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("scale", true);
intent.putExtra("return-data", false);
intent.putExtra("noFaceDetection", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCropPhotoUri);
startActivityForResult(intent, CROP_PHOTO);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode == Activity.RESULT_CANCELED)
{
Log.d("unity","user cancel operator!!");
return;
}

switch (requestCode)
{
case TAKE_PHOTO:
{
StartCrop(mPhotoUri);
}
break;
case OPEN_GALLERY:
{
Uri uri = data.getData();
StartCrop(uri);
}
break;
case CROP_PHOTO:
{
try
{
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mCropPhotoUri));
FileOutputStream fOut = null;

try
{
String path = "/mnt/sdcard/Android/data/com.niko.myunityplugin/files";
File destDir = new File(path);
if(!destDir.exists())
{
destDir.mkdirs();
}

fOut = new FileOutputStream(path + "/" + "image.png");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}

if(bitmap != null)
{
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}

UnityPlayer.UnitySendMessage("UnityPlugin","OnGetPhoto", "image.png");
}
}
the catch (a FileNotFoundException E)
{
e.printStackTrace ();
}
}
BREAK;
}
}
}
After the addition of the above code, you will find that there is an error in which, as shown:

 

Lack of information means that this class, we will this time to introduce the corresponding jar package it, and then we open build.gradle file, as shown below to add a new jar references.

 

After adding engineering we click the sync button, so that the project began to pack down from a remote repository to download the jar, as shown:

 

Once you have downloaded, then we would not have given the project

 

(4) Modify AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.niko.myunityplugin">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.niko.myunityplugin.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
</application>

<!-- 连接互联网的权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
 

(5) increase the xml file, as shown:

 

provider_paths.xml contents are:

<? XML Version = "1.0" encoding = "UTF-. 8"?>
<Paths xmlns: Android = "http://schemas.android.com/apk/res/android">
<External path-name = "external_files" . "" path = />
</ Paths>
may be happy to start compiling the project, as shown in the following figure compiled:

 

Two red boxes of things, is the need to go inside the copy to unity. Here we have to write plug-in is complete, the next there is unity began to call.

 

2.Unity call plug-in
settings (1) Environment

The compiler just put something out as shown in the directory:

 

 

 

Android plugin package name of the package name to be here and we can set up the same.

 

(2) to write code

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TestPlugin : MonoBehaviour
{
public Button mBtnCamera;
public Button mBtnGallery;
public RawImage mImage;
public Text mText;
private Action<byte[]> mPhotoAction;

// Use this for initialization
void Start()
{
mBtnCamera.onClick.AddListener(() =>
{
TakePhoto((datas) =>
{

});
});

mBtnGallery.onClick.AddListener(() =>
{
OpenGallery((datas) =>
{

});
});
}

public void TakePhoto(Action<byte[]> callback)
{
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("TakePhoto");
mPhotoAction = callback;
}

public void OpenGallery(Action<byte[]> callback)
{
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("OpenGallery");
mPhotoAction = callback;
}

void OnGetPhoto(string name)
{
StartCoroutine(LoadPhoto(name));
}

IEnumerator LoadPhoto(string name)
{
MText.text = name;
String path = "File: //" + Application.persistentDataPath + "/" + name;
the WWW new new WWW = the WWW (path);
the yield return WWW;
mImage.texture = www.texture;
IF ( ! mPhotoAction = null)
{
mPhotoAction (((the Texture2D) mImage.texture) .EncodeToPNG ());
mPhotoAction = null;
// the Destroy (Texture);
}
}
}
script linked to the object of a scene, and then the associated button pictures and text, as shown:

Note the red line: Because after taking a picture to be displayed at unity here, we give unity message, because the message the name of the object code for android is UnityPlugin, so we are here to modify the UnityPlguin.

 

 

Then start packing apk on it, I do not have the packaging process errors, after we play apk installation and operation, Congratulations, will run a flash back, ha ha ha ha. Error Figure:

 

 

Means that we lack the information android.support.v4.content.FileProvider this class, eh? Not before we add the library to the android project do? Why is being given, I put this question before the pit for a long time, checked online, said that the android engineering package, will not be packaged with the apk jar package to our in, so there is lost, but how we jar package in order to get this, so he packed it in to my apk? Here is the solution:

 

Find the wrong class package, then we hold down ctrl + left mouse button to cut into this category,

 

Then we put the mouse on this tab, you can know which package it belongs to, as shown:

 

His path shown in Figure, which is android studio for us to download from a remote repository down dependencies, this path is the source of the package, we need to compile the jar package, which we can find in the path as shown:

 

 

 

 

ok, well we found the jar package, we will copy it out, and changed its name to: support-core-utils-26.1.0-sources.jar, libs before we put down android project directory, as shown:

 

 

Let the project know the existence of this jar, and add that method jar package before it, the results shown:

 

 

We removed the remote repository before the dependent packages, to avoid duplication, re-synchronize it. At this point we recompile the library

 

With this you can see the need to rely on the jar package under this package libs directory aar, well, we can repackage the Apk. After packing everything you, you can take pictures.

 

Finally, the source address: source point my friends

Note: This package is the name of the source code used in another, and here I explain the different, here is my explanation of the reconstruction project to give you an illustration.
----------------
Disclaimer: This article is CSDN blogger "monk_CD 'original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement. .
Original link: https: //blog.csdn.net/qweewqpkn/article/details/84141614

 

 

Guess you like

Origin www.cnblogs.com/LiTZen/p/11899508.html