Development environment:
Android studio 3.5.2
Unity3d 2020.3.25f1c1
Table of contents
2. Create a new Module and name it test
3. Delete the redundant Moudle app created by default
4. Import the classes.jar of Unity3d
5. Import UnityPlayerActivity.java of Unity3d
8. AndroidMainFest configuration
Android Studio section
1. Create New Project
Create New Project , Empty Activity , package com.example.unity2photo
2. Create a new Module and name it test
Switch to Project, New - Module, Android Library and click Next.
3. Delete the redundant Moudle app created by default
Open Module Settings select the APP point - number, Yes, then Delete.
4. Import the classes.jar of Unity3d
The corresponding location below the Unity3d installation path:
D:\Software\Unity\2020.3.25f1c1\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\mono\Development\Classes
Copy class.jar and paste it under the libs directory, right-click classer.jar - Add As Library
5. Import UnityPlayerActivity.java of Unity3d
D:\Software\Unity\2020.3.25f1c1\Editor\Data\PlaybackEngines\AndroidPlayer\Source\com\unity3d\player
Copy UnityPlayerActivity.java and paste it under src - main- java - com.example.test
6. Create MainActivity
Right-click com.example.test, New –Activity – Empty Activity
7. Java code part
package com.example.test;
import android.Manifest;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.os.Bundle;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.unity_player.UnityPlayerActivity;
public class MainActivity extends UnityPlayerActivity{
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
// @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 获取存储权限,不然的话无法获取图片
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
}
}
// unity点击按钮触发这个方法
public void startPhoto() {
Log.d("unity","打开相册");
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 111); // 第二个参数是请求码
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 111: // 请求码
Log.d("Unity", "相册返回");
UnityPlayer.UnitySendMessage("Main Camera", "message", parseUri(data));
Log.d("unity", parseUri(data));
break;
}
}
}
public String parseUri(Intent data) {
Uri uri = data.getData();
String imagePath;
// 第二个参数是想要获取的数据
Cursor cursor = getContentResolver()
.query(uri, new String[]{MediaStore.Images.ImageColumns.DATA},
null, null, null);
if (cursor == null) {
imagePath = uri.getPath();
} else {
cursor.moveToFirst();
// 获取数据所在的列下标
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
imagePath = cursor.getString(index); // 获取指定列的数据
cursor.close();
}
return imagePath; // 返回图片地址
}
}
8. AndroidMainFest configuration
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<application>
<activity android:name="com.example.test.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="unityplayer.UnityActivity" android:value="true" />
</activity>
</application>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
9. Android build aar
10. Import Unity3d
Package and build test_debug.arr, decompress classes.jar to replace libs classes.jar, and then compress into test_debug.arr
Plugins - Android - AndroidMainfest.xml
Plugins - Android - test_debug.arr
Unity3d code part
2 ways to read pictures
1,UnityWebRequestTexture
2. Use file stream to read pictures
void CallAndroid()
{
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("startPhoto");
Debug.Log("点击按钮");
}
public void message(string str)
{
ShowImage(str);
Debug.Log("安卓传来信息:" + str);
//StartCoroutine(LoadTexturePreview("file://" + str));
}
//使用UnityWebRequestTexture读取图片
IEnumerator LoadTexturePreview(string path)
{
UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(path);
yield return uwr.SendWebRequest();
Debug.Log("图片地址:" + path);
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.Log("错误" + uwr.error);
}
else
{
Texture2D texture = DownloadHandlerTexture.GetContent(uwr);
// 图片显示在按钮上
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(.5f, .5f));
ImageView.sprite = sprite;
}
}
//使用文件流读取图片
private void ShowImage(string path)
{
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
fileStream.Seek(0, SeekOrigin.Begin);
byte[] bye = new byte[fileStream.Length];
fileStream.Read(bye, 0, (int)bye.Length);
fileStream.Close();
fileStream.Dispose();
fileStream = null;
Texture2D texture = new Texture2D(100, 50);
texture.LoadImage(bye);
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
ImageView.sprite = sprite;
}
final display
Complete project source code
Including: Unity3d reads the mobile phone photo album, unity opens the mobile phone camera, saves pictures, etc.
expand
Packaging APK error
Solution:
The classpath in build.gralde refers to the gradle plugin version of Android Studio.
'com.android.tools.build:gradle:3.5.2'
And the distributionUrl in gradle-wrapper.properties is the specified gradle version!
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
Gradle is an open source automated build tool, and the Gradle plugin is a plugin developed by Google for using Gradle in Android Studio.
Reference URL:
Unity Gradle Build
Unity Gradle Build - Brief Book
Intent.ACTION_PICK
Intent.ACTION_PICK - Time is just right, - Blog Garden
Unity automatic packaging - Android Studio - detailed explanation of build.gradle
Unity Automatic Packaging-Android Studio-build.gradle Detailed Explanation- Programmer Sought