Android 封装:DevBox WebView 壳 v1.0.0(aapt2 + d8 手工构建)
- com.devbox.web 1.0.0,minSdk 23 / targetSdk 28 - 文件选择、blob 下载转原生保存、摄像头/麦克风/定位授权、返回键、断网重试页 - build.sh 一条命令出签名 APK
This commit is contained in:
commit
52985b5022
11 files changed
+301
No files matched your search
+22
@@ -0,0 +1,22 @@
|
||||
data/
|
||||
data.*/
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
node_modules/
|
||||
.DS_Store
|
||||
|
||||
# dsh-go 自动补充
|
||||
dist/
|
||||
build/
|
||||
.venv/
|
||||
venv/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.log
|
||||
.env
|
||||
.env.*
|
||||
.dart_tool/
|
||||
.next/
|
||||
.cache/
|
||||
coverage/
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.devbox.web" android:versionCode="2011201" android:versionName="1.0.0">
|
||||
<uses-sdk android:minSdkVersion="23" android:targetSdkVersion="28" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||
<application android:label="@string/app_name" android:icon="@mipmap/ic_launcher"
|
||||
android:usesCleartextTraffic="true" android:hardwareAccelerated="true"
|
||||
android:allowBackup="true" android:supportsRtl="true" android:theme="@android:style/Theme.NoTitleBar">
|
||||
<activity android:name=".MainActivity" android:exported="true"
|
||||
android:configChanges="orientation|screenSize|keyboardHidden|screenLayout|uiMode"
|
||||
android:launchMode="singleTask">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,26 @@
|
||||
# DevBox Android 封装(WebView 壳)
|
||||
|
||||
把 https://110.42.217.133:8090 这套工具箱包成原生 App。
|
||||
|
||||
- 包名 `com.devbox.web`,versionName 1.0.0,minSdk 23 / targetSdk 28(sideload 用,允许明文 HTTP 与旧存储权限)
|
||||
- 纯 WebView 加壳,UI 与工具逻辑仍由服务器上的网页提供:**改工具不用重新发版**
|
||||
- 关键实现
|
||||
- `onShowFileChooser`:网页里的 `<input type=file>` 能正常选文件(含多选)
|
||||
- `AndroidSave.save(name, mime, base64)`:网页下载 `blob:` 时把数据交给原生,存到 `Download/DevBox/` 并广播媒体扫描
|
||||
- 注入脚本改写 `HTMLAnchorElement.prototype.click`,拦截 blob:/data: 链接转走原生保存(否则 WebView 里点下载没反应)
|
||||
- WebRTC / 摄像头 / 麦克风 / 定位:`onPermissionRequest` 直接授权,并申请运行时权限
|
||||
- 返回键先回退网页,再双击退出
|
||||
- 断网时显示本地「连不上服务器 + 重试」页,不白屏
|
||||
- 构建(本机已跑通,无需 Gradle)
|
||||
|
||||
```bash
|
||||
bash build.sh # aapt2 compile/link -> javac -> d8 -> 打 dex -> zipalign -> apksigner
|
||||
# 产物 out/DevBox-v1.0.0.apk(约 25 KB,签名 CN=DSH GM)
|
||||
```
|
||||
|
||||
依赖:`/usr/lib/android-sdk/{build-tools/29.0.3, platforms/android-23/android.jar}`、`/tmp/r8.jar`、keystore `/root/workspace/gm-keystore/gm.jks`(别名 gm / 口令 dshgm2026)。
|
||||
|
||||
## 说明
|
||||
|
||||
- 这是「壳 + 远程网页」方案:账号、积分、CDK、创作者工具都依赖服务器;离线只能看到提示页。
|
||||
- 如果以后要完全离线版,需要把 `js/`、`css/`、`data/zh.json` 打进 assets,并给前端加一层「无后端模式」(本地积分/无登录),那是另一套改动。
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
SDK=/usr/lib/android-sdk
|
||||
AJAR=$SDK/platforms/android-23/android.jar
|
||||
KS=/root/workspace/gm-keystore/gm.jks
|
||||
rm -rf gen out && mkdir -p gen out/dex out/classes
|
||||
|
||||
echo "== 1. 资源编译 =="
|
||||
"$SDK/build-tools/29.0.3/aapt2" compile --dir res -o out/res.zip
|
||||
|
||||
echo "== 2. 链接 + 生成 R =="
|
||||
"$SDK/build-tools/29.0.3/aapt2" link -o out/base.apk -I "$AJAR" \
|
||||
--manifest AndroidManifest.xml -A assets --java gen \
|
||||
--min-sdk-version 23 --target-sdk-version 28 --auto-add-overlay out/res.zip
|
||||
|
||||
echo "== 3. javac =="
|
||||
javac -nowarn -source 8 -target 8 -encoding UTF-8 -classpath "$AJAR" \
|
||||
-d out/classes $(find src gen -name '*.java') 2>&1 | grep -v "^警告\|warning: \[options\]\|^Note:" || true
|
||||
|
||||
echo "== 4. d8 =="
|
||||
java -cp /tmp/r8.jar com.android.tools.r8.D8 --min-api 23 --lib "$AJAR" \
|
||||
--output out/dex $(find out/classes -name '*.class')
|
||||
|
||||
echo "== 5. 打包 dex =="
|
||||
python3 - <<'PY'
|
||||
import zipfile, shutil, os
|
||||
src = 'out/base.apk'; dst = 'out/unsigned.apk'
|
||||
with zipfile.ZipFile(src) as zi, zipfile.ZipFile(dst, 'w', zipfile.ZIP_DEFLATED) as zo:
|
||||
for it in zi.infolist():
|
||||
zo.writestr(it, zi.read(it.filename))
|
||||
zo.write('out/dex/classes.dex', 'classes.dex')
|
||||
print('dex added')
|
||||
PY
|
||||
|
||||
echo "== 6. 对齐 + 签名 =="
|
||||
zipalign -f -p 4 out/unsigned.apk out/aligned.apk
|
||||
apksigner sign --ks "$KS" --ks-key-alias gm --ks-pass pass:dshgm2026 --key-pass pass:dshgm2026 \
|
||||
--min-sdk-version 23 --v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true \
|
||||
--out out/DevBox-v1.0.0.apk out/aligned.apk
|
||||
apksigner verify --print-certs out/DevBox-v1.0.0.apk | head -4
|
||||
ls -lh out/DevBox-v1.0.0.apk
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.4 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.1 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.2 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">DevBox 工具箱</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,183 @@
|
||||
package com.devbox.web;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.ContentValues;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Bitmap;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Environment;
|
||||
import android.provider.MediaStore;
|
||||
import android.util.Base64;
|
||||
import android.util.Log;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.ViewGroup;
|
||||
import android.webkit.CookieManager;
|
||||
import android.webkit.GeolocationPermissions;
|
||||
import android.webkit.JavascriptInterface;
|
||||
import android.webkit.PermissionRequest;
|
||||
import android.webkit.ValueCallback;
|
||||
import android.webkit.WebChromeClient;
|
||||
import android.webkit.WebResourceError;
|
||||
import android.webkit.WebResourceRequest;
|
||||
import android.webkit.WebSettings;
|
||||
import android.webkit.WebView;
|
||||
import android.webkit.WebViewClient;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.Toast;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class MainActivity extends Activity {
|
||||
static final String HOME = "http://110.42.217.133:8090/";
|
||||
private WebView web;
|
||||
private ValueCallback<Uri[]> filePathCallback;
|
||||
private static final int REQ_FILE = 1001;
|
||||
private long lastBack = 0;
|
||||
private static final String INJECT = "(function(){try{"
|
||||
+ "var A=HTMLAnchorElement.prototype;var orig=A.click;"
|
||||
+ "A.click=function(){try{var h=this.href||'';if(h.indexOf('blob:')===0||h.indexOf('data:')===0){"
|
||||
+ "var name=this.download||'download.bin';fetch(h).then(function(r){return r.blob()}).then(function(b){"
|
||||
+ "var fr=new FileReader();fr.onload=function(){var s=fr.result;var i=s.indexOf(',');AndroidSave.save(name,b.type||'application/octet-stream',s.substring(i+1));};"
|
||||
+ "fr.readAsDataURL(b);}).catch(function(){});return;}}catch(e){}return orig.apply(this,arguments)};"
|
||||
+ "}catch(e){}})();";
|
||||
|
||||
@Override protected void onCreate(Bundle b) {
|
||||
super.onCreate(b);
|
||||
FrameLayout root = new FrameLayout(this);
|
||||
web = new WebView(this);
|
||||
root.addView(web, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
|
||||
setContentView(root);
|
||||
|
||||
WebSettings s = web.getSettings();
|
||||
s.setJavaScriptEnabled(true);
|
||||
s.setDomStorageEnabled(true);
|
||||
s.setDatabaseEnabled(true);
|
||||
s.setAllowFileAccess(true);
|
||||
s.setLoadWithOverviewMode(true);
|
||||
s.setUseWideViewPort(true);
|
||||
s.setBuiltInZoomControls(false);
|
||||
s.setMediaPlaybackRequiresUserGesture(false);
|
||||
s.setCacheMode(WebSettings.LOAD_DEFAULT);
|
||||
if (Build.VERSION.SDK_INT >= 21) s.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
|
||||
s.setUserAgentString(s.getUserAgentString() + " DevBoxApp/1.0");
|
||||
CookieManager.getInstance().setAcceptCookie(true);
|
||||
|
||||
web.addJavascriptInterface(new SaveBridge(), "AndroidSave");
|
||||
web.setWebViewClient(new WebViewClient() {
|
||||
@Override public boolean shouldOverrideUrlLoading(WebView v, String url) {
|
||||
if (url.startsWith(HOME) || url.startsWith("file:")) return false;
|
||||
try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); } catch (Exception e) {}
|
||||
return true;
|
||||
}
|
||||
@Override public void onReceivedError(WebView v, WebResourceRequest req, WebResourceError err) {
|
||||
if (req != null && req.isForMainFrame()) showOffline();
|
||||
}
|
||||
@Override public void onPageFinished(WebView v, String url) {
|
||||
v.evaluateJavascript(INJECT, null);
|
||||
}
|
||||
});
|
||||
web.setWebChromeClient(new WebChromeClient() {
|
||||
@Override public void onPermissionRequest(final PermissionRequest request) {
|
||||
runOnUiThread(new Runnable() { public void run() { try { request.grant(request.getResources()); } catch (Exception e) {} } });
|
||||
}
|
||||
@Override public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback cb) { cb.invoke(origin, true, false); }
|
||||
@Override public boolean onShowFileChooser(WebView v, ValueCallback<Uri[]> cb, FileChooserParams params) {
|
||||
if (filePathCallback != null) filePathCallback.onReceiveValue(null);
|
||||
filePathCallback = cb;
|
||||
try {
|
||||
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
|
||||
i.addCategory(Intent.CATEGORY_OPENABLE);
|
||||
i.setType("*/*");
|
||||
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
|
||||
startActivityForResult(Intent.createChooser(i, "选择文件"), REQ_FILE);
|
||||
} catch (Exception e) { filePathCallback = null; return false; }
|
||||
return true;
|
||||
}
|
||||
@Override public void onProgressChanged(WebView v, int p) { }
|
||||
});
|
||||
|
||||
web.loadUrl(HOME);
|
||||
String[] perms = {"android.permission.CAMERA", "android.permission.RECORD_AUDIO", "android.permission.ACCESS_FINE_LOCATION"};
|
||||
if (Build.VERSION.SDK_INT >= 23) {
|
||||
ArrayList<String> need = new ArrayList<>();
|
||||
for (String p : perms) if (checkSelfPermission(p) != 0) need.add(p);
|
||||
if (!need.isEmpty()) requestPermissions(need.toArray(new String[0]), 7);
|
||||
}
|
||||
}
|
||||
|
||||
@Override protected void onActivityResult(int req, int res, Intent data) {
|
||||
if (req == REQ_FILE) {
|
||||
Uri[] out = null;
|
||||
if (res == RESULT_OK && data != null) {
|
||||
if (data.getClipData() != null) {
|
||||
int n = data.getClipData().getItemCount();
|
||||
out = new Uri[n];
|
||||
for (int i = 0; i < n; i++) out[i] = data.getClipData().getItemAt(i).getUri();
|
||||
} else if (data.getData() != null) out = new Uri[]{data.getData()};
|
||||
}
|
||||
if (filePathCallback != null) filePathCallback.onReceiveValue(out);
|
||||
filePathCallback = null;
|
||||
} else super.onActivityResult(req, res, data);
|
||||
}
|
||||
|
||||
@Override public void onBackPressed() {
|
||||
if (web.canGoBack()) { web.goBack(); return; }
|
||||
long now = System.currentTimeMillis();
|
||||
if (now - lastBack < 1800) super.onBackPressed();
|
||||
else { lastBack = now; Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show(); }
|
||||
}
|
||||
|
||||
@Override protected void onResume() { super.onResume(); if (web != null) web.onResume(); }
|
||||
@Override protected void onPause() { if (web != null) web.onPause(); super.onPause(); }
|
||||
|
||||
public class SaveBridge {
|
||||
@JavascriptInterface public void save(String name, String mime, String base64) {
|
||||
try {
|
||||
byte[] data = Base64.decode(base64, Base64.DEFAULT);
|
||||
String path = store(name, mime, data);
|
||||
toast("已保存:" + path);
|
||||
} catch (Exception e) { toast("保存失败:" + e.getMessage()); }
|
||||
}
|
||||
@JavascriptInterface public void toastMsg(String msg) { toast(msg); }
|
||||
}
|
||||
|
||||
private String store(String name, String mime, byte[] data) throws Exception {
|
||||
name = name == null || name.length() == 0 ? "devbox-" + System.currentTimeMillis() : name;
|
||||
File dir = new File(Environment.getExternalStoragePublicDirectory("Download"), "DevBox");
|
||||
if (!dir.exists()) dir.mkdirs();
|
||||
File out = new File(dir, name);
|
||||
int i = 1;
|
||||
while (out.exists()) {
|
||||
String base = name, ext = "";
|
||||
int dot = name.lastIndexOf('.');
|
||||
if (dot > 0) { base = name.substring(0, dot); ext = name.substring(dot); }
|
||||
out = new File(dir, base + "-" + (i++) + ext);
|
||||
}
|
||||
FileOutputStream fo = new FileOutputStream(out);
|
||||
fo.write(data); fo.close();
|
||||
try {
|
||||
Intent scan = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(out));
|
||||
sendBroadcast(scan);
|
||||
} catch (Exception e) {}
|
||||
return out.getAbsolutePath();
|
||||
}
|
||||
|
||||
private void showOffline() {
|
||||
String html = "<html><head><meta name='viewport' content='width=device-width,initial-scale=1'>"
|
||||
+ "<style>body{background:#070a11;color:#e8eefc;font-family:sans-serif;display:flex;height:100vh;margin:0;"
|
||||
+ "align-items:center;justify-content:center;flex-direction:column;text-align:center;padding:24px}"
|
||||
+ "h2{font-size:19px;margin:0 0 8px}p{color:#8b97b0;font-size:14px;line-height:1.7;margin:0 0 18px}"
|
||||
+ "button{background:#5b8cff;color:#fff;border:none;border-radius:10px;padding:12px 22px;font-size:15px}</style>"
|
||||
+ "</head><body><h2>连不上服务器</h2><p>DevBox 的账号与积分功能需要联网。<br>检查网络后点下面重试。</p>"
|
||||
+ "<button onclick='AndroidSave.toastMsg(\"正在重试…\")+setTimeout(function(){location.href=\"" + HOME + "\"},300)'>重试</button>"
|
||||
+ "</body></html>";
|
||||
web.loadDataWithBaseURL(HOME, html, "text/html", "utf-8", null);
|
||||
}
|
||||
|
||||
private void toast(final String m) { runOnUiThread(new Runnable() { public void run() { Toast.makeText(MainActivity.this, m, Toast.LENGTH_LONG).show(); } }); }
|
||||
}
|
||||
Reference in new issue
Block a user