wjtx_native/app/src/main/java/com/hnjc/wjtx/LaunchActivity.java
2021-10-21 15:49:15 +08:00

350 lines
13 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.hnjc.wjtx;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.hnjc.wjtx.net.DownloadRunnable;
import com.hnjc.wjtx.net.TaskInfo;
import com.hnjc.wjtx.net.WebApi;
import com.hnjc.wjtx.util.AssetsUtil;
import com.hnjc.wjtx.util.StringUtil;
import com.hnjc.wjtx.util.UnzipRunnable;
import com.xiaomi.gamecenter.sdk.MiCommplatform;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
public class LaunchActivity extends Activity {
private final String TAG = "LaunchActivity";
private final String ZERO_VERSION = "0";
private ProgressBar progressBar = null;
private TextView progressLabel = null;
private WebApi webApi;
private String zipUrl;
private String gameUrl;
private String preloadPath;
// 代码包体 assets里的版本号
private String localVersion = ZERO_VERSION;
// 预加载目录下的版本号
private String baseVersion = ZERO_VERSION;
// 远程的版本号
private String remoteVersion = ZERO_VERSION;
private String versionStr;
private String downloadStr;
private String unzipStr;
private TaskInfo info;//任务信息
private DownloadRunnable runnable;//下载任务
private UnzipRunnable unzipRunnable; // 解压任务
private boolean alterShowed;
private static final String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
private Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
//使用Handler制造一个200毫秒为周期的循环
handler.sendEmptyMessageDelayed(1, 200);
//计算下载进度
int l = (int) ((float) info.getCompletedLen() / (float) info.getContentLen() * 100);
//设置进度条进度
updateProgress(l);
if (l>=100) {//当进度>=100时取消Handler循环
handler.removeCallbacksAndMessages(null);
if (info.getType() == 0) {
File file = new File(info.getPath() + info.getName());
unzip(file);
} else {
changeLoadTxt("更新完成, 正在进入游戏");
startMain();
}
}
return true;
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch);
progressBar = findViewById(R.id.progressBar);
progressLabel = findViewById(R.id.loadLabel);
versionStr = this.getString(R.string.launch_version);
downloadStr = this.getString(R.string.launch_download);
unzipStr = this.getString(R.string.launch_unzip);
preloadPath = AssetsUtil.getDiskFileDir(this, this.getString(R.string.preload_path));
gameUrl = this.getString(R.string.game_url);
webApi = new WebApi(this);
localVersion = this.getString(R.string.local_version);
runOnUiThread(this::alertUserAgreement);
}
private void checkVersion() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int check = checkSelfPermission(permissions[0]);
if (check != PackageManager.PERMISSION_GRANTED) {
requestPermissions(permissions, 111);
return;
}
}
compareVersions();
}
private void updateProgress(int val) {
progressBar.setProgress(val);
}
private void changeLoadTxt(String title) {
progressLabel.setText(title);
}
private void compareVersions() {
changeLoadTxt(versionStr);
updateProgress(10);
getBaseVersionInfo();
updateProgress(30);
getLocalVersionInfo();
if (baseVersion.equals(ZERO_VERSION)) {
Log.e(TAG, "未获取到包体的版本号, 可能assets/game/下不包含version.json, 请重新打包!!!!");
}
if (localVersion.equals(ZERO_VERSION)) {
Log.i(TAG, "未获取到预加载目录的版本号");
} else if (StringUtil.compareAppVersion(baseVersion, localVersion) > 0) {
Log.i(TAG, "baseVersion: " + baseVersion + " 高于 localVersion: " + localVersion + ", 需清空本地预加载目录");
emptyPreload();
localVersion = ZERO_VERSION;
}
updateProgress(60);
getRemoteVersionInfo();
}
/**
* 获取位于预加载目录version.json中的版本号
*/
private void getLocalVersionInfo() {
String fileName = gameUrl.replace("index.html", "version.json");
String realPath = preloadPath + "/" + getFileDirByUrl(fileName) + "version.json" ;
File versionFile = new File(realPath);
if (versionFile.exists()) {
JSONObject data = AssetsUtil.readJsonFromFile(this, realPath);
try {
localVersion = data.getString("version");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/**
* 获取位于assets目录version.json中的版本号
*/
private void getBaseVersionInfo() {
JSONObject data = AssetsUtil.getJsonFromAssets(this, "game/version.json");
if (data != null) {
try {
baseVersion = data.getString("version");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/**
* 获取远程资源的版本号
*/
private void getRemoteVersionInfo() {
webApi.getVersionInfo((success, message, err) -> {
if (success) {
try {
remoteVersion = message.getString("version");
zipUrl = message.getString("path");
Log.i(TAG, "base version: " + baseVersion);
Log.i(TAG, "local version: " + localVersion);
Log.i(TAG, "remote version: " + remoteVersion);
Log.i(TAG, "remote resource: " + zipUrl);
boolean needUpdate = false;
if (StringUtil.compareAppVersion(baseVersion, localVersion) >= 0) {
if (StringUtil.compareAppVersion(remoteVersion, baseVersion) > 0) {
needUpdate = true;
}
} else {
if (StringUtil.compareAppVersion(remoteVersion, localVersion) > 0) {
needUpdate = true;
}
}
if (needUpdate) {
if (StringUtil.isBlank(zipUrl)) {
Log.e(TAG, "远程版本高于代码包版本和预加载版本, 需要更新, 但未获取到远程资源地址");
startMain();
} else {
Log.i(TAG, "远程版本高于代码包版本和预加载版本, 需要更新");
updateProgress(100);
preloadGame();
}
} else {
startMain();
}
} catch (JSONException e) {
e.printStackTrace();
startMain();
}
} else {
startMain();
}
});
}
private void preloadGame() {
String dir = preloadPath + "/" + getFileDirByUrl(gameUrl);
File dirFile = new File(dir);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
downloadGameRes(zipUrl, dir);
}
private void downloadGameRes(final String zipUrl, String targetDir) {
updateProgress(0);
changeLoadTxt(downloadStr);
info = new TaskInfo("game.zip", targetDir, zipUrl);
info.setType(0);
runnable = new DownloadRunnable(info);
//开始下载任务
new Thread(runnable).start();
//开始Handler循环
handler.sendEmptyMessageDelayed(1, 200);
}
private void unzip(File file) {
updateProgress(0);
changeLoadTxt(unzipStr);
info.setContentLen(0);
info.setCompletedLen(0);
info.setType(1);
unzipRunnable = new UnzipRunnable(info);
new Thread(unzipRunnable).start();
handler.sendEmptyMessageDelayed(1, 200);
}
private static String getFileDirByUrl(String urlString) {
int lastSlash = urlString.lastIndexOf('/');
String server = urlString.substring(0, lastSlash + 1);
return server.replaceFirst("://", "/").replace(":", "#0A");
}
private void emptyPreload() {
File dirFile = new File(preloadPath);
if (dirFile.exists() && dirFile.isDirectory()) {
File[] files = dirFile.listFiles();
for (File f : files) {
deletePreloadFile(f);
}
}
}
private void deletePreloadFile(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
deletePreloadFile(f);
}
file.delete();
} else if (file.exists()) {
file.delete();
}
}
private void startMain() {
Intent intent = new Intent(LaunchActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("preloadPath", preloadPath);
startActivity(intent);
overridePendingTransition(0, 0);
finish();
}
@Override
protected void onDestroy() {
//在Activity销毁时移除回调和msg并置空防止内存泄露
if(handler != null){
handler.removeCallbacksAndMessages(null);
handler = null;
}
super.onDestroy();
}
@Override
public void finish() {
super.finish();
overridePendingTransition(0, 0);
}
private void alertUserAgreement() {
SharedPreferences sp = getSharedPreferences("userAgreementResult", 0);
boolean agreed = sp.getBoolean("userAgreementResult", false);
if (agreed) {
//申请SDK所需权限会弹出权限说明弹框并且用户拒绝权限申请不会对SDK功能造成影响48小时内不会再次弹出
// MiCommplatform.getInstance().requestPermission(this);
//用户已经同意过隐私协议,直接通过
MiCommplatform.getInstance().onUserAgreed(this);
checkVersion();
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
WebView mwebView = new WebView(this);
this.alterShowed = false;
mwebView.loadUrl("https://privacy2.kingsome.cn/");
mwebView.setWebViewClient( new WebViewClient() {
//设置结束加载函数
@Override
public void onPageFinished(WebView view, String url) {
if (!alterShowed) {
alterShowed = true;
builder.show();
}
}
}
);
builder.setPositiveButton( "取消", null );
builder.setView( mwebView );
// builder.setTitle("隐私协议");
builder.setPositiveButton("同意", (dialog, which) -> {
//申请SDK所需权限会弹出权限说明弹框并且用户拒绝权限申请不会对SDK功能造成影响48小时内不会再次弹出
// MiCommplatform.getInstance().requestPermission(this);
//用户同意隐私协议,通过
MiCommplatform.getInstance().onUserAgreed(this);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("userAgreementResult", true);
editor.apply();
dialog.dismiss();
checkVersion();
});
builder.setNegativeButton("拒绝", (dialog, which) -> {
//用户不同意隐私协议不通过Demo在此处退出游戏接入方可按自己要求处理但不能调用MiCommplatform.getInstance().onUserAgreed(this);
dialog.dismiss();
android.os.Process.killProcess(android.os.Process.myPid());
});
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
switch (requestCode) {
case 111:
compareVersions();
break;
}
}
}