如何在离线情况下使用Android Studio正常运行项目

 

前段时间,项目组需要进行代码安全扫描,并且扫描环境是fortify的离线环境(无奈),最无奈的是,需要在一台离线服务器上搭建Android Studio环境,并且需要把项目整改成可以离线编译的,最后踩了不少坑才完成了,整理成文章望大家能够分享经验不用再浪费时间了!注:fortify扫描离线Android项目时,需要在项目根目录下添加“build-cache”和“files-2.1”(此处files-2.1即为联网电脑的.gradle下的files-2.1文件夹,不用做迁移)文件夹,这样能够防止代码编译报错

原始电脑路径:C:\User\aaa\xxx

离线电脑路径:C:\User\bbb\xxx

1.File->Setting->Build,Excecution,Deployment->Gradle中的Offline work必须勾选!将C:\Users\aaa\.android\build-cache下对应build版本的文件夹整个拷到另一台电脑的C:\Users\bbb\.android\build-cache下:

2.将C:\Users\aaa\.gradle 下每个文件夹中的各个文件夹都要拷贝到另外一台电脑的C:\Users\bbb\.gradle(路径可自定义,这个路径就是项目引用的gradle路径)文件夹下,如果考虑内存占用,就只拷贝对应版本的文件夹即可。

3.

3.1将C:\Users\aaa\.gradle\caches\modules-2\files-2.1(jar包所在路径,对于android中自带的jar包,可以通过图2的方式下载https://developer.android.google.cn/studio#downloads图3)中所有有关项目的jar包都要放到一个叫做C:\\Users\\bbb\\xxx\extras\m2repository(自定义路径,该路径就是项目的build.gradle文件中最后引用的路径maven{url 'file://C:\\Users\\bbb\\xxx\\extras\\m2repository'}) 的文件夹下,此处需要注意一点,在C:\Users\aaa\.gradle\caches\modules-2\files-2.1路径下的目录结构是com.android.xxx/common/1.1.1/xxx/xxx.jar这个格式的,而在C:\Users\xxx\extras\m2repository路径下的文件目录结构必须是com/android/xxx格式的(这样才能在项目的build.gradle中引用),那么有两种方式可以实现:1)用代码(代码在文章最后附上,拷贝别人的代码,找到链接之后会附上链接)进行两个文件夹中文件的整体迁移;2)也可以手动拷贝对应的每个文件,如果不嫌麻烦的话(不建议使用)

 

3.2对于项目中使用implementation 'xxx'方式引用的jar包,都要在Maven仓库中找到对应的jar包放入到libs文件夹下,这一步是一个重复操作,操作比较简单,拷贝完之后在app的build.gradle文件中添加libs文件夹的引用。注:需要在libs文件夹下添加android.jar,防止找不到对应的android源包的引用。

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'
    defaultConfig {
        applicationId "com.xxx.xxx"
        minSdkVersion 26
        targetSdkVersion 28
        versionCode 15
        versionName "2.1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        packagingOptions {
            exclude 'META-INF/proguard/android-annotations.pro'
        }
        ndk {
            abiFilters "armeabi"
        }
        multiDexEnabled true
    }

    buildTypes {
        release {
            buildConfigField "boolean", "LOG_DEBUG", "false" //false不显示log true显示log
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            shrinkResources false
            signingConfig signingConfigs.release
            debuggable false
        }
        debug {
            buildConfigField "boolean", "LOG_DEBUG", "true" //显示log
            debuggable false
        }
    }
    aaptOptions { cruncherEnabled = false }

    dexOptions {
        javaMaxHeapSize "4g"
    }

    lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in release builds,
        // but continue the build even when errors are found:
        abortOnError false
    }

    productFlavors {
    }
    allprojects {
        repositories {
            maven { url "https://jitpack.io" }
        }
    }
    compileOptions {
        sourceCompatibility '1.8'
        targetCompatibility '1.8'
    }
    repositories {
        flatDir {
            dirs 'libs'
        }
    }
}

dependencies {
    //添加libs文件夹下jar引用
    implementation fileTree(dir: 'libs', include: ['*.aar', '*.jar'], exclude: [])
}

3.3将整个xxx\extras文件夹拷贝到另一台电脑上(比如路径为C:\bbb\),并且在本地项目的build.gradle文件中添加maven {url 'file://C:\\Users\\bbb\\xxx\\extras\\m2repository'}

 

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
//把所有引用网络的代码删除,只保留本地对应的maven仓库路径
//        mavenCentral()
//        jcenter{
//            url 'http://jcenter.bintray.com'
//        }
//        maven {
//            url 'https://maven.google.com/'
//            name 'Google'
//        }
//        maven {
//            url "http://jcenter.bintray.com"
//        }
//        google()
        maven {
            url "file://C:\\Users\\bbb\\xxx\\extras\\m2repository"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
//        mavenCentral()
//        google()
//        jcenter{
//            url 'http://jcenter.bintray.com'
//        }
//
//        maven {
//            url "http://jcenter.bintray.com"
//        }
//        maven {
//            url 'https://maven.google.com/'
//            name 'Google'
//            maven { url "https://jitpack.io" }
//        }
//        maven {
//            url 'https://download.01.org/crosswalk/releases/crosswalk/android/maven2'
//        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

4.重新同步代码,编译成功!

附迁移文件代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

/**
 * 将Android中使用的gradle缓存目录中的jar包重新处理路径,用于内网离线构建
 */

public class CopyTool {
    //来源jar包文件夹
    public final static String path = "D:\\Users\\aaa\\.gradle\\caches\\modules-2\\files-2.1"; 
    //目的jar包文件夹
    public final static String stopName = "files-2.1";

    public static void main(String[] args) {
        System.out.println("Begin to copy");
        processDotForld();
        copyToLastForld();
        System.out.println("Copy finished");
    }

    /**
     * 处理文件夹中带点好的。;例如:D:/test/com.ifind.android/
     */
    public static void processDotForld() {
        File file = new File(path);
        if (file.exists()) {
            LinkedList<File> list = new LinkedList<>();
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File file2 = files[i];
                if (file2.isDirectory()) {
                    //文件夹
                    File desFile = creatforld(file2);
                    copyFileToDes(file2, desFile);
                } else {
                    //文件//目前不存在
                }
            }
        }
    }

    /**
     * 文件夹拷贝
     *
     * @param source
     * @param des
     */
    public static void copyFileToDes(File source, File des) {
        try {
            copyDir(source.getPath(), des.getPath());
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    /**
     * 文件夹拷贝
     *
     * @param sourcePath
     * @param newPath
     * @throws IOException
     */
    public static void copyDir(String sourcePath, String newPath) throws IOException {
        File file = new File(sourcePath);
        String[] filePath = file.list();

        if (!(new File(newPath)).exists()) {
            (new File(newPath)).mkdir();
        }

        for (int i = 0; i < filePath.length; i++) {
            if ((new File(sourcePath + file.separator + filePath[i])).isDirectory()) {
                copyDir(sourcePath + file.separator + filePath[i], newPath + file.separator + filePath[i]);
            }

            if (new File(sourcePath + file.separator + filePath[i]).isFile()) {
                copyFile(sourcePath + file.separator + filePath[i], newPath + file.separator + filePath[i]);
            }

        }
    }

    public static void copyFile(String oldPath, String newPath) throws IOException {
        File oldFile = new File(oldPath);
        File file = new File(newPath);
        FileInputStream in = new FileInputStream(oldFile);
        FileOutputStream out = new FileOutputStream(file);

        byte[] buffer = new byte[2097152];

        //while((in.read(buffer)) != -1){
        //  out.write(buffer);
        //}

        DataInputStream dis = new DataInputStream(new BufferedInputStream(in));
        DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(out));

        int length;
        while ((length = dis.read(buffer)) != -1) {
            dos.write(buffer, 0, length);
        }
        dos.flush();
        dos.close();
        dis.close();
    }


    /**
     * 创建文件夹
     *
     * @param file
     */
    public static File creatforld(File file) {
        String path = file.getAbsolutePath();
        if (path != null) {
            String temp = "files-2.1";
            temp = stopName;
            String temS[] = path.split(temp);

            if (temS != null && temS.length == 2) {
                String firstName = temS[0];
                String dotName = temS[1];
                if (dotName != null) {
                    String[] lasts = dotName.split("\\.");
                    int count = lasts.length;
                    if (count < 2) {
                        return null;
                    }
                    String pathNew = firstName + temp;
                    for (int i = 0; i < count; i++) {
                        if (i == 0) {
                            pathNew = pathNew + lasts[i];
                        } else {
                            pathNew = pathNew + "\\" + lasts[i];
                        }
                    }
                    if (pathNew != null && !pathNew.equals("")) {
                        File fileForld = new File(pathNew);
                        if (!fileForld.exists()) {
                            fileForld.mkdirs();
                        }
                        return fileForld;
                    }
                }
            }
        }
        return null;
    }

    public static ArrayList<File> getFile(File file) {
        ArrayList<File> list = new ArrayList<>();
        if (file.isDirectory()) {
            File[] filesTemp = file.listFiles();
            for (int i = 0; i < filesTemp.length; i++) {
                ArrayList<File> result = getFile(filesTemp[i]);
                list.addAll(result);
            }

        } else {
            list.add(file);
        }
        return list;
    }


    // 创建目录
    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {// 判断目录是否存在
            System.out.println("创建目录失败,目标目录已存在!");
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
            destDirName = destDirName + File.separator;
        }
        if (dir.mkdirs()) {// 创建目标目录
            System.out.println("创建目录成功!" + destDirName);
            return true;
        } else {
            System.out.println("创建目录失败!");
            return false;
        }
    }


    public static void copyToLastForld() {
        File file = new File(path);
        if (file.exists()) {
            LinkedList<File> list = new LinkedList<>();
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File file2 = files[i];
                if (file2.isDirectory()) {
                  //文件夹
                    proceessForld(file2);
                } else {
                  //文件//目前不存在
                }
            }
        }
    }


    private static void proceessForld(File file) {
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            File file2 = files[i];
            if (file2.isDirectory()) {
                  //文件夹
                proceessForld(file2);
            } else {
                  //文件//目前不存在//判断是否进行拷贝
                try {
                    proceessFile(file2);
                } catch (FileNotFoundException e) {
                  // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }


    private static void proceessFile(File file) throws FileNotFoundException {
        if (file != null) {
            String path = file.getAbsolutePath();
            if (path != null) {
                String[] lasts = splitString(path);
                if (lasts != null && lasts.length > 0) {
                    int count = lasts.length;
                    String last = lasts[count - 1];
                    String last2 = lasts[count - 2];


                    if (last2 != null && last2.length() > 20) {
                  //拷贝到上一级目录
                        String des = null;
                        if (count < 2) {
                            return;
                        }
                        for (int i = 0; i < count - 2; i++) {
                            if (i == 0) {
                                des = lasts[i];
                            } else {
                                des = des + "\\\\" + lasts[i];
                            }
                        }
                        des = des + "\\\\" + last;
                        String strParentDirectory = file.getParent();
                        File parentFile = new File(strParentDirectory);
                        strParentDirectory = parentFile.getParent() + "\\" + last;
                        copy(file, path, strParentDirectory);
                    } else {
                  // System.out.println("source = "+path);
                    }
                  // System.out.println("source = "+path);
                  // System.out.println("des = "+des);
                }
            }
        }
    }


    private static String[] splitString(String path) {
        String[] lasts = null;
        lasts = path.split("\\\\");
        int count = lasts.length;
        boolean isFirst = true;
        for (int i = 0; i < count; i++) {
            String str = lasts[i];
            if (str != null && str.contains(".")) {
                if (isFirst) {
                    isFirst = false;
                    System.out.println("\n\n\n\n");
                    System.out.println("path=" + path + "");
                }
                System.out.println("str=" + str + "");
            }
        }
        return lasts;
    }

    /**
     * copy动作
     *
     * @param file
     * @param source
     * @param des
     * @throws FileNotFoundException
     */
    private static void copy(File file, String source, String des) throws FileNotFoundException {
        if (file != null) {
            FileInputStream fis = null;
            FileOutputStream fot = null;
            byte[] bytes = new byte[1024];
            int temp = 0;
            File desFile = new File(des);
            if (desFile.exists()) {
                return;
            }
            try {
                fis = new FileInputStream(file);
                fot = new FileOutputStream(desFile);
                while ((temp = fis.read(bytes)) != -1) {
                    fot.write(bytes, 0, temp);
                    fot.flush();


                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fot != null) {
                    try {
                        fot.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }


        }
    }


    private static String getContent(String content) {
        String str = content;
        if (content != null && content.length() > 4) {
            str = content.substring(0, 4);
        }
        return str;
    }
}

 个人原创文字,总结了最近遇到的一些离线编译问题,如果有错误欢迎大家批评指正!

如有疑问可以微信:cai-niao-bu-ke-yi; QQ:1125325256 留言 个人网站:www.sevenyoung.net(不日即将开启,欢迎大家访问)

 

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值