import TitleBar from './TitleBar' import mainViewModel, { MainViewModel } from '../viewmodel/MainViewModel'; import ItemData from '../viewmodel/ItemData'; import { promptAction, router, Scale } from '@kit.ArkUI'; import { CommonConstants } from '../common/constants/CommonConstants'; import { wifiManager } from '@kit.ConnectivityKit'; import { AppUtil, LogUtil, NetworkUtil, PermissionUtil, PickerUtil, PreferencesUtil, RandomUtil, ScanUtil, StrUtil, ToastUtil } from '@pura/harmony-utils'; import wifi from '@ohos.wifiManager' import Logger from '../common/util/Logger'; import { common, Permissions, Want } from '@kit.AbilityKit'; import { ErrorEvent } from '@kit.ArkTS'; import { BusinessError } from '@kit.BasicServicesKit'; import { picker } from '@kit.CoreFileKit'; import { photoAccessHelper } from '@kit.MediaLibraryKit'; import { PullToRefresh } from '@ohos/pulltorefresh'; import { Utility } from '../common/util/Utility'; import { AnimationHelper, DialogAction,DialogHelper } from '@pura/harmony-dialog'; import { DialogUtil } from '@pura/harmony-utils'; import { DrawerOptions } from '../dialog/DrawerOptions'; import WifiType from '../viewmodel/WiFiType'; const TAG = 'ToolView' interface GeneratedObjectLiteralInterface_1 { bundleName: string; abilityName: string; action: string; } @Preview @Component export struct ToolView{ @State isListening: boolean = true; // 控制组件状态 true:开启水波纹 false:停止水波纹 private linkedInfo: wifi.WifiLinkedInfo = null! @State isLinked: boolean = false @StorageLink('wifiList') wifiList: Array = [] @State uriStr: string = '' @State scanResult: string = '' private scroller: Scroller = new Scroller(); @State currentName: string = '' @State ssid: string = '' @State state:AnimationStatus = AnimationStatus.Initial @State textWifi:string ='未连接' @State count:number =0 //连接、通讯历史记录 @State msgHistory: string = '' @State titleBarModel: TitleBar.Model = new TitleBar.Model() .setLeftIcon(null) .setTitleTextStyle(FontStyle.Normal) .setTitleName("工具") .setTitleFontColor(Color.White) .setTitleBarBackground($r('app.color.title_bar_bg')) .setTitleBarBottomLineColor($r('app.color.title_bar_bg')) @State bundleName:string ='' // 组件生命周期 async aboutToAppear() { this.initDialogConfig() this.bundleName = await AppUtil.getBundleName() this.scan() // 启动监听 this.addListener() console.info('LifeCycleComponent aboutToAppear'); } initDialogConfig() { DialogHelper.setDefaultConfig((config) => { config.alignment = DialogAlignment.Center; //弹窗的对齐方式。 config.offset = { dx: 0, dy: 0 }; //弹窗相对alignment所在位置的偏移量。默认值:{ dx: 0, dy: 0 } config.maskColor = 0x33000000; //自定义蒙层颜色。默认值 0x33000000 config.backgroundColor = $r('app.color.pri_bg'); //弹窗背板颜色。默认值:Color.White config.backgroundBlurStyle = BlurStyle.NONE; //弹窗背板模糊材质。默认值:BlurStyle.COMPONENT_ULTRA_THICK config.cornerRadius = 20; //设置背板的圆角半径。可分别设置4个圆角的半径。 }) } // 组件消失生命周期 aboutToDisappear() { console.info('LifeCycleComponent aboutToDisappear'); } // 扫描wifi async scan() { } //当前连接wifi的info和名称 async getLinkedInfo() { } // 监听wifi的变化 addListener() { } //跳转到市场界面进行好评 gotoHao(){ const want: Want = { uri: `store://appgallery.huawei.com/app/detail?id=${this.bundleName}` }; const context = getContext(this) as common.UIAbilityContext; context.startAbility(want).then(()=>{ //拉起成功 }).catch(()=>{ // 拉起失败 }); } //好评的自定义内容 @Builder customHaoPingBuilder(content: string) { Column() { Text(content) .fontColor(Color.White) .fontSize(16) .alignSelf(ItemAlign.Start) .fontColor(Color.White) .margin({bottom:15}) .fontSize(16) Row(){ Button('取消') .fontColor(Color.White) .linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]}) .height(50) .layoutWeight(1) .stateEffect(true) .margin({right:6}) .onClick(()=>{ DialogHelper.closeDialog('haoping'); //关闭弹框 }) Button('好评') .fontColor(Color.White) .linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]}) .layoutWeight(1) .height(50) .stateEffect(true) .margin({left:6}) .onClick(()=>{ DialogHelper.closeDialog('haoping'); //关闭弹框 this.gotoHao() PreferencesUtil.putSync("is_haoping", true); }) } } .width("100%") .padding(10) } showHaopingDialog(){ DialogHelper.showCustomContentDialog({ dialogId:'haoping', title: "该功能免费", autoCancel: false, //点击遮障层时,不关闭弹窗 backCancel: true, //点击返回键,不关闭弹窗 contentBuilder: () => { this.customHaoPingBuilder("如果您觉得好用可以给个好评吗?谢谢!\n给个好评吧,非常感谢您的支持!") }, buttons: [], }) } //自定义文本和图片 @Builder customSeeBuilder(content: string) { Column() { Text(content) .fontColor(Color.White) .fontSize(16) // Text(){ // Span('点我查看华为截屏教程') // .fontColor($r('app.color.white')) // .decoration({ type: TextDecorationType.Underline, color:$r('app.color.white') }) // .onClick(()=>{ // DialogHelper.closeDialog('dig'); //关闭弹框 // router.pushUrl({url:'pages/WebIndex', // params:{ titleName:'截图教程',webUrl:$rawfile('jieping.html')} // },router.RouterMode.Single); // // // }) // } // .alignSelf(ItemAlign.Start) // .fontColor(Color.White) // .visibility(Visibility.None) // .margin({bottom:15}) // .fontSize(16) Row(){ Button('1、截图') .fontColor(Color.White) .linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]}) .height(50) .layoutWeight(1) .stateEffect(true) .margin({right:6}) .onClick(()=>{ this.goSystemWifiSetting() }) Button('2、选图') .fontColor(Color.White) .linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]}) .layoutWeight(1) .height(50) .stateEffect(true) .margin({left:6}) .onClick(()=>{ DialogHelper.closeDialog('dig'); //关闭弹框 this.goSelectPhoto() }) } } .width("100%") .padding(10) } async showSeePwdDialog(){ if(Utility.isFreeTime()){ let isHao:boolean = PreferencesUtil.getBooleanSync('is_haoping'); if(!isHao){ this.showHaopingDialog() return } } DialogHelper.showCustomContentDialog({ dialogId:'dig', title: "提示:请按如下教程", contentBuilder: () => { this.customSeeBuilder("第一步:请点击【1、截图】按钮,去系统的WIFI设置界面点到wifi分享二维码界面,然后截图。\n\n第二步:点击【2、选图】按钮,选择该截图的图片进行wifi密码解析。\n") }, buttons: [], }) } showFileDialog() { let ps: Permissions = 'ohos.permission.READ_MEDIA'; // let ps: Permissions[] = ['ohos.permission.READ_MEDIA']; PermissionUtil.checkPermissions(ps).then((result) => { if (result) { //有文件权限,直接调用第一步和第二部对话框 this.showSeePwdDialog() } else { Logger.info(TAG, 'not file permissions state:') //没有文件权限 // this.showRuqFile(); } }) } // async showRuqFile(){ // // // DialogUtil.showPrimaryDialog({ // backgroundColor:$r('app.color.btn_green'), // title: "申请文件权限", // message: '此功能需要读取相册截图的WiFi的二维码图片,从而解析出当前wifi连接的密码。所以需要向您申请文件存储权限,如果紧急将无法使用该功能。\n', // borderStyle:BorderStyle.Dashed, // primaryButton: { // backgroundColor:$r('app.color.btn_green'), // value: "取消申请", // action: () => { // // } // }, // secondaryButton: { // backgroundColor:$r('app.color.btn_red'), // value: "现在申请", // action: () => { // let ps: Permissions[] = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA']; // PermissionUtil.requestPermissions(ps).then((result) => { // if (result) { // this.showSeePwdDialog() // } else { // ToastUtil.showLong("请在设置中打开权限") // // AppUtil.toAppSetting() // } // }) // } // }, // onWillDismiss: (dismissDialogAction: DismissDialogAction) => { // LogUtil.error("showPrimaryDialog-onWillDismiss: " + JSON.stringify(dismissDialogAction)) // if (dismissDialogAction.reason == DismissReason.PRESS_BACK) { // dismissDialogAction.dismiss() // } // if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) { // dismissDialogAction.dismiss() // } // } // }) // } //拉起相册的选择刚刚截图的二维码图片进行扫描解析密码 goSelectPhoto(){ let options = new photoAccessHelper.PhotoSelectOptions(); options.maxSelectNumber = 1; options.MIMEType =photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; //调用系统的相册 // PickerUtil.selectPhoto(options).then((uris) => { // this.uriStr = uris[0]; // // Logger.info(TAG, 'select photo uri:' + uris[0]) // //获得二维码图片uri用scan进行扫描 // ScanUtil.onDetectBarCode(uris[0]).then((scanResult)=>{ // // this.showPwdResultDialog(scanResult[0].originalValue); // Logger.info(TAG, 'scan select photo result:' + scanResult[0].originalValue) // // Logger.info(TAG, 'scan select photo result:' +JSON.stringify(scanResult, null, 2)) // }).catch((err: BusinessError) => { // this.uriStr = `扫描二维码异常:\n${JSON.stringify(err)}` // }) // // }).catch((err: BusinessError) => { // this.uriStr = `调用相册,异常:\n${JSON.stringify(err)}` // }) } //自定义文本和图片 @Builder customShowPwdBuilder(result: string) { Column() { Text('WiFi名称:'+getWiFiName(result)+'\n\nWiFi密码:'+getWiFiPWD(result)+'\n\n加密类型:WPA/WPA2\n') .fontColor(Color.White) .fontSize(16) Row(){ Button('复制密码') .fontColor(Color.White) .linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]}) .height(50) .layoutWeight(1) .stateEffect(true) .onClick(()=>{ Utility.copyText(getWiFiPWD(result)) ToastUtil.showToast('复制成功') DialogHelper.closeDialog('pwd') }) } } .width("100%") .padding(10) } //解析二维码的密码的对话框 showPwdResultDialog(result:string){ DialogHelper.showCustomContentDialog({ dialogId:'pwd', title: "WiFi详情", contentBuilder: () => { this.customShowPwdBuilder(result) }, buttons: [], }) } //跳转到系统wifi界面 goSystemWifiSetting(){ let context = getContext(this) as common.UIAbilityContext; let want: Want = { bundleName: 'com.huawei.hmos.settings', abilityName: 'com.huawei.hmos.settings.MainAbility', uri: 'wifi_entry'}; context.startAbility(want) .then(() => { // ... }) .catch((err:Error) => { console.error(`Failed to startAbility. Code: ${err.name}, message: ${err.message}`); }); } build() { Scroll(){ Column() { TitleBar({ model: $titleBarModel }) Column() { Shape() { Ellipse() .height(200) .width('100%') .fill(Color.White) .backgroundColor($r('app.color.title_bar_bg')) } } .width('100%') .height(100) .alignItems(HorizontalAlign.Start) .borderRadius({ bottomLeft: 20, bottomRight: 20 }) Stack() { Column() { Grid() { ForEach(mainViewModel.getWiFiGridData(), (item: ItemData) => { GridItem() { Column() { Image(item.img) .width(38) .height(38) .margin({top:22}) .alignSelf(ItemAlign.Center) .visibility(item.isHide ? Visibility.None : Visibility.Visible) Text(item.title) .fontSize(12) .fontWeight(300) .fontColor(Color.Grey) .margin({ top: 8 }) .visibility(item.isHide ? Visibility.None : Visibility.Visible) } // .backgroundImage($r('app.media.circle')) .backgroundImagePosition(Alignment.Top) .backgroundImageSize({width:100,height:100}) .height('100%') .width('100%') .onClick(() => { switch (item.id) { case MainViewModel.SAFE_TEST: router.pushUrl({url:'pages/SafeTestIndex' }); break case MainViewModel.SEE_PWD: // this.showFileDialog() this.showSeePwdDialog() //鸿蒙系统不需要申请文件权限 break case MainViewModel.SPEED_TEST: // router.pushUrl({url:'pages/WebPage', // params:{ titleName:'网络测速',webUrl:CommonConstants.IS_YUN_CESU2} // }); router.pushUrl({ url: 'pages/SpeedIndex' }); break case MainViewModel.JIAO_CHENG: router.pushUrl({ url: 'pages/MacPage' }); break case MainViewModel.CAMERA_TEST: router.pushUrl({ url: 'pages/AddSpeedPage' }); break case MainViewModel.POWER_TEST: //跳转到系统的省电模式 router.pushUrl({ url: 'pages/CoolingPage' }); break } }) } }) } .columnsTemplate('1fr 1fr 1fr') .rowsTemplate('1fr 1fr') .height(230) .borderRadius(24) .margin({top:50}) } } // Column() { // Line().width('100%').height(0.5).backgroundColor($r('app.color.index_tab_unselected_font_color')) // Text(this.textWifi) // .fontSize(13) // .fontColor($r('app.color.title_bar_bg')) // .alignSelf(ItemAlign.Start) // .margin({ left: 15 }) // .height(38) // .backgroundColor(Color.White) // Line().width('100%').height(1).backgroundColor($r('app.color.title_bar_bg')) // // } // .layoutWeight(1) } .width('100%') .height('100%') .backgroundColor(Color.White) } .height(1024) } /** * 查看密码的dialgo定布局提示弹窗 */ @Builder builderCustomDialogTipView() { Column() { Column({ space: '10vp' }) { Text('提示:请按如下教程') .fontSize('15fp') .fontColor(Color.Black) .textAlign(TextAlign.Start) .fontWeight(500) Text('第一步:点击第一步按钮,去系统的WIFI设置界面点到wifi分享二维码界面,然后截图。\n\n第二步:点击第二步按钮,选择该截图的图片进行wifi密码解析。\n') .fontSize('15fp') .fontColor(Color.Grey) .textAlign(TextAlign.Start) .fontWeight(FontWeight.Regular) .margin({left:8,right:8}) .padding(5) Row() { Button('第一步', { type: ButtonType.Normal, stateEffect: true }) .fontColor(Color.White) .fontSize('13fp') .width('50%') .backgroundColor('#55ceac') .onClick(() => { this.goSystemWifiSetting() }) .borderRadius({ bottomLeft: '5vp', }) Button('第二步', { type: ButtonType.Normal, stateEffect: true }) .fontColor(Color.White) .fontSize('13fp') .width('50%') .backgroundColor('#ff6b47') .onClick(() => { this.goSelectPhoto() }) .borderRadius({ bottomRight: '5vp' }) } .justifyContent(FlexAlign.SpaceBetween) .width("100%") .borderRadius({ bottomLeft: '5vp', bottomRight: '5vp' }) } .alignItems(HorizontalAlign.Center) .width('100%') .backgroundColor(Color.White) .borderRadius('5vp') .margin({ top: '15vp' }) } .width('100%') .borderRadius('5vp') .backgroundColor(Color.White) } } //根据 WIFI:T:WPA;S:Tenda_xiaoke;P:20161221;; 解析出wifi的名称 function getWiFiName(res: string): string { let str ='' if(StrUtil.isNotEmpty(res)){ if(res.indexOf('S:')!=-1){ str = res.substring(res.indexOf('S:')+2,res.indexOf(';P:')) } } return str } //根据 WIFI:T:WPA;S:Tenda_xiaoke;P:20161221;; 解析出wifi的密码 function getWiFiPWD(res: string): string { let str ='' if(StrUtil.isNotEmpty(res)){ if(res.indexOf('P:')!=-1){ str = res.substring(res.indexOf('P:')+2,res.indexOf(';;')) } } return str }