這2天在研究unity調用android原生的java代碼,由於對android開發不熟悉,一切都是從頭開始學。最開始連通過搜索引擎要用什麼關鍵字都不知該如何概括(現在知道了,即:android plugin for unity)。。。我使用的android開發工具是android studio,但是在網上搜的一大把文章都是用eclipse作爲開發工具,它和android studio的一些配置方面差別還是挺大,因此有了這篇文章,記錄下我這個小白的研究過程,也供新手參考。
如果是eclipse開發環境的話,可以參考http://www.xuanyusong.com/archives/667
系統環境
先介紹下我的一些系統環境。
OS:win7 64位
android SDK:最小SDK 4.0.3,API版本14;最大SDK5.0.1,API版本21。
創建一個andriod studio工程
step1:
step2:
step3:
step4:
經過上面4個步驟,就可以創建一個新的android studio工程。
而我的環境報錯,如下圖所示:
可以修改Gradle Scripts下的build.gradle文件,將dependencies域下的compile 'com.android.support:appcompat-v7:23.0.1'修改爲compile 'com.android.support:appcompat-v7:21.0.3',並且resync一下。具體原因可以百度。
切換下android studio中project的顯示視圖,由Android切換到Project,如下圖:
將unity的jar作爲庫加入到android studio
定位到你的unity安裝目錄下的C:\Program Files (x86)\Unity\Editor\Data\PlaybackEngines\androidplayer\release\bin,裏面又一個Classes.jar文件,複製它,把把粘貼到TestPlugin/app/libs文件夾下,然後右擊Classes.jar,點擊 Add as Library,如下圖所示。
這樣我們就可以在android studio中使用com.unity3d.player中的內容,比如com.unity3d.player.UnityPlayerActivity了。
如果按照上面的步驟執行的話,這時候你的TestPlugin/app/build.gradle應該如下:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.freedom.testplugin"
minSdkVersion 15
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile files('libs/classes.jar')
}
編寫android原生接口
修改MainActivity.java文件的內容爲:
package com.freedom.testplugin;
import android.content.Intent;
import com.unity3d.player.UnityPlayerActivity;
public class MainActivity extends UnityPlayerActivity {
public void shareText(String subject, String body) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
}
shareText就是接口函數了,到時候可以在unity中的C#腳本中直接調用它。
使用build.gradle導出jar作爲unity的plugin
修改TestPlugin/app/build.gradle文件爲:
//indicates that this is a library
apply plugin: 'com.android.library'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
sourceSets {
main {
//Path to your source code
java {
srcDir 'src/main/java'
}
}
}
defaultConfig {
minSdkVersion 15
targetSdkVersion 21
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
lintOptions {
abortOnError false
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile files('libs/classes.jar')
}
//task to delete the old jar
task deleteOldJar(type: Delete) {
delete 'release/AndroidPlugin.jar'
}
//task to export contents as jar
task exportJar(type: Copy) {
from('build/intermediates/bundles/release/')
into('release/')
include('classes.jar')
///Rename the jar
rename('classes.jar', 'AndroidPlugin.jar')
}
exportJar.dependsOn(deleteOldJar, build)
sync一下。
這時候打開android studio右邊的Gradle控制檯,並refresh all gradle projects。
這時候在TestPlugin/TestPlugin/other下會有一個exportJar。
雙擊它,在run窗口下你會看到BUILD SUCCESSFUL提示,則表示生成jar成功。
在project視圖下,你會看到TestPlugin/app/release/下生成了一個AndroidPlugin.jar文件。
這個AndroidPlugin.jar文件就是我們要導入unity中的android原生接口文件。
在unity中調用jar的接口函數
新建一個名爲TestAndroidPlugin的unity工程。在Assets文件夾下建立Plugins文件夾,再在Plugins文件夾下建立Android文件夾,然後將上面的AndroidPlugin.jar文件複製到Assets/Plugins/Android文件夾下。並且把android studio工程下的TestPlugin/app/src/main/AndroidManifest.xml複製到Assets/Plugins/Android文件夾下,並修改該xml文件。
如果不修改文件的話,在unity工程build成apk的時候會報錯,提示:Failed to re-package resources.,即打包資源有錯。
根據錯誤提示我們知道,是icon@mipmap/ic_launcher圖標和theme@style/AppTheme主題找不到資源,因此我們把unity工程中的Assets/Plugins/Android/AndroidManifest.xml文件中的android:icon和android:theme兩個域去掉,則xml文件變爲如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.freedom.testplugin" >
<application
android:allowBackup="true"
android:label="@string/app_name">
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
在unity工程創建C#文件test.cs文件,如下:
using UnityEngine;
using System.Collections;
public class test : MonoBehaviour {
string subject = "TEST";
string body = "TEST ANDROID PLUGIN FOR UNITY";
void OnGUI()
{
if (GUILayout.Button("OPEN Activity", GUILayout.Height(100)))
{
callAndroidApi();
}
}
public void callAndroidApi()
{
AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");
currentActivity.Call("shareText", subject, body);
}
}
保存下場景。最後一步,修改一下Build Settings中的Android的Player Settings中的Bundle Identifier爲Android studio的包名,com.freedom.testplugin。
測試
測試必須是真機測試,在unity editor player是不能測試的,會報錯Exception: JNI: Init'd AndroidJavaClass with null ptr!。
將生成的apk包安裝到測試機上,就可以在unity應用中調用Android原生的接口了,done!
參考文章:http://www.thegamecontriver.com/2015/04/android-plugin-unity-android-studio.html