From c6a253cb2349c2bc0babd9a26a8a85086aa16f40 Mon Sep 17 00:00:00 2001 From: PH2 <1293456824@qq.com> Date: Fri, 4 Sep 2020 12:05:27 +0800 Subject: [PATCH] =?UTF-8?q?1=E3=80=81=E7=BD=91=E7=BB=9C=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../zhiying_comm_example/MainActivity.java | 27 +++- example/lib/device_info_page.dart | 144 ++++++++++++++++++ example/lib/log_util.dart | 57 +++++++ example/lib/main.dart | 126 ++++++++++----- example/lib/package_info_page.dart | 77 ++++++++++ lib/util/global_config.dart | 2 +- lib/util/log/let_log.dart | 2 +- lib/util/net_util.dart | 67 ++++---- 8 files changed, 425 insertions(+), 77 deletions(-) create mode 100644 example/lib/device_info_page.dart create mode 100644 example/lib/log_util.dart create mode 100644 example/lib/package_info_page.dart diff --git a/example/android/app/src/main/java/cn/zhios/zhiying_comm_example/MainActivity.java b/example/android/app/src/main/java/cn/zhios/zhiying_comm_example/MainActivity.java index 15e7451..488f076 100644 --- a/example/android/app/src/main/java/cn/zhios/zhiying_comm_example/MainActivity.java +++ b/example/android/app/src/main/java/cn/zhios/zhiying_comm_example/MainActivity.java @@ -1,5 +1,6 @@ package cn.zhios.zhiying_comm_example; +import cn.zhios.zhiying_comm.ZhiyingCommPlugin; import cn.zhios.zhiying_comm.ZhiyingFlutterCommHandler; import cn.zhios.zhiying_comm.ZhiyingFlutterCommNativable; import cn.zhios.zhiying_comm.ZhiyingFlutterCommNative; @@ -9,18 +10,20 @@ import java.util.HashMap; import java.util.Map; import androidx.annotation.NonNull; + import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity implements ZhiyingFlutterCommNativable { - @Override - public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { - GeneratedPluginRegistrant.registerWith(flutterEngine); - ZhiyingFlutterCommNative.getInstance().regist((ZhiyingFlutterCommNativable) this); - } + @Override + public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { + GeneratedPluginRegistrant.registerWith(flutterEngine); + ZhiyingFlutterCommNative.getInstance().regist(this); + } - boolean localDebug = false; + + boolean localDebug = false; @Override public void openPage(Map params) { @@ -35,13 +38,21 @@ public class MainActivity extends FlutterActivity implements ZhiyingFlutterCommN @Override public Map getSetting() { Map map = new HashMap(); - map.put("domain", "http://120.76.175.204:8989"); + map.put("domain", "http://192.168.0.113:5000"); //"http://120.76.175.204:8989"); + map.put("master_id", "123456"); + map.put("secret_key", "123456"); + map.put("token", "123465"); return map; } @Override public void invokeMethod(String method, Map params, ZhiyingFlutterCommHandler handler) { - return ; + return; } + @Override + protected void onDestroy() { + super.onDestroy(); + ZhiyingFlutterCommNative.getInstance().unregist(); + } } diff --git a/example/lib/device_info_page.dart b/example/lib/device_info_page.dart new file mode 100644 index 0000000..3cd16d9 --- /dev/null +++ b/example/lib/device_info_page.dart @@ -0,0 +1,144 @@ +import 'dart:async'; + +import 'dart:io'; +import 'dart:ui'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:device_info/device_info.dart'; + + +class DeviceInfoPage extends StatefulWidget { + @override + _DeviceInfoPageState createState() => _DeviceInfoPageState(); +} + +class _DeviceInfoPageState extends State { + static final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin(); + Map _deviceData = {}; + + @override + void initState() { + super.initState(); + initPlatformState(); + } + + Future initPlatformState() async { + Map deviceData; + + try { + if (Platform.isAndroid) { + deviceData = _readAndroidBuildData(await deviceInfoPlugin.androidInfo); + } else if (Platform.isIOS) { + deviceData = _readIosDeviceInfo(await deviceInfoPlugin.iosInfo); + } + } on PlatformException { + deviceData = { + 'Error:': 'Failed to get platform version.' + }; + } + + if (!mounted) return; + + setState(() { + _deviceData = deviceData; + }); + } + + Map _readAndroidBuildData(AndroidDeviceInfo build) { + // 分辨率 + int width = window.physicalSize.width.floor(); + int height = window.physicalSize.height.floor(); + + return { + 'version.securityPatch': build.version.securityPatch, + 'version.sdkInt': build.version.sdkInt, + 'version.release': build.version.release, + 'version.previewSdkInt': build.version.previewSdkInt, + 'version.incremental': build.version.incremental, + 'version.codename': build.version.codename, + 'version.baseOS': build.version.baseOS, + 'board': build.board, + 'bootloader': build.bootloader, + 'brand': build.brand, + 'device': build.device, + 'display': build.display, + 'fingerprint': build.fingerprint, + 'hardware': build.hardware, + 'host': build.host, + 'id': build.id, + 'manufacturer': build.manufacturer, + 'model': build.model, + 'product': build.product, + 'supported32BitAbis': build.supported32BitAbis, + 'supported64BitAbis': build.supported64BitAbis, + 'supportedAbis': build.supportedAbis, + 'tags': build.tags, + 'type': build.type, + 'isPhysicalDevice': build.isPhysicalDevice, + 'androidId': build.androidId, + 'systemFeatures': build.systemFeatures, + '分辨率': '${width} * ${height}', + }; + } + + Map _readIosDeviceInfo(IosDeviceInfo data) { + + // 分辨率 + int width = window.physicalSize.width.floor(); + int height = window.physicalSize.height.floor(); + + return { + 'name': data.name, + 'systemName': data.systemName, + 'systemVersion': data.systemVersion, + 'model': data.model, + 'localizedModel': data.localizedModel, + 'identifierForVendor': data.identifierForVendor, + 'isPhysicalDevice': data.isPhysicalDevice, + 'utsname.sysname:': data.utsname.sysname, + 'utsname.nodename:': data.utsname.nodename, + 'utsname.release:': data.utsname.release, + 'utsname.version:': data.utsname.version, + 'utsname.machine:': data.utsname.machine, + '分辨率': '${width} * ${height}', + }; + } + + @override + Widget build(BuildContext context) { + return MaterialApp( + home: Scaffold( + appBar: AppBar( + title: Text( + Platform.isAndroid ? 'Android Device Info' : 'iOS Device Info'), + ), + body: ListView( + children: _deviceData.keys.map((String property) { + return Row( + children: [ + Container( + padding: const EdgeInsets.all(10.0), + child: Text( + property, + style: const TextStyle( + fontWeight: FontWeight.bold, + ), + ), + ), + Expanded( + child: Container( + padding: const EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0), + child: Text( + '${_deviceData[property]}', + maxLines: 10, + overflow: TextOverflow.ellipsis, + ), + )), + ], + ); + }).toList(), + ), + ), + ); + } +} \ No newline at end of file diff --git a/example/lib/log_util.dart b/example/lib/log_util.dart new file mode 100644 index 0000000..970f9d8 --- /dev/null +++ b/example/lib/log_util.dart @@ -0,0 +1,57 @@ + +import 'package:zhiying_comm/zhiying_comm.dart'; + +class LogUtil { + static void test() { + // log + Logger.log("this is log"); + +// debug + Logger.debug("this is debug", "this is debug message"); + +// warn + Logger.warn("this is warn", "this is a warning message"); + +// error + Logger.error("this is error", "this is a error message"); + +// test error + try { + final test = {}; + test["test"]["test"] = 1; + } catch (a, e) { + Logger.error(a, e); + } + +// time test + Logger.time("timeTest"); + Logger.endTime("timeTest"); + +// log net work + Logger.net( + "api/user/getUser", + data: {"user": "yung", "pass": "xxxxxx"}, + ); + Logger.endNet( + "api/user/getUser", + data: { + "users": [ + {"id": 1, "name": "yung", "avatar": "xxx"}, + {"id": 2, "name": "yung2", "avatar": "xxx"} + ] + }, + ); + +// log net work + Logger.net("ws/chat/getList", data: {"chanel": 1}, type: "Socket"); + Logger.endNet( + "ws/chat/getList", + data: { + "users": [ + {"id": 1, "name": "yung", "avatar": "xxx"}, + {"id": 2, "name": "yung2", "avatar": "xxx"} + ] + }, + ); + } +} diff --git a/example/lib/main.dart b/example/lib/main.dart index 947a402..c7584a8 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,8 +1,8 @@ import 'package:flutter/material.dart'; -import 'dart:async'; - -import 'package:flutter/services.dart'; import 'package:zhiying_comm/zhiying_comm.dart'; +import 'package:zhiying_comm_example/device_info_page.dart'; +import 'package:zhiying_comm_example/log_util.dart'; +import 'package:zhiying_comm_example/package_info_page.dart'; void main() => runApp(MyApp()); @@ -21,37 +21,95 @@ class _MyAppState extends State { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( - appBar: AppBar( - title: const Text('智莺-基础库'), - ), - body: Wrap( - direction: Axis.horizontal, - spacing: 5, - children: [ - RaisedButton( - onPressed: () { - NetUtil.post('/siteapi/v1/ucenter/login/', params: { - 'username': 'xiangguohui', - 'password': 'fnuo123com' - }); - }, - child: Text('登录请求'), - ), - RaisedButton( - onPressed: () { - NetUtil.request('/api/v1/rec/featured?page=1', - method: NetMethod.GET, params: {}); - }, - child: Text('页面请求'), - ), - RaisedButton( - onPressed: () { - NetUtil.request('/api/v1/config.json', params: {}); - }, - child: Text('基础配置'), - ) - ], - )), + appBar: AppBar( + title: const Text('智莺-基础库'), + ), + body: HomePage(), + ), + ); + } +} + +class HomePage extends StatelessWidget { + netPost() async { + dynamic result = await NetUtil.post('/api/v1/rec/featured?page=1', params: null); + print("result === ${result?.toString()}"); + } + + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + child: Center( + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + RaisedButton( + onPressed: () { + Navigator.push(context, MaterialPageRoute(builder: (_) { + return DeviceInfoPage(); + })); + }, + child: Text('设备信息'), + ), + RaisedButton( + onPressed: () { + Navigator.push(context, MaterialPageRoute(builder: (_) { + return PackageInfoPage(); + })); + }, + child: Text('应用信息'), + ), + RaisedButton( + onPressed: () { + NetUtil.post('/siteapi/v1/ucenter/login/', params: { + 'username': 'xiangguohui', + 'password': 'fnuo123com' + }); + }, + child: Text('登录请求'), + ), + RaisedButton( + onPressed: () { + NetUtil.request('/api/v1/rec/featured?page=1', params: null, + onError: (msg) { + print('onERROR = ${msg?.toString() ?? 'onError'}'); + }, onSuccess: (json) { + print('onSuccess = ${json?.toString() ?? 'onSuccess'}'); + }, onCache: (json) { + print('onCache = ${json?.toString() ?? 'onCache'}'); + }); + }, + child: Text('网络异步请求(带缓存)'), + ), + RaisedButton( + onPressed: () { + netPost(); + }, + child: Text('网络同步请求(无缓存)'), + ), + + RaisedButton( + onPressed: (){ + LogUtil.test(); + }, + child: Text('显示日志'), + ), + RaisedButton( + onPressed: (){ + Navigator.push(context, MaterialPageRoute( + builder: (_){ + return Logger(); + } + )); + }, + child: Text('打开日志视图'), + ), + + ], + ), + ), ); } } diff --git a/example/lib/package_info_page.dart b/example/lib/package_info_page.dart new file mode 100644 index 0000000..48b378b --- /dev/null +++ b/example/lib/package_info_page.dart @@ -0,0 +1,77 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// ignore_for_file: public_member_api_docs + +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:package_info/package_info.dart'; + +class PackageInfoPage extends StatelessWidget { + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'PackageInfo Demo', + theme: ThemeData(primarySwatch: Colors.blue), + home: MyHomePage(title: 'PackageInfo example app'), + ); + } +} + +class MyHomePage extends StatefulWidget { + MyHomePage({Key key, this.title}) : super(key: key); + + final String title; + + @override + _MyHomePageState createState() => _MyHomePageState(); +} + +class _MyHomePageState extends State { + PackageInfo _packageInfo = PackageInfo( + appName: 'Unknown', + packageName: 'Unknown', + version: 'Unknown', + buildNumber: 'Unknown', + ); + + @override + void initState() { + super.initState(); + _initPackageInfo(); + } + + Future _initPackageInfo() async { + final PackageInfo info = await PackageInfo.fromPlatform(); + setState(() { + _packageInfo = info; + }); + } + + Widget _infoTile(String title, String subtitle) { + return ListTile( + title: Text(title), + subtitle: Text(subtitle ?? 'Not set'), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text(widget.title), + ), + body: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + _infoTile('App name', _packageInfo.appName), + _infoTile('Package name', _packageInfo.packageName), + _infoTile('App version', _packageInfo.version), + _infoTile('Build number', _packageInfo.buildNumber), + ], + ), + ); + } +} \ No newline at end of file diff --git a/lib/util/global_config.dart b/lib/util/global_config.dart index b918aa6..7c99c19 100644 --- a/lib/util/global_config.dart +++ b/lib/util/global_config.dart @@ -4,5 +4,5 @@ class GlobalConfig { static final String HTTP_RESPONSE_KEY_MSG = 'msg'; static final String HTTP_RESPONSE_KEY_DATA = 'data'; /// 成功返回的CODE值 - static final int RESPONSE_SUCCESS_CODE = 200; + static final int RESPONSE_SUCCESS_CODE = 1; } diff --git a/lib/util/log/let_log.dart b/lib/util/log/let_log.dart index d3fb822..5dec19b 100644 --- a/lib/util/log/let_log.dart +++ b/lib/util/log/let_log.dart @@ -132,7 +132,7 @@ class Logger extends StatelessWidget { /// Recording network information static void net(String api, - {String type = "请求接口", int status = 100, Object data}) { + {String type = "接口", int status = 100, Object data}) { assert(api != null); if (enabled) _Net.request(api, type, status, data); } diff --git a/lib/util/net_util.dart b/lib/util/net_util.dart index a02b533..e35c5f9 100644 --- a/lib/util/net_util.dart +++ b/lib/util/net_util.dart @@ -153,39 +153,41 @@ class NetUtil { Response response; try { Dio dio = await NetUtil.getInstance().dio; - dio.request(path, - data: sign, options: Options(method: enumToString(method))); + response = await dio.request(path, data: sign, options: Options(method: enumToString(method))); } on DioError catch (e) { _formatError(e); } - if (response == null) { - return null; - } + try{ + var result = response.data is Map ? response.data : jsonDecode(response.data); + // TODO 解密? + if (result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] == + GlobalConfig.RESPONSE_SUCCESS_CODE || + result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] == + '${GlobalConfig.RESPONSE_SUCCESS_CODE}') { + if (onSuccess != null) { + onSuccess(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]); + // 缓存返回的数据 + _setCallBackCacheData(cacheKey, response.data is Map ? jsonEncode(response.data) : response.data); + } + return; + } - var result = jsonDecode(response.data); - //TODO 加密? - if (result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] == - GlobalConfig.RESPONSE_SUCCESS_CODE || - result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] == - '${GlobalConfig.RESPONSE_SUCCESS_CODE}') { - if (onSuccess != null) { - onSuccess(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]); - // 缓存返回的数据 - _setCallBackCacheData(cacheKey, response.data); + Logger.error('error: ' + result[GlobalConfig.HTTP_RESPONSE_KEY_MSG]); + Fluttertoast.showToast( + msg: result[GlobalConfig.HTTP_RESPONSE_KEY_MSG], + toastLength: Toast.LENGTH_SHORT, + gravity: ToastGravity.BOTTOM, + ); + if (onError != null) { + onError(result[GlobalConfig.HTTP_RESPONSE_KEY_MSG] ?? '未知错误'); + } + }catch (e){ + if (onError != null) { + onError(e?.toString() ?? '未知错误'); } - return; } - Logger.error('error: ' + result[GlobalConfig.HTTP_RESPONSE_KEY_MSG]); - Fluttertoast.showToast( - msg: result[GlobalConfig.HTTP_RESPONSE_KEY_MSG], - toastLength: Toast.LENGTH_SHORT, - gravity: ToastGravity.BOTTOM, - ); - if (onError != null) { - onError(result[GlobalConfig.HTTP_RESPONSE_KEY_MSG] ?? '未知错误'); - } return; } @@ -273,14 +275,13 @@ class NetUtil { // 读取缓存 Map cacheMap = await SharedPreferencesUtil.getNetCacheResult(cacheKey); + if (!EmptyUtil.isEmpty(cacheMap) && - cacheMap.containsKey(GlobalConfig.RESPONSE_SUCCESS_CODE) && - (cacheMap[GlobalConfig.RESPONSE_SUCCESS_CODE] == - GlobalConfig.RESPONSE_SUCCESS_CODE || - cacheMap[GlobalConfig.RESPONSE_SUCCESS_CODE] == - '${GlobalConfig.RESPONSE_SUCCESS_CODE}') && + cacheMap.containsKey(GlobalConfig.HTTP_RESPONSE_KEY_CODE) && + (cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] == GlobalConfig.RESPONSE_SUCCESS_CODE || + cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] == '${GlobalConfig.RESPONSE_SUCCESS_CODE}') && null != cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA]) { - onCache(cacheMap['data']); + onCache(cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA]); return; } return; @@ -341,14 +342,14 @@ class NetUtil { class _NetInterceptors extends InterceptorsWrapper { @override Future onRequest(RequestOptions options) { - Logger.net(options?.path, data: options.data.toString()); + Logger.net(options?.uri?.toString(), data: options.data.toString()); // TODO 加密? return super.onRequest(options); } @override Future onResponse(Response response) { - Logger.endNet(response?.statusCode?.toString(), + Logger.endNet(response?.request?.uri?.toString(), data: response?.data?.toString() ?? ''); // TODO 解密? return super.onResponse(response);