package nodomain.freeyourgadget.gadgetbridge.womp; import android.app.Activity; import android.webkit.JavascriptInterface; import android.widget.Toast; import org.json.JSONObject; /** * WebView 与原生桥:网络请求、扫码、登录态。 */ public class WompJsBridge { public interface Host { void scan(String callbackId); void closePage(); void onLoggedIn(); void onLogout(); void evalJs(String script); } private final Activity activity; private final Host host; public WompJsBridge(Activity activity, Host host) { this.activity = activity; this.host = host; } @JavascriptInterface public String getSorter() { return WompSession.getSorterJson(activity); } @JavascriptInterface public String getSavedPhone() { return WompSession.getPhone(activity); } @JavascriptInterface public String getSavedPassword() { return WompSession.getPassword(activity); } @JavascriptInterface public void saveCredentials(String phone, String password) { WompSession.saveCredentials(activity, phone, password); } @JavascriptInterface public void toast(final String msg) { activity.runOnUiThread(() -> Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show()); } @JavascriptInterface public void scan(String callbackId) { activity.runOnUiThread(() -> host.scan(callbackId)); } @JavascriptInterface public void close() { activity.runOnUiThread(host::closePage); } @JavascriptInterface public void loginSuccess(String json) { try { JSONObject obj = new JSONObject(json); String phone = obj.optString("phone"); String password = obj.optString("password"); WompSession.saveLogin(activity, phone, password, obj); activity.runOnUiThread(host::onLoggedIn); } catch (Exception e) { activity.runOnUiThread(() -> Toast.makeText(activity, "登录数据异常", Toast.LENGTH_SHORT).show()); } } @JavascriptInterface public void logout() { WompSession.clear(activity); activity.runOnUiThread(host::onLogout); } @JavascriptInterface public boolean isCheckedIn() { return WompSession.isCheckedIn(activity); } @JavascriptInterface public void setCheckedIn(boolean checkedIn) { WompSession.setCheckedIn(activity, checkedIn); } @JavascriptInterface public void getLocation(String callbackId) { activity.runOnUiThread(() -> WompLocation.fetch(activity, (ok, json) -> deliver(callbackId, ok, json))); } @JavascriptInterface public void request(String path, String jsonBody, final String callbackId) { JSONObject body; try { body = jsonBody == null || jsonBody.length() == 0 ? new JSONObject() : new JSONObject(jsonBody); } catch (Exception e) { deliver(callbackId, false, "{\"message\":\"参数错误\"}"); return; } WompApi.post(path, body, (ok, resp) -> deliver(callbackId, ok, resp)); } private void deliver(String callbackId, boolean ok, String body) { final String script = "window.__wompCb && window.__wompCb(" + JSONObject.quote(callbackId) + "," + ok + "," + JSONObject.quote(body) + ")"; activity.runOnUiThread(() -> host.evalJs(script)); } }