-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNativeBridge.java
More file actions
652 lines (587 loc) · 22.1 KB
/
Copy pathNativeBridge.java
File metadata and controls
652 lines (587 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
package com.example.cheng.js;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.os.VibratorManager;
import android.webkit.JavascriptInterface;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
/**
* JS 可调用桥:注册为 window.NativeBridge
* <p>
* 覆盖经典场景:同步调用、返回值、JSON、异步回调、系统能力、页面控制等。
*/
public class NativeBridge {
public interface Host {
Activity getActivity();
void updateStatus(String text);
void evaluateJavascript(String script);
void startQrScan();
void openFilePicker();
void reloadWebView();
void goBackWebView();
boolean canGoBackWebView();
void closePage();
void openExternalUrl(String url);
void setActivityTitle(String title);
/** Whether current page is allowed to call sensitive APIs */
boolean isTrustedPage();
void requestLocation(String callbackName);
void pickImageAsBase64(String callbackName);
String getCookie(String url);
void setCookie(String url, String cookie);
}
private final Host host;
public NativeBridge(Host host) {
this.host = host;
}
// ---------- UI / Feedback ----------
@JavascriptInterface
public void showToast(final String message) {
runOnUi(new Runnable() {
@Override
public void run() {
Toast.makeText(host.getActivity(), message == null ? "" : message, Toast.LENGTH_SHORT).show();
}
});
}
@JavascriptInterface
public void showDialog(final String title, final String message) {
runOnUi(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(host.getActivity())
.setTitle(title == null ? "提示" : title)
.setMessage(message == null ? "" : message)
.setPositiveButton("确定", null)
.show();
}
});
}
/**
* Native confirm:结果通过 callbackName(true/false) 回传
*/
@JavascriptInterface
public void showConfirm(final String title, final String message, final String callbackName) {
runOnUi(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(host.getActivity())
.setTitle(title == null ? "确认" : title)
.setMessage(message == null ? "" : message)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
invokeBoolCallback(callbackName, true);
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
invokeBoolCallback(callbackName, false);
}
})
.setCancelable(true)
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
invokeBoolCallback(callbackName, false);
}
})
.show();
}
});
}
/**
* Native prompt:结果通过 callbackName(text|null) 回传
*/
@JavascriptInterface
public void showPrompt(final String title, final String defaultText, final String callbackName) {
runOnUi(new Runnable() {
@Override
public void run() {
final EditText input = new EditText(host.getActivity());
input.setText(defaultText == null ? "" : defaultText);
new AlertDialog.Builder(host.getActivity())
.setTitle(title == null ? "输入" : title)
.setView(input)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
invokeStringCallback(callbackName, input.getText().toString());
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
invokeStringCallback(callbackName, null);
}
})
.show();
}
});
}
@JavascriptInterface
public void setNativeStatus(final String text) {
runOnUi(new Runnable() {
@Override
public void run() {
host.updateStatus(text);
}
});
}
@JavascriptInterface
public void setTitle(final String title) {
runOnUi(new Runnable() {
@Override
public void run() {
host.setActivityTitle(title);
}
});
}
@JavascriptInterface
public void vibrate(final int milliseconds) {
runOnUi(new Runnable() {
@Override
public void run() {
int ms = milliseconds <= 0 ? 40 : Math.min(milliseconds, 2000);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
VibratorManager vm = (VibratorManager) host.getActivity()
.getSystemService(Context.VIBRATOR_MANAGER_SERVICE);
if (vm != null) {
vm.getDefaultVibrator().vibrate(
VibrationEffect.createOneShot(ms, VibrationEffect.DEFAULT_AMPLITUDE));
}
} else {
Vibrator v = (Vibrator) host.getActivity().getSystemService(Context.VIBRATOR_SERVICE);
if (v != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(ms, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
v.vibrate(ms);
}
}
}
} catch (Exception ignored) {
}
}
});
}
// ---------- Device / App info ----------
@JavascriptInterface
public String getDeviceInfo() {
JSONObject json = new JSONObject();
try {
json.put("manufacturer", Build.MANUFACTURER);
json.put("model", Build.MODEL);
json.put("sdkInt", Build.VERSION.SDK_INT);
json.put("release", Build.VERSION.RELEASE);
json.put("brand", Build.BRAND);
json.put("device", Build.DEVICE);
} catch (JSONException ignored) {
}
return json.toString();
}
@JavascriptInterface
public String getAppInfo() {
JSONObject json = new JSONObject();
Activity act = host.getActivity();
try {
PackageManager pm = act.getPackageManager();
PackageInfo info = pm.getPackageInfo(act.getPackageName(), 0);
json.put("packageName", act.getPackageName());
json.put("versionName", info.versionName);
json.put("versionCode", Build.VERSION.SDK_INT >= 28
? info.getLongVersionCode()
: info.versionCode);
} catch (Exception e) {
try {
json.put("error", e.getMessage());
} catch (JSONException ignored) {
}
}
return json.toString();
}
@JavascriptInterface
public String getNetworkInfo() {
JSONObject json = new JSONObject();
try {
ConnectivityManager cm = (ConnectivityManager) host.getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
String type = "none";
boolean connected = false;
if (cm != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
android.net.Network network = cm.getActiveNetwork();
NetworkCapabilities caps = network != null ? cm.getNetworkCapabilities(network) : null;
if (caps != null) {
connected = caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
type = "wifi";
} else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
type = "cellular";
} else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
type = "ethernet";
} else {
type = "other";
}
}
} else {
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
connected = true;
type = ni.getTypeName() == null ? "other" : ni.getTypeName().toLowerCase();
}
}
}
json.put("connected", connected);
json.put("type", type);
} catch (JSONException ignored) {
}
return json.toString();
}
// ---------- Data ----------
@JavascriptInterface
public void postJson(final String json) {
runOnUi(new Runnable() {
@Override
public void run() {
try {
JSONObject obj = new JSONObject(json == null ? "{}" : json);
String name = obj.optString("name", "(unknown)");
int count = obj.optInt("count", 0);
host.updateStatus("JSON: name=" + name + ", count=" + count);
Toast.makeText(host.getActivity(), "已解析 JSON", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
host.updateStatus("JSON 解析失败: " + e.getMessage());
}
}
});
}
/**
* 异步:Native 处理后调用 window[callbackName](resultObject)
*/
@JavascriptInterface
public void callNativeAsync(final String action, final String payload, final String callbackName) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(600);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
final String result;
try {
JSONObject out = new JSONObject();
out.put("ok", true);
out.put("action", action == null ? "" : action);
out.put("echo", payload == null ? "" : payload);
out.put("from", "NativeBridge");
out.put("ts", System.currentTimeMillis());
result = out.toString();
} catch (JSONException e) {
return;
}
runOnUi(new Runnable() {
@Override
public void run() {
String safeName = sanitizeCallback(callbackName);
if (safeName == null) {
return;
}
host.evaluateJavascript("typeof window['" + safeName + "']==='function'&&window['"
+ safeName + "'](" + result + ")");
}
});
}
}).start();
}
// ---------- System intents ----------
@JavascriptInterface
public void copyToClipboard(final String text) {
runOnUi(new Runnable() {
@Override
public void run() {
ClipboardManager cm = (ClipboardManager) host.getActivity()
.getSystemService(Context.CLIPBOARD_SERVICE);
if (cm != null) {
cm.setPrimaryClip(ClipData.newPlainText("jsbridge", text == null ? "" : text));
Toast.makeText(host.getActivity(), "已复制到剪贴板", Toast.LENGTH_SHORT).show();
}
}
});
}
@JavascriptInterface
public String readClipboard() {
ClipboardManager cm = (ClipboardManager) host.getActivity()
.getSystemService(Context.CLIPBOARD_SERVICE);
if (cm == null || cm.getPrimaryClip() == null || cm.getPrimaryClip().getItemCount() == 0) {
return "";
}
CharSequence text = cm.getPrimaryClip().getItemAt(0).coerceToText(host.getActivity());
return text == null ? "" : text.toString();
}
@JavascriptInterface
public void shareText(final String text) {
runOnUi(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, text == null ? "" : text);
host.getActivity().startActivity(Intent.createChooser(intent, "分享到"));
}
});
}
@JavascriptInterface
public void openExternal(final String url) {
runOnUi(new Runnable() {
@Override
public void run() {
host.openExternalUrl(url);
}
});
}
@JavascriptInterface
public void dial(final String phone) {
runOnUi(new Runnable() {
@Override
public void run() {
if (phone == null || phone.length() == 0) {
return;
}
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
try {
host.getActivity().startActivity(intent);
} catch (Exception e) {
Toast.makeText(host.getActivity(), "无法打开拨号盘", Toast.LENGTH_SHORT).show();
}
}
});
}
@JavascriptInterface
public void sendSms(final String phone, final String body) {
runOnUi(new Runnable() {
@Override
public void run() {
Uri uri = Uri.parse("smsto:" + (phone == null ? "" : phone));
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", body == null ? "" : body);
try {
host.getActivity().startActivity(intent);
} catch (Exception e) {
Toast.makeText(host.getActivity(), "无法打开短信", Toast.LENGTH_SHORT).show();
}
}
});
}
@JavascriptInterface
public void sendEmail(final String to, final String subject, final String body) {
runOnUi(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:" + (to == null ? "" : to)));
intent.putExtra(Intent.EXTRA_SUBJECT, subject == null ? "" : subject);
intent.putExtra(Intent.EXTRA_TEXT, body == null ? "" : body);
try {
host.getActivity().startActivity(Intent.createChooser(intent, "发送邮件"));
} catch (Exception e) {
Toast.makeText(host.getActivity(), "无法打开邮件应用", Toast.LENGTH_SHORT).show();
}
}
});
}
// ---------- Media / scan / file ----------
@JavascriptInterface
public void startScan() {
runOnUi(new Runnable() {
@Override
public void run() {
host.startQrScan();
}
});
}
@JavascriptInterface
public void pickFile() {
runOnUi(new Runnable() {
@Override
public void run() {
host.openFilePicker();
}
});
}
// ---------- Page control ----------
@JavascriptInterface
public void reload() {
runOnUi(new Runnable() {
@Override
public void run() {
host.reloadWebView();
}
});
}
@JavascriptInterface
public void goBack() {
runOnUi(new Runnable() {
@Override
public void run() {
host.goBackWebView();
}
});
}
@JavascriptInterface
public boolean canGoBack() {
return host.canGoBackWebView();
}
@JavascriptInterface
public void closePage() {
runOnUi(new Runnable() {
@Override
public void run() {
host.closePage();
}
});
}
// ---------- Cookie / Location / Image / Auth ----------
@JavascriptInterface
public String getCookie(String url) {
String value = host.getCookie(url);
return value == null ? "" : value;
}
@JavascriptInterface
public void setCookie(final String url, final String cookie) {
runOnUi(new Runnable() {
@Override
public void run() {
host.setCookie(url, cookie);
Toast.makeText(host.getActivity(), "Cookie 已写入", Toast.LENGTH_SHORT).show();
}
});
}
@JavascriptInterface
public void getLocation(final String callbackName) {
runOnUi(new Runnable() {
@Override
public void run() {
host.requestLocation(callbackName);
}
});
}
@JavascriptInterface
public void pickImageBase64(final String callbackName) {
runOnUi(new Runnable() {
@Override
public void run() {
host.pickImageAsBase64(callbackName);
}
});
}
/**
* Production-style gate: requires demo token + trusted page origin.
* Demo token: demo-token-jsandroid
*/
@JavascriptInterface
public String secureCall(String token, String action, String payload) {
JSONObject out = new JSONObject();
try {
if (!host.isTrustedPage()) {
out.put("ok", false);
out.put("error", "untrusted_origin");
return out.toString();
}
if (!"demo-token-jsandroid".equals(token)) {
out.put("ok", false);
out.put("error", "unauthorized");
return out.toString();
}
out.put("ok", true);
out.put("action", action == null ? "" : action);
out.put("echo", payload == null ? "" : payload);
out.put("from", "secureCall");
out.put("ts", System.currentTimeMillis());
} catch (JSONException ignored) {
}
return out.toString();
}
@JavascriptInterface
public boolean isTrustedPage() {
return host.isTrustedPage();
}
// ---------- helpers ----------
private void invokeBoolCallback(String callbackName, boolean value) {
String safe = sanitizeCallback(callbackName);
if (safe == null) {
return;
}
host.evaluateJavascript("typeof window['" + safe + "']==='function'&&window['"
+ safe + "'](" + value + ")");
}
private void invokeStringCallback(String callbackName, String value) {
String safe = sanitizeCallback(callbackName);
if (safe == null) {
return;
}
host.evaluateJavascript("typeof window['" + safe + "']==='function'&&window['"
+ safe + "'](" + jsonStringLiteral(value) + ")");
}
private static String sanitizeCallback(String callbackName) {
if (callbackName == null || callbackName.length() == 0) {
return null;
}
String safe = callbackName.replaceAll("[^A-Za-z0-9_$]", "");
return safe.length() == 0 ? null : safe;
}
private void runOnUi(Runnable r) {
host.getActivity().runOnUiThread(r);
}
static String jsonStringLiteral(String value) {
if (value == null) {
return "null";
}
StringBuilder sb = new StringBuilder("\"");
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case '\\':
case '"':
sb.append('\\').append(c);
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
default:
if (c < 0x20) {
sb.append(String.format("\\u%04x", (int) c));
} else {
sb.append(c);
}
}
}
sb.append('"');
return sb.toString();
}
}