• AndroidStudio给Unity打jar包


    环境:

    AndroidStudio2.0

    Unity4.68


    AS打jar包

    新建空工程

    删除无用的MainActivity等。

    新建Module

    Module选择Android Library,起名为unitylib

    向Module中引入Unity的classes.jar


    不同版本unity   classes.jar的位置
    ...........Unity468EditorDataPlaybackEnginesandroidplayer eleasein
    ...........Unity53EditorDataPlaybackEnginesAndroidPlayerVariationsmonoReleaseClasses


    把unity classes.jar直接放入新建module文件下的libs中

    把classes.jar引入,具体过程为

    选择unitylib,点击+号,确定引入了classes.jar后点击ok保存,退出Project Structure界面


    想删除新建的module,需要在ProjectStructure中先点-号,然后回到把unitylib delete调,然后在回到工程中把unitylib整个delete掉

    打包内容填写

    这里要打包一个MainActivity,所以在module中新建一个MainActivity.java



    MainActivity内容为

    package com.n.unitylib;
    
    import android.app.Activity;
    import android.content.res.Configuration;
    import android.graphics.PixelFormat;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.KeyEvent;
    import android.view.MotionEvent;
    import android.view.Window;
    import android.view.WindowManager;
    
    import com.unity3d.player.UnityPlayer;
    
    public class MainActivity extends Activity {
    
        protected UnityPlayer mUnityPlayer;		// don't change the name of this variable; referenced from native code
    
        // Setup activity layout
        @Override protected void onCreate (Bundle savedInstanceState)
        {
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            super.onCreate(savedInstanceState);
    
            getWindow().takeSurface(null);
            getWindow().setFormat(PixelFormat.RGBX_8888); // <--- This makes xperia play happy
    
            mUnityPlayer = new UnityPlayer(this);
            if (mUnityPlayer.getSettings ().getBoolean ("hide_status_bar", true))
                getWindow ().setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    
            setContentView(mUnityPlayer);
            mUnityPlayer.requestFocus();
        }
    
        // Quit Unity
        @Override protected void onDestroy ()
        {
            mUnityPlayer.quit();
            super.onDestroy();
        }
    
        // Pause Unity
        @Override protected void onPause()
        {
            super.onPause();
            mUnityPlayer.pause();
        }
    
        // Resume Unity
        @Override protected void onResume()
        {
            super.onResume();
            mUnityPlayer.resume();
        }
    
        // This ensures the layout will be correct.
        @Override public void onConfigurationChanged(Configuration newConfig)
        {
            super.onConfigurationChanged(newConfig);
            mUnityPlayer.configurationChanged(newConfig);
        }
    
        // Notify Unity of the focus change.
        @Override public void onWindowFocusChanged(boolean hasFocus)
        {
            super.onWindowFocusChanged(hasFocus);
            mUnityPlayer.windowFocusChanged(hasFocus);
        }
    
        // For some reason the multiple keyevent type is not supported by the ndk.
        // Force event injection by overriding dispatchKeyEvent().
        @Override public boolean dispatchKeyEvent(KeyEvent event)
        {
            if (event.getAction() == KeyEvent.ACTION_MULTIPLE)
                return mUnityPlayer.injectEvent(event);
            return super.dispatchKeyEvent(event);
        }
    
        // Pass any events not handled by (unfocused) views straight to UnityPlayer
        @Override public boolean onKeyUp(int keyCode, KeyEvent event)     { return mUnityPlayer.injectEvent(event); }
        @Override public boolean onKeyDown(int keyCode, KeyEvent event)   { return mUnityPlayer.injectEvent(event); }
        @Override public boolean onTouchEvent(MotionEvent event)          { return mUnityPlayer.injectEvent(event); }
        /*API12*/ public boolean onGenericMotionEvent(MotionEvent event)  { return mUnityPlayer.injectEvent(event); }
    
    
        public static void Test()
        {
            Log.e("nafio","success!");
        }
    }
    

    AndroidManifest.xml内容为

    <?xml version="1.0" encoding="utf-8"?>
    <manifest
        xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.n.unitylib"
        android:installLocation="preferExternal"
        android:versionCode="1"
        android:versionName="1.0">
        <supports-screens
            android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:xlargeScreens="true"
            android:anyDensity="true"/>
    
        <application
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
            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" />
                    <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
                </intent-filter>
                <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
                <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="false" />
            </activity>
        </application>
    </manifest>



    配置gradle打包参数

    在module的build.gradle最后添加

    task makeJar(type: Copy) {
        delete 'build/libs/unitylib.jar'
        from('build/intermediates/bundles/release/')
        into('build/libs/')
        include('classes.jar')
        rename('classes.jar', 'unitylib.jar')
    }
    
    makeJar.dependsOn(build)


    打jar包

    然后在Terminal中输入gradlew makejar

    第一次运行Androidstudio可能会更新gradle,20-30分钟,更新完会自动打jar包


    jar包位置在



    android调试module

    module用来打包,如果要调试

    把module中的build.gradle中

    apply plugin: 'com.android.library'
    改为
    apply plugin: 'com.android.application'

    然后同步下gradle module就是普通工程了




    Unity调用

    新建空工程
    在Assets下新建Plugins/Android/
    把打出的unitylib.jar和对应的AndroidManifest.xml(这个从哪copy都可以,单独写都可以,只要内容对就行)

    新建脚本,随便挂一个节点上
    using UnityEngine;
    using System.Collections;
    
    public class TestAS : MonoBehaviour {
    	private AndroidJavaObject _java;
    	public AndroidJavaObject Java
    	{
    		get
    		{
    			if (_java == null)
    			{
    				var javaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    				_java = javaClass.GetStatic<AndroidJavaObject>("currentActivity");
    			}
    			return _java;
    		}
    	}
    	// Use this for initialization
    	void Start () {
    		Debug.Log("nafio-----START");
    		Java.CallStatic("Test");
    		Debug.Log("nafio-----END");
    	}
    	
    	// Update is called once per frame
    	void Update () {
    	
    	}
    }
    


    打包时注意一点,包名保持跟jar包中的包名一致(如果jar包中包含的不是主Acticity,而是其他java类,应该不一致也可以)


    打apk出来,运行输出  android中写的log  
     Log.e("nafio","success!");



    遇到问题记录

    Lint found errors in the project; aborting build


    解决办法
    文件build.gradle,添加如下信息
    android {
       lintOptions {
           abortOnError false
       }
    }

  • 相关阅读:
    开篇之作
    瀑布流特效
    随写
    关于冒泡排序的补充
    New start-开始我的学习记录吧
    java中序列化的简单认识
    我的Python之路
    算法学习笔记
    Leaflet个人封装笔记
    反射获取config实体类属性并赋值
  • 原文地址:https://www.cnblogs.com/nafio/p/9137291.html
Copyright © 2020-2023  润新知