feat(system): support app internal update apk
This commit is contained in:
@@ -7,8 +7,8 @@ android {
|
||||
applicationId "com.imyeyu.gao.customer"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 2
|
||||
versionName "1.0.1"
|
||||
versionCode 3
|
||||
versionName "1.1.0"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
<!-- Permissions -->
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||
</manifest>
|
||||
|
||||
@@ -14,12 +14,14 @@ import androidx.core.view.ViewCompat;
|
||||
import androidx.core.view.WindowCompat;
|
||||
import androidx.core.view.WindowInsetsCompat;
|
||||
import com.getcapacitor.BridgeActivity;
|
||||
import com.imyeyu.gao.customer.shellupdater.ShellUpdaterPlugin;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public class MainActivity extends BridgeActivity {
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
registerPlugin(ShellUpdaterPlugin.class);
|
||||
super.onCreate(savedInstanceState);
|
||||
applyEdgeToEdge();
|
||||
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package com.imyeyu.gao.customer.shellupdater;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.provider.Settings;
|
||||
import androidx.core.content.FileProvider;
|
||||
import com.getcapacitor.JSObject;
|
||||
import com.getcapacitor.Plugin;
|
||||
import com.getcapacitor.PluginCall;
|
||||
import com.getcapacitor.PluginMethod;
|
||||
import com.getcapacitor.annotation.CapacitorPlugin;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/// 应用外壳下载与安装
|
||||
@CapacitorPlugin(name = "ShellUpdater")
|
||||
public class ShellUpdaterPlugin extends Plugin {
|
||||
private final ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
private final AtomicBoolean downloading = new AtomicBoolean(false);
|
||||
private File directory;
|
||||
private boolean awaitingSettings;
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
directory = new File(getContext().getCacheDir(), "shell-updates");
|
||||
executor.execute(() -> {
|
||||
File[] files = directory.listFiles();
|
||||
if (files == null) return;
|
||||
// 只清 6 小时前的残留:安装期间进程可能被杀后重启,立刻删除会让安装器读不到文件
|
||||
long cutoff = System.currentTimeMillis() - 6 * 60 * 60 * 1000L;
|
||||
for (File file : files) {
|
||||
if (file.isFile() && file.lastModified() < cutoff) file.delete();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// 检查安装未知应用权限
|
||||
@PluginMethod
|
||||
public void canInstall(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("allowed", Build.VERSION.SDK_INT < Build.VERSION_CODES.O || getContext().getPackageManager().canRequestPackageInstalls());
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
/// 打开本应用的安装权限设置
|
||||
@PluginMethod
|
||||
public void openInstallSettings(PluginCall call) {
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getContext().getPackageName()));
|
||||
awaitingSettings = true;
|
||||
getActivity().startActivity(intent);
|
||||
}
|
||||
call.resolve();
|
||||
} catch (Exception e) {
|
||||
call.reject("无法打开安装权限设置", e);
|
||||
}
|
||||
}
|
||||
|
||||
/// 下载并校验安装包,然后打开系统安装器
|
||||
@PluginMethod
|
||||
public void downloadAndInstall(PluginCall call) {
|
||||
String url = call.getString("url");
|
||||
String sha256 = call.getString("sha256");
|
||||
String fileName = call.getString("fileName");
|
||||
if (url == null || sha256 == null || !sha256.matches("(?i)[0-9a-f]{64}") || fileName == null || !fileName.matches("[a-zA-Z0-9._-]+\\.apk")) {
|
||||
call.reject("安装包参数无效");
|
||||
return;
|
||||
}
|
||||
if (!downloading.compareAndSet(false, true)) {
|
||||
call.reject("安装包正在下载");
|
||||
return;
|
||||
}
|
||||
executor.execute(() -> download(call, url, sha256, fileName));
|
||||
}
|
||||
|
||||
private void download(PluginCall call, String address, String expected, String fileName) {
|
||||
File file = new File(directory, fileName);
|
||||
HttpURLConnection connection = null;
|
||||
try {
|
||||
if (!directory.exists() && !directory.mkdirs()) throw new Exception("无法创建下载目录");
|
||||
URL url = new URL(address);
|
||||
if (!"https".equalsIgnoreCase(url.getProtocol()) && !"http".equalsIgnoreCase(url.getProtocol())) throw new Exception("下载地址无效");
|
||||
connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setConnectTimeout(15000);
|
||||
connection.setReadTimeout(30000);
|
||||
connection.setInstanceFollowRedirects(true);
|
||||
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) throw new Exception("安装包下载失败");
|
||||
long total = connection.getContentLengthLong();
|
||||
long received = 0;
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
try (InputStream input = connection.getInputStream(); FileOutputStream output = new FileOutputStream(file)) {
|
||||
byte[] buffer = new byte[32768];
|
||||
int size;
|
||||
while ((size = input.read(buffer)) != -1) {
|
||||
output.write(buffer, 0, size);
|
||||
digest.update(buffer, 0, size);
|
||||
received += size;
|
||||
JSObject progress = new JSObject();
|
||||
progress.put("received", received);
|
||||
progress.put("total", total);
|
||||
progress.put("percent", 0 < total ? (int) Math.min(100, received * 100 / total) : 0);
|
||||
notifyListeners("downloadProgress", progress);
|
||||
}
|
||||
}
|
||||
StringBuilder actual = new StringBuilder();
|
||||
for (byte b : digest.digest()) actual.append(String.format(Locale.ROOT, "%02x", b & 255));
|
||||
if (!actual.toString().equalsIgnoreCase(expected)) throw new Exception("安装包校验失败");
|
||||
Uri uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".fileprovider", file);
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||
intent.setDataAndType(uri, "application/vnd.android.package-archive");
|
||||
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
|
||||
getActivity().runOnUiThread(() -> {
|
||||
try {
|
||||
getActivity().startActivity(intent);
|
||||
call.resolve();
|
||||
} catch (Exception e) {
|
||||
call.reject("无法打开系统安装器", e);
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
file.delete();
|
||||
call.reject("安装包下载或校验失败", e);
|
||||
} finally {
|
||||
if (connection != null) connection.disconnect();
|
||||
downloading.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void handleOnResume() {
|
||||
if (awaitingSettings) {
|
||||
awaitingSettings = false;
|
||||
notifyListeners("resume", new JSObject());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void handleOnDestroy() {
|
||||
executor.shutdown();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user