很久没有写博客了,最近公司要求游戏要做自动更新功能。所以今天来总结一下,过程种踩的种种神坑。有些小伙伴要说了,现在Unity不是都用热更吗?资源用AB包,代码可以用lua,或者ILRunTime?没错,目前主流Unity游戏更新解决方案,是这样的。但是由于我们的游戏包体很小只有25M左右,而且属于小游戏,上线后不会长期高频的迭代,只会修复修复bug,所以没有考虑采用热更的方式。
我是Unity开发者,对于Java不熟悉,安卓开发也不是很熟,所以踩了不少坑,大家可以直接使用我的代码来实现。
- 首先需要检查版本号。我们需要在服务器存放版本文件,安卓通过读取该文件来对比判断是否游戏需要更新。
代码附上。
private static String getVersion() throws IOException, JSONException {
URL url = new URL("这里填写服务器版本文件的Url");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(false);
httpURLConnection.setReadTimeout(8 * 1000);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
// 获取返回的数据
String result = readResourceAsString(httpURLConnection.getInputStream());
//对json数据进行解析
JSONObject jsonObject = new JSONObject(result);
String strings = jsonObject.getString("version");
Log.d("Unity", "请求成功,result--->" + result);
return strings;
} else {
Log.d("Unity", "请求失败:" + httpURLConnection.getResponseCode());
}
return null;
}
/**
* 读取数据流为字符串
*/
private static String readResourceAsString(InputStream in) throws IOException {
StringBuilder builder = new StringBuilder();
// InputStream in = resource.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str ;
while ((str = bufferedReader.readLine())!=null){
builder.append(str);
}
//关闭流
bufferedReader.close();
inputStreamReader.close();
in.close();
return builder.toString();
}
这里,踩到了第一个坑。GET方法,一定要设置 httpURLConnection.set