最近项目中需要接入google分析,接入google分析时需要下载google-services.json,放到项目中的app文件夹下。由于项目是对外提供的SDK,基于方便易用的目的,决定用gradle插件来实现。
实现思路是:
- 从后端请求google-services.json文件。
- 通过gradle插件将该文件写入到app文件夹中。
如何在gradle插件中进行网络请求,在之前的文章Android 自定义Gradle插件(三):动态添加依赖中已经有介绍过了,这里不再赘述。
将google-services.json写入到app文件夹
实现方式与在其他安卓项目中类似,就是通过File类来创建文件,并通过流来写入数据,代码如下:
public class FileUtils {
/**
* 向文件夹保存文件
*
* @param floderFile 要保存文件的文件夹
* @param fileName 文件名
* @param fileContentData 文件内容
*/
public static void saveFileToFolder(File floderFile, String fileName, String fileContentData) {
File createFile = new File(floderFile, fileName);
LogUtils.println("create file path :" + createFile.getPath());
//先删除旧的file
if (createFile.exists()) {
boolean delete = createFile.delete();
LogUtils.println("delete old file success :" + delete);
}
try {
boolean create = createFile.createNewFile();
LogUtils.println("create new file success :" + create);
} catch (IOException e) {
e.printStackTrace();
}
if (createFile.exists()) {
FileOutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
BufferedWriter writer = null;
try {
outputStream = new FileOutputStream(createFile);
outputStreamWriter = new OutputStreamWriter(outputStream);
writer = new BufferedWriter(outputStreamWriter);
writer.write(fileContentData);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
if (outputStreamWriter != null) {
outputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class MyPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.afterEvaluate {
//app module 的路径文件可以通过project.projectDir来获取。
//如果要在build文件夹下创建文件,可以通过 project.buildDir来获取路径文件。
FileUtils.saveFileToFolder(project.projectDir, "google-services.json", "写入的内容")
}
}
}
复制代码
效果图: