package com.hs.offlinex5demo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import com.tencent.smtt.export.external.TbsCoreSettings;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.TbsListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
public class InitActivity extends AppCompatActivity {
private static final String TAG = "InitActivity";
//写入到硬盘的文件地址
private File tbsFile;
private final Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_init);
tbsFile = new File(this.getFilesDir(), "x5.tbs.apk");
moveTbsFile(this::initX5);
}
//初始化x5
private void loadX5() {
QbSdk.preInit(this, true, new QbSdk.PreInitCallback() {
@Override
public void onCoreInitFinished() {
Log.d(TAG, "onCoreInitFinished: ");
}
@Override
public void onViewInitFinished(boolean b) {
Log.d(TAG, "onViewInitFinished: " + b);
if (b) {
startPage(QbSdk.getTbsVersion(InitActivity.this));
} else {
Toast.makeText(InitActivity.this, "X5初始化失败", Toast.LENGTH_SHORT).show();
}
}
});
}
private void moveTbsFile(Runnable callBack) {
new Thread(() -> {
try {
if (!tbsFile.exists()) {
tbsFile.createNewFile();
}
InputStream is = InitActivity.this.getAssets().open("tbs_core_046247_20230317115214_nolog_fs_obfs_arm64-v8a_release.apk");
FileOutputStream fos = new FileOutputStream(tbsFile);
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
is.close();
fos.close();
mHandler.post(callBack);
} catch (Exception e) {
Toast.makeText(this, "写入X5tbs文件失败", Toast.LENGTH_SHORT).show();
}
}).start();
}
private void initX5() {
int version = QbSdk.getTbsVersion(this);
if (version > 0) {
startPage(version);
return;
}
// 在调用TBS初始化、创建WebView之前进行如下配置
HashMap<String, Object> map = new HashMap<>();
map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
QbSdk.initTbsSettings(map);
//监听安装回调
QbSdk.setTbsListener(new TbsListener() {
@Override
public void onDownloadFinish(int i) {
Log.d(TAG, "onDownloadFinish: ");
}
@Override
public void onInstallFinish(int i) {
Log.d(TAG, "onInstallFinish: " + i);
if (i == 200) {
//安装成功后再调用初始化。
loadX5();
}
}
@Override
public void onDownloadProgress(int i) {
Log.d(TAG, "onDownloadProgress: ");
}
});
//这里调用安装 会触发安装完成回调
QbSdk.installLocalTbsCore(InitActivity.this, 46247, tbsFile.getAbsolutePath());
}
private void startPage(int v) {
Toast.makeText(this, "X5已初始化,3秒后跳转。v:" + v, Toast.LENGTH_SHORT).show();
mHandler.postDelayed(() -> {
startActivity(new Intent(this, MainActivity.class));
}, 3000);
}
}