web_page.dart
15.6 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
import 'dart:async';
import 'package:device_info/device_info.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:one_key/net/dio_util.dart';
import 'package:one_key/res/colors.dart';
import 'package:one_key/utils/event_bus.dart';
import 'package:one_key/utils/utils.dart';
import 'package:one_key/widgets/system_app_bar.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:one_key/utils/event_bus.dart';
import 'package:one_key/widgets/app_bar.dart';
import 'package:one_key/widgets/system_app_bar.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:collection';
// import 'package:open_file/open_file.dart';
// import 'package:flutter_downloader/flutter_downloader.dart';
class WebPage extends StatefulWidget {
final String title;
final String url;
final bool need;
const WebPage({Key key, this.title, this.url, this.need = false})
: super(key: key);
@override
_WebPageState createState() => _WebPageState();
}
class _WebPageState extends State<WebPage> {
final GlobalKey webViewKey = GlobalKey();
InAppWebViewController webViewController;
InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
useShouldOverrideUrlLoading: true,
useOnDownloadStart: true,
mediaPlaybackRequiresUserGesture: false,
),
android: AndroidInAppWebViewOptions(
useHybridComposition: true,
),
ios: IOSInAppWebViewOptions(
allowsInlineMediaPlayback: true,
));
PullToRefreshController pullToRefreshController;
ContextMenu contextMenu;
String url = "";
double progress = 0;
final urlController = TextEditingController();
// Future<void> openFile(filePath) async {
// final _result = await OpenFile.open(filePath);
// print(_result.message);
// // setState(() {
// // _openResult = "type=${_result.type} message=${_result.message}";
// // });
// }
@override
void initState() {
super.initState();
// Enable hybrid composition.
_init();
}
Future<bool> _checkPermission() async {
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
if (Platform.isAndroid && androidInfo.version.sdkInt <= 28) {
final status = await Permission.storage.status;
if (status != PermissionStatus.granted) {
final result = await Permission.storage.request();
if (result == PermissionStatus.granted) {
return true;
}
} else {
return true;
}
} else {
return true;
}
return false;
}
Future<bool> checkPermissionStorage() async {
var status = await Permission.storage.status;
if (!status.isGranted) {
status = await Permission.storage.request();
if (status.isGranted) {
return true;
}
} else {
return true;
}
return false;
}
_init() async {
// WidgetsFlutterBinding.ensureInitialized();
// await FlutterDownloader.initialize(debug: true);
if (Platform.isAndroid) {
await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
var swAvailable = await AndroidWebViewFeature.isFeatureSupported(
AndroidWebViewFeature.SERVICE_WORKER_BASIC_USAGE);
var swInterceptAvailable = await AndroidWebViewFeature.isFeatureSupported(
AndroidWebViewFeature.SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST);
if (swAvailable && swInterceptAvailable) {
AndroidServiceWorkerController serviceWorkerController =
AndroidServiceWorkerController.instance();
serviceWorkerController.serviceWorkerClient =
AndroidServiceWorkerClient(
shouldInterceptRequest: (request) async {
print(request);
return null;
},
);
}
}
// await FlutterDownloader.initialize(
// debug: true // optional: set false to disable printing logs to console
// );
await Permission.storage.request();
}
@override
Widget build(BuildContext context) {
return Scaffold(
// We're using a Builder here so we have a context that is below the Scaffold
// to allow calling Scaffold.of(context) so we can show a snackbar.
appBar: SystemAppBar(
widget.title,
onTap: () {
if (widget.need) {
Utils.changeStatusColor(color: MyColours.color_199095);
}
Navigator.of(context).pop();
},
),
body: WillPopScope(
onWillPop: () async {
if (widget.need) {
Utils.changeStatusColor(color: MyColours.color_199095);
}
return true;
},
child: Column(
children: [
Expanded(
child: InAppWebView(
key: webViewKey,
// contextMenu: contextMenu,
initialUrlRequest: URLRequest(
url: Uri.parse("http://colorcun.com/privacy1.html")),
// initialFile: "assets/index.html",
initialUserScripts: UnmodifiableListView<UserScript>([]),
initialOptions: options,
pullToRefreshController: pullToRefreshController,
onWebViewCreated: (controller) {
webViewController = controller;
},
onLoadStart: (controller, url) {
setState(() {
this.url = url.toString();
urlController.text = this.url;
});
},
androidOnPermissionRequest:
(controller, origin, resources) async {
return PermissionRequestResponse(
resources: resources,
action: PermissionRequestResponseAction.GRANT);
},
shouldOverrideUrlLoading:
(controller, navigationAction) async {
var uri = navigationAction.request.url;
if (![
"http",
"https",
"file",
"chrome",
"data",
"javascript",
"about"
].contains(uri.scheme)) {
if (await canLaunch(url)) {
// Launch the App
await launch(
url,
);
// and cancel the request
return NavigationActionPolicy.CANCEL;
}
}
return NavigationActionPolicy.ALLOW;
},
onLoadStop: (controller, url) async {
pullToRefreshController.endRefreshing();
setState(() {
this.url = url.toString();
urlController.text = this.url;
});
},
onLoadError: (controller, url, code, message) {
pullToRefreshController.endRefreshing();
},
onProgressChanged: (controller, progress) {
if (progress == 100) {
pullToRefreshController.endRefreshing();
}
setState(() {
this.progress = progress / 100;
urlController.text = this.url;
});
},
onUpdateVisitedHistory: (controller, url, androidIsReload) {
setState(() {
this.url = url.toString();
urlController.text = this.url;
});
},
onConsoleMessage: (controller, consoleMessage) {
print(consoleMessage);
},
onDownloadStart: (controller, url) async {
print("onDownloadStart $url");
Utils.showToast('开始下载...');
// final taskId = await FlutterDownloader.enqueue(
// url: url.toString(),
// savedDir: (await getExternalStorageDirectory()).path,
// showNotification:
// true, // show download progress in status bar (for Android)
// openFileFromNotification:
// true, // click on notification to open downloaded file (for Android)
// );
final dir = await getExternalStorageDirectory();
String savePath = dir.path + "/one_key";
Directory directory = new Directory(savePath);
if (directory.existsSync()) {
//删除历史apk
final List<FileSystemEntity> files = directory.listSync();
for (FileSystemEntity file in files) {
file.deleteSync();
}
}
DioUtil().download(url.toString(), savePath,
onProgress: (received, total) {
// if (_progress != 100) {
// int progress = ((received / total) * 100).round();
// _progress = progress;
// _setState(() {});
// }
if (received == total) {
print('object');
Utils.showToast('文件已保存在${savePath}');
// openFile(savePath);
//下载完成
// InstallPlugin.installApk(savePath, "com.naji.one_key");
}
});
// },
// DioUtil().download(url.toString(),
// (await getExternalStorageDirectory()).path,
// onProgress: (received, total) {
// // if (_progress != 100) {
// // int progress = ((received / total) * 100).round();
// // _progress = progress;
// // _setState(() {});
// // }
// if (received == total) {
// //下载完成
// // InstallPlugin.installApk(savePath, "com.naji.one_key");
// }
// });
},
))
],
)
// Builder(builder: (BuildContext context) {
// return WebView(
// initialUrl: "http://colorcun.com/privacy1.html",
// javascriptMode: JavascriptMode.unrestricted,
// onWebViewCreated: (WebViewController webViewController) {
// _controller.complete(webViewController);
// },
// // TODO(iskakaushik): Remove this when collection literals makes it to stable.
// // ignore: prefer_collection_literals
// javascriptChannels: <JavascriptChannel>[
// _toasterJavascriptChannel(context),
// ].toSet(),
// navigationDelegate: (NavigationRequest request) {
// if (request.url.startsWith('https://www.youtube.com/')) {
// print('blocking navigation to $request}');
// return NavigationDecision.prevent;
// }
// print('allowing navigation to $request');
// return NavigationDecision.navigate;
// },
// onPageStarted: (String url) {
// print('Page started loading: $url');
// },
// onPageFinished: (String url) async {
// print('Page finished loading: $url');
// // showDownloadProgress(context);
// final dir = await getExternalStorageDirectory();
// String savePath = dir.path + "/one_key";
// DioUtil().download(url, savePath,
// onProgress: (received, total) {
// // if (_progress != 100) {
// // int progress = ((received / total) * 100).round();
// // _progress = progress;
// // _setState(() {});
// // }
// if (received == total) {
// print('object');
// //下载完成
// // InstallPlugin.installApk(savePath, "com.naji.one_key");
// }
// });
// },
// gestureNavigationEnabled: true,
// );
// }),
));
}
// JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
// return JavascriptChannel(
// name: 'Toaster',
// onMessageReceived: (JavascriptMessage message) {
// Scaffold.of(context).showSnackBar(
// SnackBar(content: Text(message.message)),
// );
// });
// }
}
// class WebPage extends StatelessWidget {
// final String title;
// final String url;
// final bool need;
// const WebPage({Key key, this.title, this.url, this.need = false})
// : super(key: key);
// @override
// Widget build(BuildContext context) {
// final Completer<WebViewController> _controller =
// Completer<WebViewController>();
// return Scaffold(
// appBar: SystemAppBar(title, onTap: () {
// if (need) {
// Utils.changeStatusColor(color: MyColours.color_199095);
// }
// Navigator.of(context).pop();
// }),
// body: WillPopScope(
// onWillPop: () async {
// if (need) {
// Utils.changeStatusColor(color: MyColours.color_199095);
// }
// return true;
// },
// child: WebView(
// initialUrl: "http://colorcun.com/privacy1.html",
// javascriptMode: JavascriptMode.unrestricted,
// onWebViewCreated: (WebViewController webViewController) {
// // Loading.showLoading(context);
// _controller.complete(webViewController);
// },
// javascriptChannels: <JavascriptChannel>[
// _toasterJavascriptChannel(context),
// ].toSet(),
// navigationDelegate: (NavigationRequest request) {
// if (request.url.startsWith('https://www.youtube.com/')) {
// return NavigationDecision.prevent;
// }
// return NavigationDecision.navigate;
// },
// onPageStarted: (String url) {},
// onPageFinished: (String url) {
// // Loading.hideLoading(context);
// },
// gestureNavigationEnabled: true,
// )),
// );
// }
// JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
// return JavascriptChannel(
// name: 'Toaster',
// onMessageReceived: (JavascriptMessage message) {
// Scaffold.of(context).showSnackBar(
// SnackBar(content: Text(message.message)),
// );
// });
// }
// }