Unity 命令打包安装Android Apk

2017-12-23  本文已影响0人  代瑶
image.png

配置好三个环境,否则无法使用cmd命令执行的

package com.myunity;

import net.lingala.zip4j.core.ZipFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

/**
 * Created by Administrator on 2017/12/13.
 */

public class GenerateUnityAAR {

    private static void copyFileTo(String oldFilePath, String newFilePath) {
        File mManifestFile = new File(oldFilePath);
        FileInputStream fisManifest = null;
        try {
            fisManifest = new FileInputStream(mManifestFile);

            FileOutputStream outManifest = new FileOutputStream(new File(newFilePath));

            int count = fisManifest.available();
            byte[] data = new byte[count];
            if ((fisManifest.read(data)) != -1) {
                outManifest.write(data); // 复制文件内容
            }
            outManifest.close(); // 关闭输出流
            fisManifest.close(); // 关闭输入流
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String androidAppPath = "C:\\Users\\MrDai\\Desktop\\myunity\\app\\";
        // FIXKXT: 2017/12/14 Unity Assets-Plugins-Android文件夹目录
        String mUnityAndroidPath = "C:\\Users\\MrDai\\Desktop\\MyUnityDemo\\Assets\\Plugins\\Android";

        try {
            File mAarFile = new File(androidAppPath, "build/outputs/aar/app-debug.aar");

            ZipFile zipFile = new ZipFile(mAarFile);
            zipFile.setFileNameCharset("GBK");
            zipFile.removeFile("libs/classes.jar");
            zipFile.removeFile("libs/zip4j_1.3.2.jar");

            zipFile.extractFile("AndroidManifest.xml", androidAppPath + "/build/outputs/aar/");

            copyFileTo(androidAppPath + "/build/outputs/aar/AndroidManifest.xml", mUnityAndroidPath + "\\AndroidManifest.xml");
            copyFileTo(androidAppPath + "/build/outputs/aar/app-debug.aar", mUnityAndroidPath + "\\app.aar");

            System.out.println("操作AAR成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这段代码放置到android代码中,并添加zip4j的jar,我们在unity一键打包时需要命令执行java编译GenerateUnityAAR文件的


image.png

接下来我们编写Unity代码,在Editor 中创建文件UnityMenu 代码如下


image.png
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using UnityEditor;
using UnityEngine;

public class UnityMenu : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    [MenuItem("Install APP/编译并且安装")]
    private static void startBuild()
    {
        //编译JAVA
        //javac -cp C:\Users\MrDai\Desktop\myunity\app\libs\zip4j_1.3.2.jar -encoding utf-8 -d C:\Users\MrDai\Desktop\myunity\app C:\Users\MrDai\Desktop\myunity\app\src\main\java\com\myunity\GenerateUnityAAR.java
        
        //执行JAVA
        //cd C:\Users\MrDai\Desktop\myunity\app
        //C:
        //java -cp .;C:\Users\MrDai\Desktop\myunity\app\libs\zip4j_1.3.2.jar  com.myunity.GenerateUnityAAR
        string mAndroidPath = "C:\\Users\\MrDai\\Desktop\\myunity\\app\\";//安卓路径
        string mAndroidPf = "C:";//安卓盘符

        string mAndroidJavaFile = "com\\myunity\\GenerateUnityAAR.java";
        string mAndroidClassFile = "com.myunity.GenerateUnityAAR";

        //gradle 编译
        string buildAndroidCmd = " /c cd " + mAndroidPath + " & " + mAndroidPf + "  & gradle clean & gradle assembleDebug";
        UnityEngine.Debug.Log("Gradle build 编译.... " + buildAndroidCmd);
        exeCmd(buildAndroidCmd,true);

        //编译javac
        string moveFileToUnityCmd = " /c javac -cp "
            + mAndroidPath + "\\libs\\zip4j_1.3.2.jar -encoding utf-8 -d  "
            + mAndroidPath + "  "
            + mAndroidPath + "\\src\\main\\java\\"+ mAndroidJavaFile;
        UnityEngine.Debug.Log("java 代码编译.... " + moveFileToUnityCmd);
        exeCmd(moveFileToUnityCmd, true);

        //编译javac
        string runJavaCmd = " /c cd "+ mAndroidPath+ " & java -cp .;"+ mAndroidPath + "\\libs\\zip4j_1.3.2.jar "+ mAndroidClassFile;
        UnityEngine.Debug.Log("java 代码编译.... " + runJavaCmd);
        exeCmd(runJavaCmd, true);

        //打包所有场景
        List<string> lsit = new List<string>();
        foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes)
        {
            if (scene.enabled)
            {
                lsit.Add(scene.path);
            }
        }


        //开始执行代码,各种打包
        string buildOut = BuildPipeline.BuildPlayer(lsit.ToArray(), "Sample.apk", BuildTarget.Android, BuildOptions.None);
        UnityEngine.Debug.Log("buildOut.... " + buildOut);

        string unityApkPath = "C:\\Users\\MrDai\\Desktop\\MyUnityDemo\\Sample.apk";
        exeCmd(" /k adb install -r " + unityApkPath,false);
    }

    private static void exeCmd(string cmdInfo,bool isOpenCmdWin)
    {
        ProcessStartInfo mCmdProcess = new ProcessStartInfo("C:\\Windows\\system32\\cmd.exe");
        mCmdProcess.Arguments = cmdInfo;
        mCmdProcess.CreateNoWindow = isOpenCmdWin;         // 不创建新窗口    
        mCmdProcess.UseShellExecute = true;       //不启用shell启动进程   

        mCmdProcess.RedirectStandardOutput = false; // 重定向标准输出 
        mCmdProcess.RedirectStandardInput = false; // 重定向标准输出    
        mCmdProcess.RedirectStandardError = false;  // 重定向错误输出  

        Process mProcess = Process.Start(mCmdProcess);

        mCmdProcess.StandardOutputEncoding = System.Text.Encoding.GetEncoding("GBK");
        mCmdProcess.StandardErrorEncoding = System.Text.Encoding.GetEncoding("GBK");

        try {
            String myReadInfo = mProcess.StandardOutput.ReadToEnd();
            if (myReadInfo != null) {
                UnityEngine.Debug.Log("Cmd执行.... " + myReadInfo);
            }
        }
        catch (Exception e) {

        }
        mProcess.WaitForExit();
    }
}

在startBuild上配上[MenuItem("Install APP/编译并且安装")]则会在Unity工具任务栏出现Install App选项了

Unity 中创建Button,添加一个点击事件和Android进行交互
交互代码:

AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("showCurrentTime");

这里的showCurrentTime是Android中预留的public方法

上一篇下一篇

猜你喜欢

热点阅读