zhenghy

Merge remote-tracking branch 'origin/main'

# Conflicts:
#	sight_harmony/features/wdComponent/src/main/ets/components/view/OperRowListView.ets
Showing 42 changed files with 1326 additions and 532 deletions
... ... @@ -48,4 +48,8 @@ export class SpConstants{
//游客状态下首次评论时间
static FIRSTCOMMENTTIME = 'firstCommentTime'
static TOURIST_NICK_NAME = 'touristNickName'
// 个推推送
static GETUI_PUSH_CID = "cid"
static GETUI_PUSH_DEVICE_TOKEN = "deviceToken"
}
\ No newline at end of file
... ...
... ... @@ -133,10 +133,15 @@ export class NetworkManager {
* 同步获取网络类型,耗时
*/
public getNetTypeSync(): NetworkType {
let netHandle = connection.getDefaultNetSync();
let netCapabilities = connection.getNetCapabilitiesSync(netHandle)
this.reset(netCapabilities.bearerTypes)
return this.networkType;
try {
let netHandle = connection.getDefaultNetSync();
let netCapabilities = connection.getNetCapabilitiesSync(netHandle)
this.reset(netCapabilities.bearerTypes)
return this.networkType;
} catch (e) {
Logger.error(TAG, 'getNetTypeSync e: ' + JSON.stringify(e))
}
return NetworkType.TYPE_UNKNOWN
}
private parseData(data: connection.NetCapabilityInfo) {
... ...
... ... @@ -43,7 +43,7 @@ export class NetworkUtil {
*/
static isNetConnected(): boolean {
let type = NetworkManager.getInstance().getNetType()
if (type == NetworkType.TYPE_NONE) {
if (type == NetworkType.TYPE_UNKNOWN || type == NetworkType.TYPE_NONE) {
return false
}
return true
... ...
... ... @@ -807,4 +807,9 @@ export class HttpUrlUtils {
let url = HttpUrlUtils.getHost() + "/api/rmrb-user-center/common/user/c/device/push";
return url;
}
}
\ No newline at end of file
static getUploadPushInfoUrl() {
let url = HttpUrlUtils.getHost() + "/api/rmrb-contact/contact/zh/c/push/device"
return url
}
}
... ...
... ... @@ -12,4 +12,6 @@ export { ProcessUtils } from './src/main/ets/utils/ProcessUtils'
export { AssignChannelParam } from './src/main/ets/utils/HomeChannelUtils';
export { RouterJumpInterceptor, JumpInterceptorAction } from './src/main/ets/router/RouterJumpInterceptor'
\ No newline at end of file
export { RouterJumpInterceptor, JumpInterceptorAction } from './src/main/ets/router/RouterJumpInterceptor'
export { AppInnerLink } from './src/main/ets/utils/AppInnerLink'
... ...
import { url } from '@kit.ArkTS'
import App from '@system.app'
import { Logger } from 'wdKit/Index'
const TAG = "AppInnerLink"
export class AppInnerLink {
static readonly INNER_LINK_PROTCOL = "rmrbapp:"
static readonly INNER_LINK_HOSTNAME = "rmrb.app"
static readonly INNER_LINK_PATHNAME = "openwith"
// 内链跳转
// 内链地址例如:rmrbapp://rmrb.app/openwith?type=article&subType=h5_template_article&contentId=30000762651&relId=500000038702&skipType=1&relType=1
static jumpWithLink(innerLink: string) {
let params = AppInnerLink.parseParams(innerLink)
if (!params) {
Logger.info(TAG, "跳转无效的链接地址 " + innerLink)
return
}
switch (params.skipType) {
case 1: {
AppInnerLink.jumpParams(params)
break
}
case 2: {
AppInnerLink.jumpNoParams(params)
break
}
case 3: {
AppInnerLink.jumpAppH5(params)
break
}
case 4: {
AppInnerLink.jumpOutH5(params)
break
}
case 5: {
AppInnerLink.jumpThirdApp(params)
break
}
default: {
Logger.info(TAG, "跳转无效的链接地址 " + innerLink)
}
}
}
private static jumpParams(params: InnerLinkParam) {
}
private static jumpNoParams(params: InnerLinkParam) {
}
private static jumpAppH5(params: InnerLinkParam) {
}
private static jumpOutH5(params: InnerLinkParam) {
}
private static jumpThirdApp(params: InnerLinkParam) {
}
static parseParams(link: string) : InnerLinkParam | undefined {
const that = url.URL.parseURL(link)
if (that.protocol !== AppInnerLink.INNER_LINK_PROTCOL) {
return
}
if (that.hostname !== AppInnerLink.INNER_LINK_HOSTNAME) {
return
}
if (that.pathname !== AppInnerLink.INNER_LINK_PATHNAME) {
return
}
let obj = {} as InnerLinkParam
const params = that.params
obj.type = params.get("type") as string
obj.subType = params.get("subType") as string
obj.contentId = params.get("contentId") as string
obj.relId = params.get("relId") as string
obj.relType = params.get("relType") as string
obj.pageId = params.get("pageId") as string
obj.url = params.get("url") as string
obj.activityId = params.get("activityId") as string
obj.activityType = params.get("activityType") as string
obj.creatorId = params.get("creatorId") as string
obj.firstChannelId = params.get("firstChannelId") as string
obj.skipType = Number(params.get("skipType"))
obj.isLogin = params.get("isLogin") as string
return obj
}
}
interface InnerLinkParam {
type?: string,
subType?: string,
contentId?: string,
relId?: string,
relType?: string
pageId?: string,
url?: string,
activityId?: string,
activityType?: string,
creatorId?: string,
firstChannelId?: string,
skipType: number,
isLogin?: string,
}
\ No newline at end of file
... ...
... ... @@ -145,6 +145,7 @@ export struct ENewspaperPageComponent {
.onClick(() => {
this.calendarDialogShow = !this.calendarDialogShow
if (this.calendarDialogShow) {
this.calendarDialogController.open()
} else {
this.calendarDialogController.close()
... ...
... ... @@ -103,6 +103,10 @@ export struct RMCalendar {
nowFontColor: this.nowFontColor,
disableClick: (item: RMCalendarBean) => {
if (this.disableCellClick) {
if (!NetworkUtil.isNetConnected()) {
ToastUtils.showToast('网络出小差了,请检查网络后重试', 1000)
return
}
this.disableCellClick(item)
}
},
... ...
import { RMCalendarBean } from './RMCalendarBean';
import font from '@ohos.font';
import { ToastUtils, NetworkUtil } from 'wdKit/Index';
@Component
export struct RMCalenderCell {
... ... @@ -38,6 +38,12 @@ export struct RMCalenderCell {
}
getItemColor() {
if (!NetworkUtil.isNetConnected()) {
if (this.selectItem && this.selectItem.time == this.item.time) {
return this.selectFontColor
}
return this.disabledFontColor
}
if (!this.isShowSelectBg() && this.item.isNow) {
return this.nowFontColor
} else if (this.item.isPre) {
... ... @@ -136,9 +142,11 @@ export struct RMCalenderCell {
return
// }
}
this.selectItem = this.item
if (this.cellClick) {
this.cellClick(this.item)
if (NetworkUtil.isNetConnected()) {
this.selectItem = this.item
if (this.cellClick) {
this.cellClick(this.item)
}
}
})
}
... ...
... ... @@ -8,7 +8,7 @@ export struct CardSourceInfo {
@ObjectLink compDTO: CompDTO
build() {
Flex() {
Flex({ alignItems: ItemAlign.Center }) {
if (this.contentDTO.corner) {
Text(this.contentDTO.corner)
.fontSize($r("app.float.font_size_11"))
... ... @@ -28,31 +28,45 @@ export struct CardSourceInfo {
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
}
if (((this.contentDTO.rmhPlatform === 1 && this.contentDTO.rmhInfo?.rmhName && this.contentDTO.rmhInfo?.rmhName != '') || (this.contentDTO.source && this.contentDTO.source != '')) && (this.getContentDtoBean()?.interactData?.commentNum || DateTimeUtils.getCommentTime(Number.parseFloat(this.contentDTO.publishTime)) != '')) {
if (((this.contentDTO.rmhPlatform === 1 && this.contentDTO.rmhInfo?.rmhName && this.contentDTO.rmhInfo?.rmhName != '') || (this.contentDTO.source && this.contentDTO.source != '')) && (this.getContentDtoBean()?.interactData?.commentNum
// || DateTimeUtils.getCommentTime(Number.parseFloat(this.contentDTO.publishTime)) != ''
|| (this.contentDTO.isSearch || this.contentDTO.isCollection ||
!this.contentDTO.isSearch && DateTimeUtils.getCommentTime
(Number
.parseFloat(this
.contentDTO.publishTime))
.indexOf
('-') === -1)
)) {
Image($r("app.media.point"))
.width(16)
.height(16)
.width(11)
.height(11)
}
// 新闻tab下的卡片,2天之前的不显示时间。但是如果是搜索情况下展示的卡片,显示时间
if (this.contentDTO.isSearch || this.contentDTO.isCollection ||
!this.contentDTO.isSearch && DateTimeUtils.getCommentTime
(Number
.parseFloat(this
.contentDTO.publishTime))
.indexOf
('-') === -1) {
// if (this.contentDTO.isSearch || this.contentDTO.isCollection ||
// (!this.contentDTO.isSearch &&
// DateTimeUtils.getCommentTime(Number.parseFloat(this.contentDTO.publishTime)).indexOf('-') === -1)) {
//
// Text(DateTimeUtils.getCommentTime(Number.parseFloat(this.contentDTO.publishTime)))
// .fontSize($r("app.float.font_size_11"))
// .fontColor($r("app.color.color_B0B0B0"))
// .flexShrink(0);
// }
if (this.contentDTO.source) {
Text(DateTimeUtils.getCommentTime(Number.parseFloat(this.contentDTO.publishTime)))
.fontSize($r("app.float.font_size_11"))
.fontColor($r("app.color.color_B0B0B0"))
.flexShrink(0)
.flexShrink(0);
}
if (this.getContentDtoBean()?.interactData?.commentNum) {
if (this.getContentDtoBean()?.interactData?.commentNum && this.contentDTO.source) {
Text(`${this.getContentDtoBean()?.interactData?.commentNum}评`)
.fontSize($r("app.float.font_size_11"))
.fontColor($r("app.color.color_B0B0B0"))
.flexShrink(0)
.margin({ left: 6 })
.visibility(Number(this.getContentDtoBean()?.interactData?.commentNum) === 0 ? Visibility.None : Visibility.Visible)
.visibility(Number(this.getContentDtoBean()?.interactData?.commentNum) === 0 ? Visibility.None :
Visibility.Visible)
}
}
.width(CommonConstants.FULL_WIDTH)
... ... @@ -67,7 +81,7 @@ export struct CardSourceInfo {
if (this.compDTO == undefined) {
return this.contentDTO
}
if(this.compDTO.operDataList.length == 0){
if (this.compDTO.operDataList.length == 0) {
return this.contentDTO
}
return this.compDTO.operDataList[0]
... ...
... ... @@ -62,20 +62,7 @@ export struct Card19Component {
}
// 图片-从无图到9图展示
createImg({ fullColumnImgUrls: this.contentDTO.fullColumnImgUrls })
.onClick(() => {
const photoList: PhotoListBean[] = this.contentDTO.fullColumnImgUrls.map(item => {
const photo: PhotoListBean = {
width: item.weight,
height: item.height,
picPath: item.fullUrl||item.url,
picDesc: '',
itemType:2,
id:0
}
return photo
})
ProcessUtils.gotoMultiPictureListPage(photoList, 0)
})
CarderInteraction({ contentDTO: this.contentDTO })
//TODO 底部的:分享、评论、点赞 功能;需要引用一个公共组件
}
... ... @@ -107,12 +94,12 @@ struct createImg {
@State loadImg: boolean = false;
async aboutToAppear(): Promise<void> {
this.loadImg = await onlyWifiLoadImg();
if (this.fullColumnImgUrls.length === 4) { // 为了使用栅格布局以便于占用三分之二的宽度,加一个占位
this.fullColumnImgUrls.splice(2, 0, {
fullUrl: ''
} as FullColumnImgUrlDTO)
}
this.loadImg = await onlyWifiLoadImg();
console.log('card19-this.fullColumnImgUrls',JSON.stringify(this.fullColumnImgUrls))
}
... ... @@ -167,14 +154,14 @@ struct createImg {
alignContent: Alignment.BottomEnd
}) {
if (this.getPicType() === 1) {
Image(this.loadImg ? item.fullUrl||item.url : '')
Image(this.loadImg ? item.fullUrl || item.url : '')
.backgroundColor(0xf5f5f5)
.width('100%')
.height(172)
.autoResize(true)
.borderRadius(this.caclImageRadius(index))
} else if (this.getPicType() === 2) {
Image(this.loadImg ? item.fullUrl||item.url : '')
Image(this.loadImg ? item.fullUrl || item.url : '')
.width('100%')
.height(305)
.autoResize(true)
... ... @@ -291,6 +278,20 @@ struct createImg {
.padding({ bottom: 3 })
}
}
.onClick(() => {
const photoList: PhotoListBean[] = this.fullColumnImgUrls.map(item => {
const photo: PhotoListBean = {
width: item.weight,
height: item.height,
picPath: item.fullUrl||item.url,
picDesc: '',
itemType:2,
id:0
}
return photo
})
ProcessUtils.gotoMultiPictureListPage(photoList, index)
})
}
}
})
... ...
... ... @@ -87,12 +87,12 @@ export struct Card5Component {
}
.alignContent(Alignment.Bottom)
.width(CommonConstants.FULL_WIDTH)
// .padding({
// left: $r('app.float.card_comp_pagePadding_lf'),
// right: $r('app.float.card_comp_pagePadding_lf'),
// top: $r('app.float.card_comp_pagePadding_tb'),
// bottom: $r('app.float.card_comp_pagePadding_tb')
// })
.padding({
left: $r('app.float.card_comp_pagePadding_lf'),
right: $r('app.float.card_comp_pagePadding_lf'),
top: $r('app.float.card_comp_pagePadding_tb'),
bottom: $r('app.float.card_comp_pagePadding_tb')
})
.onClick((event: ClickEvent) => {
this.clicked = true;
ProcessUtils.processPage(this.contentDTO)
... ...
... ... @@ -54,9 +54,9 @@ export struct Card6Component {
// }
Stack() {
if (this.contentDTO.newTags) {
Notes({ newTags: this.contentDTO.newTags })
Notes({ newTags: this.contentDTO.newTags }).height(27).align(Alignment.Center)
} else if (this.contentDTO.objectType == '5') {
Notes({ objectType: this.contentDTO.objectType })
Notes({ objectType: this.contentDTO.objectType }).height(27).align(Alignment.Center)
}
Text() {
... ... @@ -114,7 +114,7 @@ export struct Card6Component {
bottom: $r('app.float.card_comp_pagePadding_tb')
})
.width(CommonConstants.FULL_WIDTH)
.height(this.contentDTO.appStyle === CompStyle.Card_13 ? 107 : 217)
// .height(this.contentDTO.appStyle === CompStyle.Card_13 ? 107 : 217)
.justifyContent(FlexAlign.SpaceBetween)
}
}
\ No newline at end of file
... ...
... ... @@ -13,7 +13,7 @@ const TAG: string = 'Card9Component';
@Component
export struct Card9Component {
@State contentDTO: ContentDTO = new ContentDTO();
@State loadImg: boolean = true;
// @State loadImg: boolean = true;
@State clicked: boolean = false;
@State titleMarked: boolean = false;
@State str01: string = '';
... ... @@ -54,10 +54,11 @@ export struct Card9Component {
.maxLines(2)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.margin({ top: 10, bottom: 10 })
.fontWeight(400)
}
// 大图
Stack() {
Image(this.loadImg ? this.contentDTO.coverUrl : '')
Image(this.contentDTO.coverUrl)
.backgroundColor(0xf5f5f5)
.width('100%')
.height(133)
... ...
... ... @@ -21,8 +21,9 @@ export struct Notes {
bottom: 3
})
.linearGradient({ angle: 90, colors: [['#FFFF2B00', 0.0], ['#FFFE6A00', 1.0]] })
.fontColor(Color.White)
.borderRadius($r('app.float.button_border_radius'))
.fontColor(Color.White)// .borderRadius($r('app.float.button_border_radius'))
.borderRadius(2)
.margin({ top: 1 })
}
}
... ...
... ... @@ -17,10 +17,10 @@ export struct ZhSingleRow04 {
//顶部
Row() {
Row() {
Image($r("app.media.local_selection"))
.width(24)
.height(24)
.margin({ right: 4 })
// Image($r("app.media.local_selection"))
// .width(24)
// .height(24)
// .margin({ right: 4 })
Text(this.compDTO.objectTitle)
.fontSize($r("app.float.font_size_17"))
.fontColor($r("app.color.color_222222"))
... ... @@ -36,7 +36,8 @@ export struct ZhSingleRow04 {
.width(14)
.height(14)
}
.visibility(this.compDTO?.objectType === '0' || this.compDTO?.objectType === '' ? Visibility.None : Visibility.Visible)
.visibility(this.compDTO?.objectType === '0' || this.compDTO?.objectType === '' ? Visibility.None :
Visibility.Visible)
.onClick(() => {
if (this.compDTO?.objectType === '11') {
ProcessUtils.jumpChannelTab(this.compDTO.objectId, this.compDTO.pageId as string, this.compDTO.objectTitle)
... ... @@ -64,9 +65,11 @@ export struct ZhSingleRow04 {
operDataListItem: item
}
)
.margin({right: index === this.compDTO.operDataList.length - 1 ? 26 : 0, left:
index === 0 ? $r('app.float.card_comp_pagePadding_lf') : 0,
top: 6})
.margin({
right: index === this.compDTO.operDataList.length - 1 ? 26 : 0, left:
index === 0 ? $r('app.float.card_comp_pagePadding_lf') : 0,
top: 6
})
.onClick(() => {
ProcessUtils.processPage(item)
})
... ... @@ -106,8 +109,7 @@ struct localCard {
.align(Alignment.TopStart)
.maxLines(3)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.lineHeight(20)
.margin({bottom: 17})
.lineHeight(25)
.fontWeight(500)
Row() {
Text(DateTimeUtils.getCommentTime(Number.parseFloat(this.operDataListItem.publishTime)))
... ... @@ -115,7 +117,7 @@ struct localCard {
.fontColor($r("app.color.color_B0B0B0"))
.margin({ right: 5 })
// 这里需要外部查询评论接口后,写入字段
if(this.operDataListItem.interactData?.commentNum) {
if (this.operDataListItem.interactData?.commentNum) {
Text(`${this.operDataListItem.interactData?.commentNum}评`)
.fontSize(12)
}
... ... @@ -139,7 +141,12 @@ struct localCard {
.border({
radius: 2,
})
.shadow({ radius: 6, color: '#1A000000', offsetX: 3, offsetY: 0 })
.shadow({
radius: 6,
color: '#1A000000',
offsetX: 0,
offsetY: 3
}) // 设置下方阴影
.margin({
right: 10
})
... ...
... ... @@ -30,6 +30,7 @@ export struct ZhSingleRow06 {
this.loadImg = await onlyWifiLoadImg();
}
/**
* 点赞、取消点赞
*/
... ... @@ -43,7 +44,7 @@ export struct ZhSingleRow06 {
const commentInfo = this.compDTO.operDataList[0]?.commentInfo as commentInfo;
// commentLikeChange(this.item)
this.newsStatusOfUser.likeStatus = this.newsStatusOfUser.likeStatus === '1' ? '0' : '1';
// this.newsStatusOfUser.likeStatus = this.newsStatusOfUser.likeStatus === '1' ? '0' : '1';
const commentLikeParam = {
targetId: commentInfo.newsId || '',
id: commentInfo.commentId,
... ... @@ -51,8 +52,9 @@ export struct ZhSingleRow06 {
api_status: this.newsStatusOfUser?.likeStatus == '1' ? false : true
} as commentItemModel;
commentViewModel.commentLike(commentLikeParam).then(() => {
}).catch(() => {
this.newsStatusOfUser.likeStatus = this.newsStatusOfUser.likeStatus === '1' ? '0' : '1';
}).catch((err: Error) => {
console.log('06-err', JSON.stringify(err))
})
}
... ... @@ -168,7 +170,7 @@ export struct ZhSingleRow06 {
? item.operDataList[0]?.commentInfo?.userHeaderUrl
? item.operDataList[0].commentInfo.userHeaderUrl
: $r('app.media.default_head')
: $r('app.media.comment_rmh_tag'))
: $r('app.media.icon_default_head_mater'))
.width(32)
.height(32)
.borderRadius(16)
... ...
... ... @@ -34,7 +34,7 @@ export struct ChildCommentComponent {
.borderRadius(50)
}.width('89lpx')
.height('89lpx')
.margin({ right: '15lpx' })
.margin({ right: '3lpx' })
Column() {
Text(this.data.fromUserName)
... ...
... ... @@ -8,11 +8,16 @@ import { CustomPullToRefresh } from '../reusable/CustomPullToRefresh';
import { PeopleShipNoMoreData } from '../reusable/PeopleShipNoMoreData';
import { EmptyComponent } from '../view/EmptyComponent';
import { ErrorComponent } from '../view/ErrorComponent';
import LoadMoreLayout from '../page/LoadMoreLayout'
import { LottieView } from '../../components/lottie/LottieView'
import LoadMoreLayout from '../page/LoadMoreLayout';
import { LottieView } from '../../components/lottie/LottieView';
import dataPreferences from '@ohos.data.preferences';
import { BusinessError } from '@ohos.base';
const TAG: string = 'LiveMorePage';
const PREFERENCES_NAME = 'rmrLiveMorePage.db'
let preferenceTheme: dataPreferences.Preferences | null = null
/**
* 直播更多:
* type=1 直播
... ... @@ -37,7 +42,13 @@ struct LiveMorePage {
@State viewType: ViewType = ViewType.LOADING
private scroller: Scroller = new Scroller()
@State liveRoomList: LiveRoomDataBean[] = []
aboutToAppear(): void {
// 点击过的数据
@State clickDatas: Array<string> = []
async aboutToAppear() {
await this.getPreferencesFromStorage()
this.getLivMoreClickPreference()
Logger.debug(TAG, '数据:' + JSON.stringify(this.clickDatas))
this.currentPage = 1
this.getData()
}
... ... @@ -93,10 +104,9 @@ struct LiveMorePage {
LoadingLayout() {
}
@Builder
ListLayout() {
List({scroller: this.scroller}) {
List({ scroller: this.scroller }) {
// 下拉刷新
LazyForEach(this.data, (contentDTO: ContentDTO) => {
ListItem() {
... ... @@ -120,7 +130,7 @@ struct LiveMorePage {
.height('calc(100% - 44vp)')
.onReachEnd(() => {
Logger.debug(TAG, "触底了");
if(!this.isLoading && this.hasMore){
if (!this.isLoading && this.hasMore) {
//加载分页数据
this.currentPage++;
this.getData()
... ... @@ -137,11 +147,12 @@ struct LiveMorePage {
buildItem(item: ContentDTO) {
Column() {
Text(item.newsTitle)
.fontSize(17)
.fontSize(18)
.maxLines(2)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.margin({ top: 16, bottom: 8 })
.alignSelf(ItemAlign.Start)
.fontColor(this.isClicked(item.objectId) ? $r('app.color.color_848484') : $r('app.color.color_222222'))
Stack() {
if (item.fullColumnImgUrls && item.fullColumnImgUrls.length > 0) {
Image(item.fullColumnImgUrls[0].url)
... ... @@ -191,6 +202,7 @@ struct LiveMorePage {
}
.width('100%')
.onClick(() => {
this.clickRowBuildItem(item)
ProcessUtils.processPage(item)
})
}
... ... @@ -292,14 +304,14 @@ struct LiveMorePage {
}
this.data.push(...liveReviewDTO.list)
this.getLiveRoomDataInfo(liveReviewDTO.list)
} else {
} else {
this.hasMore = false;
}
this.resolveEnd(true, resolve)
if (liveReviewDTO.list.length == 0 && this.currentPage == 1) {
this.viewType = ViewType.EMPTY
}
}catch (exception) {
} catch (exception) {
this.resolveEnd(false, resolve)
}
// PageViewModel.getLiveMoreUrl(this.type, this.currentPage, this.pageSize).then(async (liveReviewDTO) => {
... ... @@ -315,7 +327,7 @@ struct LiveMorePage {
if (resolve) {
if (this.currentPage == 1 && isTop) {
resolve('已更新至最新')
}else {
} else {
resolve('')
}
}
... ... @@ -334,23 +346,24 @@ struct LiveMorePage {
});
return idList.join(',')
}
// 获取评论数
async getLiveRoomDataInfo(list: ContentDTO[]) {
const reserveIds = this.getLiveDetailIds(list)
Logger.debug(TAG,'是否预约数据:' +` ${reserveIds}`)
Logger.debug(TAG, '是否预约数据:' + ` ${reserveIds}`)
PageViewModel.getLiveRoomBatchInfo(reserveIds).then((result) => {
Logger.debug(TAG,'是否预约数据:' +` ${JSON.stringify(result)}`)
Logger.debug(TAG, '是否预约数据:' + ` ${JSON.stringify(result)}`)
if (result && result.length > 0) {
this.liveRoomList.push(...result)
this.data.reloadData()
}
}).catch(() =>{
}).catch(() => {
// this.data.push(...list)
})
}
// 判断是否预约
getLiveRoomNumber(item: ContentDTO): string {
getLiveRoomNumber(item: ContentDTO): string {
const objc = this.liveRoomList.find((element: LiveRoomDataBean) => {
return element.liveId.toString() == item.objectId
})
... ... @@ -362,14 +375,64 @@ struct LiveMorePage {
private computeShowNum(count: number): string {
if (count >= 10000) {
let num = ( count / 10000).toFixed(1)
if (Number(num.substring(num.length-1)) == 0) {
num = num.substring(0, num.length-2)
let num = (count / 10000).toFixed(1)
if (Number(num.substring(num.length - 1)) == 0) {
num = num.substring(0, num.length - 2)
}
return num + '万人参加'
}
return `${count}人参加`
}
isClicked(objectId: string) {
return this.clickDatas.includes(objectId)
}
clickRowBuildItem(item: ContentDTO) {
if (item.objectId && !this.clickDatas.includes(item.objectId)) {
Logger.debug(TAG, '数据:' + JSON.stringify(this.clickDatas))
this.clickDatas.push(item.objectId.toString())
this.putLiveMoreClickPreference()
}
}
async getPreferencesFromStorage() {
let context = getContext(this) as Context
preferenceTheme = await dataPreferences.getPreferences(context, PREFERENCES_NAME)
}
putLiveMoreClickPreference() {
Logger.info(TAG, `Put begin` + JSON.stringify(this.clickDatas))
if (preferenceTheme !== null && this.clickDatas.length > 0) {
// await
const arr: Array<string> = []
arr.push(...this.clickDatas)
preferenceTheme.put('liveMorePage', arr).then(() => {
Logger.debug(TAG,"Succeeded in putting value of 'startup'.");
}).catch((err: BusinessError) => {
Logger.debug(TAG, "Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message);
})
// await preferenceTheme.flush()
preferenceTheme.flush((err: BusinessError) => {
if (err) {
Logger.debug(TAG, "Failed to flush. code =" + err.code + ", message =" + err.message);
return;
}
})
}
}
getLivMoreClickPreference() {
Logger.info(TAG, `Get begin`)
if (preferenceTheme !== null) {
preferenceTheme.get('liveMorePage', []).then((data: dataPreferences.ValueType) => {
if (data instanceof Array) {
this.clickDatas = data as Array<string>
}
}).catch((err: BusinessError) => {
console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
})
}
}
}
\ No newline at end of file
... ...
... ... @@ -255,7 +255,7 @@ export struct PageComponent {
this.pageModel.channelId = this.channelId;
this.pageModel.currentPage = 1;
this.pageModel.pageTotalCompSize = 0;
// TODO PageHelper.getInitCacheData(this.pageModel, this.pageAdvModel)
PageHelper.getInitCacheData(this.pageModel, this.pageAdvModel)
PageHelper.getInitData(this.pageModel, this.pageAdvModel)
}, 100)
}
... ...
... ... @@ -74,8 +74,8 @@ export struct PeopleShipRecommendComponent {
}
.columnsTemplate('1fr 1fr 1fr')
.columnsGap(20)
.rowsGap(20)
.height(Math.ceil(this.rmhList.length / 3.0) * 136)
.rowsGap(16)
.height(Math.ceil(this.rmhList.length / 3.0) * 132)
.backgroundColor(Color.Transparent)
.margin({
right: '20vp',
... ... @@ -85,7 +85,7 @@ export struct PeopleShipRecommendComponent {
// 为你推荐
Button(this.rmhSelectedList.length == 0 ? '一键关注' : `一键关注 (${this.rmhSelectedList.length})`, { type: ButtonType.Normal, stateEffect: this.rmhSelectedList.length != 0 })
.margin({
top: '24vp',
top: '10vp',
bottom: '10vp'
})
.width('120vp')
... ... @@ -104,6 +104,8 @@ export struct PeopleShipRecommendComponent {
})
}
.width('100%')
.justifyContent(FlexAlign.Start)
}
// 选中
... ...
... ... @@ -130,7 +130,10 @@ struct ReserveMorePage {
Image(item.fullColumnImgUrls[0]?.url)
.width('100%')
.objectFit(ImageFit.Contain)
.borderRadius(4)
.borderRadius({
topLeft: '4vp',
topRight: '4vp'
})
this.LiveImage()
}
... ...
... ... @@ -110,6 +110,10 @@ export struct SearchComponent {
this.searchHistoryData = SearcherAboutDataModel.getSearchHistoryData()
}
stopInput(){
this.controller.stopEditing()
}
build() {
Column() {
this.searchInputComponent()
... ... @@ -117,7 +121,7 @@ export struct SearchComponent {
Scroll(this.scroller) {
Column() {
if(this.searchHistoryData!=null && this.searchHistoryData.length>0){
SearchHistoryComponent({ searchHistoryData: $searchHistoryData, onDelHistory: (): void => this.getSearchHistoryData(),onGetSearchRes: (item,index): void => this.getSearchHistoryResData(item,index) })
SearchHistoryComponent({ searchHistoryData: $searchHistoryData, onDelHistory: (): void => this.getSearchHistoryData(),onGetSearchRes: (item,index): void => this.getSearchHistoryResData(item,index),onCloseInput : (): void => this.stopInput() })
}
if(this.searchHistoryData.length>0){
... ... @@ -140,7 +144,13 @@ export struct SearchComponent {
} else {
if (this.hasChooseSearch) {
//搜索结果
SearchResultComponent({count:this.count,searchText:this.searchText,isGetRequest:this.isGetRequest})
SearchResultComponent({count:this.count,searchText:this.searchText,isGetRequest:this.isGetRequest,onClickTryAgain: (): void => {
if(StringUtils.isNotEmpty(this.searchText)){
SearcherAboutDataModel.putSearchHistoryData(this.searchText)
this.getSearchHistoryData()
this.getSearchInputResData(this.searchText)
}
}})
} else {
//联想搜索
SearchRelatedComponent({relatedSearchContentData:$relatedSearchContentsData,onGetSearchRes: (item): void => this.getSearchRelatedResData(item),searchText:this.searchText})
... ... @@ -251,7 +261,6 @@ export struct SearchComponent {
.textFont({ size: "27lpx", weight: "400lpx" })
// .defaultFocus(true)
.id("searchId")
.focusable(true)
.searchIcon({
size:0
})
... ...
... ... @@ -8,11 +8,14 @@ import { MyCustomDialog } from '../reusable/MyCustomDialog'
@Component
export struct SearchHistoryComponent{
@Link searchHistoryData:SearchHistoryItem[]
onCloseInput?: () => void;
onDelHistory?: () => void;
onGetSearchRes?: (item:string,index:number) => void;
dialogController: CustomDialogController = new CustomDialogController({
builder: MyCustomDialog({
cancel: this.onCancel,
cancel: () => {
this.onCancel()
},
confirm: () => {
this.onAccept()
},
... ... @@ -33,6 +36,9 @@ export struct SearchHistoryComponent{
}
onCancel() {
if (this.onCloseInput !== undefined) {
this.onCloseInput()
}
console.info('Callback when the first button is clicked')
}
... ...
import { CompDTO, ContentDTO } from 'wdBean/Index'
import { LazyDataSource, UserDataLocal } from 'wdKit/Index'
import { LazyDataSource, NetworkUtil, UserDataLocal } from 'wdKit/Index'
import { HttpUtils } from 'wdNetwork/Index'
import SearcherAboutDataModel from '../../model/SearcherAboutDataModel'
import { SearchSuggestRequestItem } from '../../viewmodel/SearchSuggestRequestItem'
... ... @@ -26,6 +26,8 @@ export struct SearchResultComponent {
@State suggest_count: number = 0;
@State isLoading: boolean = false
scroller: Scroller = new Scroller()
onClickTryAgain?: () => void;
@State isConnectNetwork : boolean = NetworkUtil.isNetConnected()
aboutToAppear(): void {
if (this.count.length === 0 && this.isGetRequest == true) {
... ... @@ -67,9 +69,22 @@ export struct SearchResultComponent {
List() {
ListItem() {
//缺省图
EmptyComponent({emptyType:4})
.height('612lpx')
.width('100%')
if(this.isConnectNetwork){
EmptyComponent({emptyType:4})
.height('612lpx')
.width('100%')
}else{
EmptyComponent({ emptyType: 1,emptyHeight:"100%" ,retry: () => {
this.isConnectNetwork = NetworkUtil.isNetConnected()
if(this.isConnectNetwork){
if (this.onClickTryAgain !== undefined) {
this.onClickTryAgain()
}
}
}})
.height("100%")
.width('100%')
}
}
if(this.suggest_count > 0){
ListItem() {
... ...
... ... @@ -46,11 +46,11 @@ const TAG = 'OperRowListView';
@Preview
@Component
export struct OperRowListView {
private onBack = () => {
private onBack: () => void = () => {
}
private onCommentFocus = () => {
private onCommentFocus: () => void = () => {
}
private onCommentIconClick = () => {
private onCommentIconClick: () => void = () => {
}
@Prop @Watch('onDetailUpdated') contentDetailData: ContentDetailDTO // 稿件详情
/**
... ... @@ -136,11 +136,12 @@ export struct OperRowListView {
build() {
// 视频详情页
Column() {
Image($r('app.media.ic_news_detail_division'))
.width('100%')
.height($r('app.float.margin_1'))
.margin({ bottom: -2 })
// .margin({bottom: -2})
Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
// AudioDialog()
... ...
import { RMCalendar } from '../components/calendar/RMCalendar'
import { RMCalendarBean } from '../components/calendar/RMCalendarBean'
import { ToastUtils, NetworkUtil } from 'wdKit/Index';
@CustomDialog
export struct ENewspaperCalendarDialog {
... ... @@ -26,4 +27,9 @@ export struct ENewspaperCalendarDialog {
}
})
}
aboutToAppear(): void {
if (!NetworkUtil.isNetConnected()) {
ToastUtils.showToast('网络出小差了,请检查网络后重试', 1000)
}
}
}
\ No newline at end of file
... ...
import router from '@ohos.router'
import { StringUtils } from 'wdKit';
import { NetworkUtil, StringUtils } from 'wdKit';
import { WDRouterPage, WDRouterRule } from 'wdRouter';
import { editModelParams } from '../model/EditInfoModel';
import { HomePageBottomCommentComponent } from '../components/mine/home/HomePageBottomCommentComponent';
import { HomePageBottomFollowComponent } from '../components/mine/home/HomePageBottomFollowComponent';
import MinePageDatasModel from '../model/MinePageDatasModel';
import { EmptyComponent } from '../components/view/EmptyComponent';
import { CustomTitleUI } from '../components/reusable/CustomTitleUI';
const TAG = "MineHomePage"
... ... @@ -33,6 +35,7 @@ struct MineHomePage {
scroller: Scroller = new Scroller();
@State params:Record<string, string> = router.getParams() as Record<string, string>;
@State isCommentEnter:string = "";
@State isConnectNetwork : boolean = NetworkUtil.isNetConnected()
onPageShow(): void {
this.getUserInfo()
... ... @@ -47,216 +50,235 @@ struct MineHomePage {
}
build() {
Stack({ alignContent: Alignment.Top }){
Image($r('app.media.title_bg'))
.width('100%')
.height('355lpx')
.objectFit(ImageFit.Cover)
if(this.isConnectNetwork){
Stack({ alignContent: Alignment.Top }){
Image($r('app.media.title_bg'))
.width('100%')
.height('355lpx')
.objectFit(ImageFit.Cover)
Column(){
Stack({ alignContent: Alignment.Top }){
this.MineHomeTitleTransparent()
this.MineHomeTitleWhite()
}
Column(){
Stack({ alignContent: Alignment.Top }){
this.MineHomeTitleTransparent()
this.MineHomeTitleWhite()
}
Scroll(this.scroller) {
Column() {
//用户信息区域
Row() {
Stack(){
Image(this.headPhotoUrl)
.alt($r('app.media.default_head'))
.width('115lpx')
.height('115lpx')
.objectFit(ImageFit.Auto)
.clip(new Circle({ width: '115lpx', height: '115lpx' }))
Image(this.levelHead)
.width('165lpx')
.height('165lpx')
.objectFit(ImageFit.Auto)
}.onClick(()=>{
let params = {'headPhotoUrl': this.headPhotoUrl} as Record<string, string>;
WDRouterRule.jumpWithPage(WDRouterPage.showUserHeaderPage,params)
}).width('165lpx')
.height('165lpx')
Scroll(this.scroller) {
Column() {
//用户信息区域
Row() {
Stack(){
Image(this.headPhotoUrl)
.alt($r('app.media.default_head'))
.width('100lpx')
.height('100lpx')
.objectFit(ImageFit.Auto)
.borderRadius(50)
Image(this.levelHead)
.width('130lpx')
.height('130lpx')
.objectFit(ImageFit.Cover)
}.onClick(()=>{
let params = {'headPhotoUrl': this.headPhotoUrl} as Record<string, string>;
WDRouterRule.jumpWithPage(WDRouterPage.showUserHeaderPage,params)
}).width('135lpx')
.height('135lpx')
Column() {
Row() {
Text(`${this.userName}`)
.fontColor($r('app.color.white'))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.fontSize('38lpx')
.lineHeight('50lpx')
.fontWeight('500lpx')
.onClick(()=>{
let params: editModelParams = {
editContent: this.userName
}
WDRouterRule.jumpWithPage(WDRouterPage.editUserNikeNamePage,params)
})
if(this.levelId>0){
Text(`等级${this.levelId}`)
.fontColor($r('app.color.color_ED2800'))
.fontSize('23lpx')
.fontWeight(500)
.margin({ left: '10lpx' })
.backgroundImage($r("app.media.my_grade_bg"))
.backgroundImageSize(ImageSize.Cover)
.padding({left:"17lpx",right:"8lpx"})
.height('35lpx')
}
Blank()
}.width('507lpx')
Row() {
Row() {
Text(`${this.browseNum}`)
.textStyle()
Text("阅读")
.textStyle2()
}
.margin({ right: '15lpx' })
Divider()
.height('19lpx')
.width('2lpx')
.color($r('app.color.white'))
.vertical(true)
.opacity(0.4)
Row() {
Text(`${this.commentNum}`)
.textStyle()
Text("评论")
.textStyle2()
}.margin({ right: '15lpx', left: '15lpx' })
Divider()
.height('19lpx')
.width('2lpx')
.color($r('app.color.white'))
.vertical(true)
.opacity(0.4)
Row() {
Text(`${this.attentionNum}`)
.textStyle()
Text("关注")
.textStyle2()
}.margin({ left: '15lpx' })
}.margin({ top: '23lpx' })
}.alignItems(HorizontalAlign.Start)
.margin({ left: StringUtils.isEmpty(this.levelHead)?'32lpx':"3lpx" })
}
.onAreaChange((oldValue: Area, newValue: Area) => {
if (this.firstPositionY === 0) {
this.firstPositionY = newValue.globalPosition.y as number
}else{
let persent = (this.firstPositionY - Number(newValue.globalPosition.y)) / (this.firstPositionY * 0.3)
if(persent > 1){
persent = 1
}
this.tileOpacity = persent
}
})
.backgroundColor($r('app.color.color_transparent'))
.height('184lpx')
.width('100%')
.padding({ left: '6lpx' })
//用户简介区域
Column() {
Row() {
Text(`${this.userName}`)
.fontColor($r('app.color.white'))
.maxLines(1)
Text(this.isHasIntroduction?"简介:"+this.desc:this.desc)
.fontSize('27lpx')
.maxLines(3)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.fontSize('38lpx')
.lineHeight('50lpx')
.fontWeight('500lpx')
.lineHeight('40lpx')
.fontWeight('400lpx')
.fontColor(this.isHasIntroduction?$r('app.color.color_222222'):$r('app.color.color_999999'))
.textAlign(TextAlign.Start)
.onClick(()=>{
let params: editModelParams = {
editContent: this.userName
editContent: this.isHasIntroduction?this.desc:''
}
WDRouterRule.jumpWithPage(WDRouterPage.editUserNikeNamePage,params)
WDRouterRule.jumpWithPage(WDRouterPage.editUserIntroductionPage,params)
})
if(this.levelId>0){
Text(`等级${this.levelId}`)
.textAlign(TextAlign.Center)
.fontColor($r('app.color.color_ED2800'))
.backgroundColor($r('app.color.white'))
.fontSize('19lpx')
.width('96lpx')
.height('35lpx')
.margin({ left: '10lpx' })
if(!this.isHasIntroduction){
Image($r('app.media.user_info_edit_icon'))
.width('27lpx')
.height('27lpx')
.interpolation(ImageInterpolation.High)
.objectFit(ImageFit.Auto)
}
}
Blank()
}.width('507lpx')
Row() {
Row() {
Text(`${this.browseNum}`)
.textStyle()
Text("阅读")
.textStyle2()
}
.margin({ right: '15lpx' })
Divider()
.height('19lpx')
.width('2lpx')
.color($r('app.color.white'))
.vertical(true)
.opacity(0.4)
Row() {
Text(`${this.commentNum}`)
.textStyle()
Text("评论")
.textStyle2()
}.margin({ right: '15lpx', left: '15lpx' })
Divider()
.height('19lpx')
.width('2lpx')
.color($r('app.color.white'))
.vertical(true)
.opacity(0.4)
Row() {
Text(`${this.attentionNum}`)
.textStyle()
Text("关注")
.textStyle2()
}.margin({ left: '15lpx' })
}.margin({ top: '23lpx' })
}.alignItems(HorizontalAlign.Start)
.margin({ left: '32lpx' })
}
.onAreaChange((oldValue: Area, newValue: Area) => {
if (this.firstPositionY === 0) {
this.firstPositionY = newValue.globalPosition.y as number
}else{
let persent = (this.firstPositionY - Number(newValue.globalPosition.y)) / (this.firstPositionY * 0.3)
if(persent > 1){
persent = 1
}
this.tileOpacity = persent
}
})
.backgroundColor($r('app.color.color_transparent'))
.height('184lpx')
.width('100%')
.padding({ left: '35lpx' })
//用户简介区域
Column() {
Row() {
Text(this.isHasIntroduction?"简介:"+this.desc:this.desc)
.fontSize('27lpx')
.maxLines(3)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.lineHeight('40lpx')
Text(`来到人民日报${this.registerTimeForDay}天`)
.fontSize('23lpx')
.lineHeight('25lpx')
.fontWeight('400lpx')
.fontColor(this.isHasIntroduction?$r('app.color.color_222222'):$r('app.color.color_999999'))
.fontColor($r('app.color.color_999999'))
.textAlign(TextAlign.Start)
.onClick(()=>{
let params: editModelParams = {
editContent: this.isHasIntroduction?this.desc:''
}
WDRouterRule.jumpWithPage(WDRouterPage.editUserIntroductionPage,params)
})
if(!this.isHasIntroduction){
Image($r('app.media.user_info_edit_icon'))
.width('27lpx')
.height('27lpx')
.interpolation(ImageInterpolation.High)
.objectFit(ImageFit.Auto)
}
}
.margin({ top: '15lpx' })
Text(`来到人民日报${this.registerTimeForDay}天`)
.fontSize('23lpx')
.lineHeight('25lpx')
.fontWeight('400lpx')
.fontColor($r('app.color.color_999999'))
.textAlign(TextAlign.Start)
.margin({ top: '15lpx' })
}.padding({ left: '31lpx',right:'31lpx',top:'19lpx',bottom:'31lpx'})
.alignItems(HorizontalAlign.Start)
.justifyContent(FlexAlign.Center)
.width('100%')
.backgroundColor($r('app.color.white'))
//间隔符
Divider().width('100%').height('12lpx').color($r('app.color.color_F5F5F5')).strokeWidth('12lpx')
//tab 页面
Stack({ alignContent: Alignment.Top }){
Tabs({controller: this.controller}) {
TabContent() {
HomePageBottomCommentComponent({commentNum:$commentNum})
}
TabContent() {
HomePageBottomFollowComponent()
}
}
}.padding({ left: '31lpx',right:'31lpx',top:'19lpx',bottom:'31lpx'})
.alignItems(HorizontalAlign.Start)
.justifyContent(FlexAlign.Center)
.width('100%')
.backgroundColor($r('app.color.white'))
.animationDuration(0)
.onChange((index: number) => {
this.currentIndex = index
})
.vertical(false)
.barHeight("77lpx")
//间隔符
Column() {
// 页签
Row({ space: 7 }) {
Scroll() {
Row() {
this.TabBuilder(0,"评论")
this.TabBuilder(1,"关注")
Divider().width('100%').height('12lpx').color($r('app.color.color_F5F5F5')).strokeWidth('12lpx')
//tab 页面
Stack({ alignContent: Alignment.Top }){
Tabs({controller: this.controller}) {
TabContent() {
HomePageBottomCommentComponent({commentNum:$commentNum})
}
TabContent() {
HomePageBottomFollowComponent()
}
}
.backgroundColor($r('app.color.white'))
.animationDuration(0)
.onChange((index: number) => {
this.currentIndex = index
})
.vertical(false)
.barHeight("77lpx")
Column() {
// 页签
Row({ space: 7 }) {
Scroll() {
Row() {
this.TabBuilder(0,"评论")
this.TabBuilder(1,"关注")
}
.justifyContent(FlexAlign.Start)
}
.justifyContent(FlexAlign.Start)
.align(Alignment.Start)
.scrollable(ScrollDirection.Horizontal)
.scrollBar(BarState.Off)
.width('100%')
.padding({left:'31lpx'})
}
.align(Alignment.Start)
.scrollable(ScrollDirection.Horizontal)
.scrollBar(BarState.Off)
.alignItems(VerticalAlign.Bottom)
.width('100%')
.padding({left:'31lpx'})
}
.alignItems(VerticalAlign.Bottom)
.backgroundColor($r('app.color.white'))
.alignItems(HorizontalAlign.Start)
.width('100%')
.height('77lpx')
}
.backgroundColor($r('app.color.white'))
.alignItems(HorizontalAlign.Start)
.width('100%')
.height('77lpx')
}
}.width("100%")
}.width("100%")
}
.edgeEffect(EdgeEffect.None)
.scrollBar(BarState.Off)
.width('100%')
.layoutWeight(1)
}
.edgeEffect(EdgeEffect.None)
.scrollBar(BarState.Off)
.width('100%')
.layoutWeight(1)
}.width('100%')
.layoutWeight(1)
}else{
Column(){
CustomTitleUI({ titleName: "" })
EmptyComponent({ emptyType: 1,emptyHeight:"100%" ,retry: () => {
this.isConnectNetwork = NetworkUtil.isNetConnected()
if(this.isConnectNetwork){
this.getUserInfo()
}
},})
.layoutWeight(1)
.width('100%')
}
}.width('100%')
.layoutWeight(1)
}
}
@Builder MineHomeTitleTransparent() {
... ...
import router from '@ohos.router'
import { Params } from 'wdBean';
import { StringUtils } from 'wdKit';
import { NetworkUtil, StringUtils } from 'wdKit';
import { OtherHomePageBottomCommentComponent } from '../components/mine/home/OtherHomePageBottomCommentComponent';
import { OtherHomePageBottomFollowComponent } from '../components/mine/home/OtherHomePageBottomFollowComponent';
import { CustomTitleUI } from '../components/reusable/CustomTitleUI';
import { EmptyComponent } from '../components/view/EmptyComponent';
import MinePageDatasModel from '../model/MinePageDatasModel';
import { OtherUserDetailRequestItem } from '../viewmodel/OtherUserDetailRequestItem';
... ... @@ -39,6 +41,7 @@ struct OtherNormalUserHomePage {
@State attentionNum:number = 0//关注数
@State desc:string = ""
userType:string = "1"
@State isConnectNetwork : boolean = NetworkUtil.isNetConnected()
aboutToAppear(){
this.getUserInfo()
... ... @@ -47,185 +50,202 @@ struct OtherNormalUserHomePage {
build() {
Stack({ alignContent: Alignment.Top }){
Image($r('app.media.title_bg'))
.width('100%')
.height('355lpx')
.objectFit(ImageFit.Cover)
Column(){
Stack({ alignContent: Alignment.Top }){
this.MineHomeTitleTransparent()
this.MineHomeTitleWhite()
}
if(this.isConnectNetwork){
Stack({ alignContent: Alignment.Top }){
Image($r('app.media.title_bg'))
.width('100%')
.height('355lpx')
.objectFit(ImageFit.Cover)
Column(){
Stack({ alignContent: Alignment.Top }){
this.MineHomeTitleTransparent()
this.MineHomeTitleWhite()
}
Scroll() {
Column() {
//用户信息区域
Row() {
Stack(){
Image(this.headPhotoUrl)
.alt($r('app.media.default_head'))
.width('100lpx')
.height('100lpx')
.objectFit(ImageFit.Cover)
.borderRadius(50)
Image(this.levelHead)
.width('130lpx')
.height('130lpx')
.objectFit(ImageFit.Cover)
.borderRadius(50)
}
Scroll() {
Column() {
//用户信息区域
Row() {
Stack(){
Image(this.headPhotoUrl)
.alt($r('app.media.default_head'))
.width('115lpx')
.height('115lpx')
.objectFit(ImageFit.Cover)
.clip(new Circle({ width: '115lpx', height: '115lpx' }))
Image(this.levelHead)
.width('165lpx')
.height('165lpx')
.objectFit(ImageFit.Cover)
}
Column() {
Row() {
Text(`${this.userName}`)
.fontColor($r('app.color.white'))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.fontSize('38lpx')
.lineHeight('50lpx')
.fontWeight('500lpx')
Text(`等级${this.levelId}`)
.textAlign(TextAlign.Center)
.fontColor($r('app.color.color_ED2800'))
.backgroundColor($r('app.color.white'))
.fontSize('19lpx')
.width('96lpx')
.height('35lpx')
.margin({ left: '10lpx' })
Blank()
}.width('507lpx')
Row() {
Row() {
Text(`${this.browseNum}`)
.textStyle()
Text("阅读")
.textStyle2()
}
.margin({ right: '15lpx' })
Divider()
.height('19lpx')
.width('2lpx')
.color($r('app.color.white'))
.vertical(true)
.opacity(0.4)
Column() {
Row() {
Text(`${this.commentNum}`)
.textStyle()
Text("评论")
.textStyle2()
}.margin({ right: '15lpx', left: '15lpx' })
Divider()
.height('19lpx')
.width('2lpx')
.color($r('app.color.white'))
.vertical(true)
.opacity(0.4)
Text(`${this.userName}`)
.fontColor($r('app.color.white'))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.fontSize('38lpx')
.lineHeight('50lpx')
.fontWeight('500lpx')
if(this.levelId>0){
Text(`等级${this.levelId}`)
.fontColor($r('app.color.color_ED2800'))
.fontSize('23lpx')
.fontWeight(500)
.margin({ left: '10lpx' })
.backgroundImage($r("app.media.my_grade_bg"))
.backgroundImageSize(ImageSize.Cover)
.padding({left:"17lpx",right:"8lpx"})
.height('35lpx')
}
Blank()
}.width('507lpx')
Row() {
Text(`${this.attentionNum}`)
.textStyle()
Text("关注")
.textStyle2()
}.margin({ left: '15lpx' })
}.margin({ top: '23lpx' })
}.alignItems(HorizontalAlign.Start)
.margin({ left: '32lpx' })
}
.onAreaChange((oldValue: Area, newValue: Area) => {
if (this.firstPositionY === 0) {
this.firstPositionY = newValue.globalPosition.y as number
}else{
let persent = (this.firstPositionY - Number(newValue.globalPosition.y)) / (this.firstPositionY * 0.3)
if(persent > 1){
persent = 1
}
this.tileOpacity = persent
Row() {
Text(`${this.browseNum}`)
.textStyle()
Text("阅读")
.textStyle2()
}
.margin({ right: '15lpx' })
Divider()
.height('19lpx')
.width('2lpx')
.color($r('app.color.white'))
.vertical(true)
.opacity(0.4)
Row() {
Text(`${this.commentNum}`)
.textStyle()
Text("评论")
.textStyle2()
}.margin({ right: '15lpx', left: '15lpx' })
Divider()
.height('19lpx')
.width('2lpx')
.color($r('app.color.white'))
.vertical(true)
.opacity(0.4)
Row() {
Text(`${this.attentionNum}`)
.textStyle()
Text("关注")
.textStyle2()
}.margin({ left: '15lpx' })
}.margin({ top: '23lpx' })
}.alignItems(HorizontalAlign.Start)
.margin({ left: StringUtils.isEmpty(this.levelHead)?'32lpx':"3lpx" })
}
})
.backgroundColor($r('app.color.color_transparent'))
.height('184lpx')
.width('100%')
.padding({ left: '35lpx' })
//用户简介区域
if(StringUtils.isNotEmpty(this.desc)){
Column() {
Row() {
Text(this.desc)
.fontSize('27lpx')
.maxLines(3)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.lineHeight('40lpx')
.fontWeight('400lpx')
.fontColor($r('app.color.color_222222'))
.textAlign(TextAlign.Start)
}
}.padding({ left: '31lpx',right:'31lpx',top:'19lpx',bottom:'31lpx'})
.alignItems(HorizontalAlign.Start)
.justifyContent(FlexAlign.Center)
.width('100%')
.backgroundColor($r('app.color.white'))
}
//间隔符
Divider().width('100%').height('12lpx').color($r('app.color.color_F5F5F5')).strokeWidth('12lpx')
//tab 页面
Stack({ alignContent: Alignment.Top }){
Tabs({controller: this.controller}) {
TabContent() {
OtherHomePageBottomCommentComponent({curUserId:this.curUserId,levelHead:this.levelHead,commentNum:$commentNum})
}
TabContent() {
OtherHomePageBottomFollowComponent({curUserId:this.curUserId})
.onAreaChange((oldValue: Area, newValue: Area) => {
if (this.firstPositionY === 0) {
this.firstPositionY = newValue.globalPosition.y as number
}else{
let persent = (this.firstPositionY - Number(newValue.globalPosition.y)) / (this.firstPositionY * 0.3)
if(persent > 1){
persent = 1
}
this.tileOpacity = persent
}
}
.backgroundColor($r('app.color.white'))
.animationDuration(0)
.onChange((index: number) => {
this.currentIndex = index
})
.vertical(false)
.barHeight('77lpx')
.backgroundColor($r('app.color.color_transparent'))
.height('184lpx')
.width('100%')
.padding({ left: '6lpx' })
Column() {
// 页签
Row({ space: 7 }) {
Scroll() {
Row() {
this.TabBuilder(0,"评论")
this.TabBuilder(1,"关注")
//用户简介区域
if(StringUtils.isNotEmpty(this.desc)){
Column() {
Row() {
Text(this.desc)
.fontSize('27lpx')
.maxLines(3)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.lineHeight('40lpx')
.fontWeight('400lpx')
.fontColor($r('app.color.color_222222'))
.textAlign(TextAlign.Start)
}
}.padding({ left: '31lpx',right:'31lpx',top:'19lpx',bottom:'31lpx'})
.alignItems(HorizontalAlign.Start)
.justifyContent(FlexAlign.Center)
.width('100%')
.backgroundColor($r('app.color.white'))
}
//间隔符
Divider().width('100%').height('12lpx').color($r('app.color.color_F5F5F5')).strokeWidth('12lpx')
//tab 页面
Stack({ alignContent: Alignment.Top }){
Tabs({controller: this.controller}) {
TabContent() {
OtherHomePageBottomCommentComponent({curUserId:this.curUserId,levelHead:this.levelHead,commentNum:$commentNum})
}
TabContent() {
OtherHomePageBottomFollowComponent({curUserId:this.curUserId})
}
}
.backgroundColor($r('app.color.white'))
.animationDuration(0)
.onChange((index: number) => {
this.currentIndex = index
})
.vertical(false)
.barHeight('77lpx')
Column() {
// 页签
Row({ space: 7 }) {
Scroll() {
Row() {
this.TabBuilder(0,"评论")
this.TabBuilder(1,"关注")
}
.justifyContent(FlexAlign.Start)
}
.justifyContent(FlexAlign.Start)
.align(Alignment.Start)
.scrollable(ScrollDirection.Horizontal)
.scrollBar(BarState.Off)
.width('90%')
.padding({left:'31lpx'})
}
.align(Alignment.Start)
.scrollable(ScrollDirection.Horizontal)
.scrollBar(BarState.Off)
.width('90%')
.padding({left:'31lpx'})
.alignItems(VerticalAlign.Bottom)
.width('100%')
}
.alignItems(VerticalAlign.Bottom)
.backgroundColor($r('app.color.white'))
.alignItems(HorizontalAlign.Start)
.width('100%')
.height('77lpx')
}
.backgroundColor($r('app.color.white'))
.alignItems(HorizontalAlign.Start)
.width('100%')
.height('77lpx')
}
}.width("100%")
}.width("100%")
}
.edgeEffect(EdgeEffect.None)
.scrollBar(BarState.Off)
.width('100%')
.layoutWeight(1)
}
.edgeEffect(EdgeEffect.None)
.scrollBar(BarState.Off)
.width('100%')
.layoutWeight(1)
}.width('100%')
.layoutWeight(1)
}else{
Column(){
CustomTitleUI({ titleName: "" })
EmptyComponent({ emptyType: 1,emptyHeight:"100%" ,retry: () => {
this.isConnectNetwork = NetworkUtil.isNetConnected()
if(this.isChangeToUserEdit){
this.getUserInfo()
}
},})
.layoutWeight(1)
.width('100%')
}
}.width('100%')
.layoutWeight(1)
}
}
@Builder MineHomeTitleTransparent() {
... ...
import { CompDTO, ContentDTO, InteractDataDTO, LiveReviewDTO, LiveRoomDataBean, PageDTO, PageInfoDTO } from 'wdBean';
import { CompStyle, ViewType } from 'wdConstant/Index';
import { CollectionUtils, DateTimeUtils, LazyDataSource, Logger, NetworkUtil, StringUtils } from 'wdKit';
import { CollectionUtils, DateTimeUtils, LazyDataSource, Logger, NetworkUtil, StringUtils, ToastUtils } from 'wdKit';
import { closeRefresh } from '../utils/PullDownRefresh';
import PageModel from './PageModel';
import PageViewModel from './PageViewModel';
... ... @@ -33,9 +33,16 @@ export class PageHelper {
* 刷新数据
*/
async refreshUI(pageModel: PageModel, pageAdvModel: PageAdModel) {
let netStatus = NetworkUtil.isNetConnected()
if (!netStatus) {
ToastUtils.showToast('网络出小差了,请检查网络后重试', 1000)
setTimeout(() => {
closeRefresh(pageModel, false)
}, 500)
return
}
pageModel.loadStrategy = 2
pageModel.pageTotalCompSize = 0;
// TODO 下拉刷新,是否加载缓存
this.getPageInfo(pageModel, pageAdvModel)
}
... ... @@ -43,6 +50,11 @@ export class PageHelper {
* 分页加载
*/
async loadMore(pageModel: PageModel) {
let netStatus = NetworkUtil.isNetConnected()
if (!netStatus) {
ToastUtils.showToast('网络出小差了,请检查网络后重试', 1000)
return
}
pageModel.loadStrategy = 3
// 暂只支持comp分页加载,节目分页加载的得完善框架(如直播回看节目数据分页)
this.compLoadMore(pageModel)
... ... @@ -52,55 +64,20 @@ export class PageHelper {
* 进页面请求数据
*/
async getInitCacheData(pageModel: PageModel, pageAdvModel: PageAdModel) {
Logger.error('zzzz', 'getInitCacheData')
Logger.debug(TAG, 'getInitCacheData')
PageViewModel.getPageInfoCache(pageModel.pageId).then(pageInfo => {
Logger.debug(TAG, 'getInitCacheData back: ' + pageInfo)
if (pageInfo == null) {
return;
}
pageModel.pageInfo = pageInfo;
pageModel.cachePageInfoMd5 = pageInfo.md5
//解析页面挂角广告资源
pageAdvModel.analysisAdvSource(pageInfo);
this.parseCacheGroup(pageModel)
this.parseGroup(pageModel, true)
})
}
async parseCacheGroup(pageModel: PageModel) {
Logger.error('zzzz', 'parseCacheGroup')
let pageInfo: PageInfoDTO = pageModel.pageInfo
pageModel.groupList = []
pageInfo.pageAdList = []
pageInfo.oneRequestPageGroupCompList = new ArrayList()
pageModel.groupList.push(...pageInfo.groups)
for (const group of pageInfo.groups) {
pageModel.groupId = group.id;
pageModel.groupData = group
// await,确保groups接口顺序执行
let pageDto = await PageViewModel.getPageGroupCacheData(pageModel.bizCopy()) as PageDTO
let index = pageInfo.groups.indexOf(group)
if (index == 0) {
// 清空comp列表
pageModel.compList.clear()
}
this.analysisPageGroupCompData(pageDto, pageInfo)
}
// 收集页面所有楼层的组件信息,同步完成广告投放计算,异步完成稿件批查,
pageModel.pageTotalCompSize = pageInfo.oneRequestPageGroupCompList.length + pageModel.pageTotalCompSize
// 处理页面广告数据,投放到页面的位置
// TODO 缓存数据不加载广告
// this.handlePageCompAdvPostion(pageInfo.oneRequestPageGroupCompList, pageModel, pageInfo.pageAdList);
//遍历所有组件和稿件数据 push到页面
for (let element of pageInfo.oneRequestPageGroupCompList) {
pageModel.compList.push(CompDTO.createNewsBean(element))
}
pageModel.currentPage++
pageModel.viewType = ViewType.LOADED
closeRefresh(pageModel, true)
}
/**
* 进页面请求数据
*/
... ... @@ -134,33 +111,51 @@ export class PageHelper {
promptAction.showToast({ message: err });
})
} else {
Logger.debug(TAG, 'getPageInfo')
PageViewModel.getPageInfo(pageModel.pageId).then(pageInfo => {
Logger.debug(TAG, 'getPageInfo back: ' + JSON.stringify(pageInfo))
if (pageInfo == null) {
pageModel.viewType = ViewType.EMPTY;
pageModel.emptyType = WDViewDefaultType.WDViewDefaultType_NoContent1;
return;
}
pageModel.pageInfo = pageInfo;
//解析页面挂角广告资源
pageAdvModel.analysisAdvSource(pageInfo);
this.parseGroup(pageModel)
// if (pageModel.currentPage == 1) {
// // 保存缓存
// CacheData.saveCacheData(CacheData.comPageInfoCacheKey + pageModel.pageId, pageInfo, pageInfo.md5)
// }
if (pageInfo.md5 == pageModel.cachePageInfoMd5) {
// 缓存一致,不解析
Logger.debug(TAG, 'getPageInfo 与缓存一致,不解析广告。。。')
} else {
Logger.debug(TAG, 'getPageInfo 要解析广告')
if (pageModel.currentPage == 1) {
// 保存缓存
CacheData.saveCacheData(CacheData.comPageInfoCacheKey + pageModel.pageId, pageInfo, pageInfo.md5)
}
//解析页面挂角广告资源
pageAdvModel.analysisAdvSource(pageInfo);
}
Logger.debug(TAG, 'getPageInfo go on')
this.parseGroup(pageModel, false)
}).catch(() => {
if (this.isPageLoaded(pageModel)) {
return
}
pageModel.viewType = ViewType.EMPTY;
pageModel.emptyType = WDViewDefaultType.WDViewDefaultType_ContentFailed;
})
}
}
private isPageLoaded(pageModel: PageModel) {
if (pageModel.compList.size() > 0) {
return true
}
return false
}
/**
* 解析信息流页面楼层数据
* @param pageModel
*/
async parseGroup(pageModel: PageModel) {
async parseGroup(pageModel: PageModel, isCache: boolean) {
let pageInfo: PageInfoDTO = pageModel.pageInfo
pageModel.groupList = []
pageInfo.pageAdList = []
... ... @@ -177,8 +172,26 @@ export class PageHelper {
pageModel.groupData = group
//Logger.error("ZZZXXXXX", '楼层id-start--》' + pageModel.groupId);
let pageDto: PageDTO
Logger.debug(TAG, 'parseGroup isCache: ' + isCache)
if (isCache) {
pageDto = await PageViewModel.getPageGroupCacheData(pageModel.bizCopy()) as PageDTO
pageModel.cacheGroupInfoMd5 = pageDto.md5
} else {
pageDto = await PageViewModel.getPageGroupCompData(pageModel.bizCopy()) as PageDTO
if (pageDto.md5 == pageModel.cacheGroupInfoMd5) {
Logger.debug(TAG, 'parseGroup cache load, return: ' + pageDto.md5)
// 缓存数据一致,不再刷新
return
}
Logger.debug(TAG, 'parseGroup cache load, save: ')
// 保存缓存
CacheData.saveCacheData(CacheData.compGroupInfoDataCacheKey + pageModel.pageId + pageModel.groupId, pageDto,
pageDto.md5)
}
Logger.debug(TAG, 'parseGroup go on')
// await,确保groups接口顺序执行
let pageDto = await PageViewModel.getPageGroupCompData(pageModel.bizCopy()) as PageDTO
// let pageDto = page
let index = pageInfo.groups.indexOf(group)
// 解析楼层组件
... ... @@ -197,9 +210,6 @@ export class PageHelper {
} else {
pageInfo.lastCompSourceType = 0
}
// // 保存缓存
// CacheData.saveCacheData(CacheData.compGroupInfoDataCacheKey + pageModel.pageId + pageModel.groupId, pageDto,
// pageDto.md5)
}
}
... ...
... ... @@ -63,6 +63,10 @@ export default class PageModel {
pageType: number = 0;
extra: string = ''
// 缓存数据相关
cachePageInfoMd5: string = ''
cacheGroupInfoMd5: string = ''
/**
* 简单复制业务数据
*/
... ...
... ... @@ -173,6 +173,10 @@
{
"name": "color_white_30",
"value": "#4D000000"
},
{
"name": "color_848484",
"value": "#848484"
}
]
}
\ No newline at end of file
... ...
... ... @@ -2,4 +2,5 @@ export { add } from "./src/main/ets/utils/Calc"
export { HWLocationUtils } from './src/main/ets/location/HWLocationUtils'
export { WDPushNotificationManager } from "./src/main/ets/notification/WDPushNotificationManager"
\ No newline at end of file
// export { WDPushNotificationManager } from "./src/main/ets/notification/WDPushNotificationManager"
export { GetuiPush } from "./src/main/ets/getuiPush/GetuiPush"
\ No newline at end of file
... ...
... ... @@ -7,10 +7,12 @@
"license": "Apache-2.0",
"packageType": "InterfaceHar",
"dependencies": {
"library": "file:./src/main/ets/getuiPush/GTSDK-1.0.1.0.har",
"wdConstant": "file:../../commons/wdConstant",
"wdLogin": "file:../../features/wdLogin",
"wdKit": "file:../../commons/wdKit",
"wdBean": "file:../../features/wdBean",
"wdRouter": "file:../../commons/wdRouter",
"wdNetwork": "file:../../commons/wdNetwork"
}
}
\ No newline at end of file
... ...
import { common, Want } from '@kit.AbilityKit';
import PushManager, {
BindAliasCmdMessage,
GTCmdMessage, GTNotificationMessage, GTTransmitMessage, PushConst,
SetTagCmdMessage,
Tag,
UnBindAliasCmdMessage } from 'library';
import { AppUtils, DeviceUtil, EmitterEventId, EmitterUtils, Logger, SPHelper } from 'wdKit/Index';
import { HostEnum, HostManager, HttpBizUtil, HttpUrlUtils, HttpUtils, ResponseDTO } from 'wdNetwork/Index';
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { SpConstants } from 'wdConstant/Index';
import { PushContentBean, PushContentParser } from './PushContentParser';
const TAG = "GetuiPush"
export class GetuiPush {
private static GETUI_APPID_ONLINE = "sMkzgp09Ov82nU1MGk7Ae6"
private static GETUI_APPID_TEST = "ZMi5AAXYHE84VN9p55YpW2"
private readonly ALIAS_SN_USERID = "userID"
private readonly TAG_SN_TAG = "tag1"
private readonly TAG_PD_ZH = "peopledaily_zh"
private cid: string = ""
private deviceToken: string = ""
private currentUserId = ""
private lastPushContent?: PushContentBean
private initialed = false
private constructor() {
}
private static manager: GetuiPush
static sharedInstance() : GetuiPush {
if (!GetuiPush.manager) {
GetuiPush.manager = new GetuiPush()
}
return GetuiPush.manager
}
init(context: common.UIAbilityContext) {
const isOnlineEnv = HostManager.getHost() === HostEnum.HOST_PRODUCT
PushManager.initialize({
appId:isOnlineEnv ? GetuiPush.GETUI_APPID_TEST : GetuiPush.GETUI_APPID_TEST,
context: context,
onSuccess: (cid:string) => {
Logger.debug(TAG, "个推SDK初始化成功,cid = " + cid)
this.initialed = true
this.cid = cid
this.registerEvents()
this.checkSetup()
},
onFailed: (error:string) => {
Logger.error(TAG, "个推SDK初始化失败,error = " + error)
}
})
}
async requestEnableNotifications(context: common.UIAbilityContext) : Promise<boolean> {
let enabled = await notificationManager.isNotificationEnabled()
if (!enabled) {
try {
await notificationManager.requestEnableNotification(context)
enabled = true
} catch (err) {
Logger.error(TAG, "请求通知权限报错: " + JSON.stringify(err))
let error = err as BusinessError
if (error.code == 1600004) {
Logger.error(TAG, "请求通知权限 - 用户已拒绝")
}
}
}
Logger.info(TAG, "推送 enabled " + enabled)
return enabled
}
checkSetup() {
if (!this.initialed) { return }
if (HttpUtils.isLogin()) {
const userId = SPHelper.default.getSync(SpConstants.USER_ID, "") as string
this.currentUserId = userId
this.setAlias(true, userId)
}
let tags = [this.TAG_PD_ZH, AppUtils.getAppVersionCode()]
this.setTags(tags)
}
// 默认是开启的
switchPush(turnOn: boolean) {
turnOn ? PushManager.turnOnPush() : PushManager.turnOffPush()
}
registerEvents() {
// 登录和退出
EmitterUtils.receiveEvent(EmitterEventId.LOGIN_SUCCESS, () => {
const userId = SPHelper.default.getSync(SpConstants.USER_ID, "") as string
this.currentUserId = userId
this.setAlias(true, userId)
})
EmitterUtils.receiveEvent(EmitterEventId.FORCE_USER_LOGIN_OUT, () => {
if (this.currentUserId.length) {
this.setAlias(false, this.currentUserId)
}
})
PushManager.setPushCallback({
// cid
onReceiveClientId: (clientId: string) => {
Logger.debug(TAG, "推送 接收到 clientId = " + clientId)
this.cid = PushManager.getClientId()
SPHelper.default.save(SpConstants.GETUI_PUSH_CID, this.cid)
this.uploadPushInfo(this.cid)
},
//接收⼚商token
onReceiveDeviceToken: (deviceToken:string) => {
Logger.debug(TAG, "推送 deviceToken = " + deviceToken)
this.deviceToken = deviceToken;
SPHelper.default.save(SpConstants.GETUI_PUSH_DEVICE_TOKEN, this.deviceToken)
},
// cid 离线上线通知
onReceiveOnlineState: (onLine:boolean) => {
Logger.debug(TAG, "推送 onLine State = " + onLine)
},
//命令相应回复
onReceiveCommandResult: (result: GTCmdMessage) => {
Logger.debug(TAG, "推送 Cmd Message = " + JSON.stringify(result))
this.dealWithCmdMessage(result)
},
//sdk 收到透传消息
onReceiveMessageData: (message: GTTransmitMessage) => {
Logger.debug(TAG, "推送 透传 Message = " + JSON.stringify(message))
this.dealWithTransmitMessage(message)
},
//通知到达回调
onNotificationMessageArrived: (message: GTNotificationMessage) => {
Logger.debug(TAG, "推送 通知到达回调 " + JSON.stringify(message))
},
//通知点击回调, 需要配合PushManager.setClickWant(want)使⽤
onNotificationMessageClicked: (message: GTNotificationMessage) => {
Logger.debug(TAG, "推送 通知 点击 回调 " + JSON.stringify(message))
},
})
}
setAlias(bind: boolean, alias: string, sn: string = this.ALIAS_SN_USERID) {
if (!this.initialed) { return }
if (bind) {
Logger.debug(TAG, "推送 绑定别名 " + alias)
PushManager.bindAlias(alias, sn)
} else {
Logger.debug(TAG, "推送 解绑别名 " + alias)
PushManager.unBindAlias(alias, true, sn)
}
}
setTags(tags: string[], sn: string = this.TAG_SN_TAG) {
if (!this.initialed) { return }
Logger.debug(TAG, "推送 设置标签 " + tags)
PushManager.setTag(tags.map((tag) => {
return new Tag().setName(tag)
}), sn)
}
setBadgeNumber(number: number) {
Logger.debug(TAG, "推送 设置角标 " + number)
PushManager.setBadgeNum(number)
}
// 接收推送数据,包括启动和二次点击拉起
// 参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/push-dev-0000001727885258
onWant(want: Want) {
this.onNewWant(want, true)
}
onNewWant(want: Want, startup: boolean = false) {
Logger.debug(TAG, "want: " + JSON.stringify(want))
this.lastPushContent = undefined
let pushContent = PushContentParser.getPushLinkFromWant(want)
if (pushContent && pushContent.isPush) {
Logger.debug(TAG, "接收到推送: " + JSON.stringify(want.parameters))
this.lastPushContent = pushContent
if (this.initialed) {
this.comsumeLastPushContent()
}
}
}
// 首次进入主页,即可解析跳转推送
onReachMainPage() {
if (this.initialed) {
this.comsumeLastPushContent()
} else {
this.lastPushContent = undefined
}
}
comsumeLastPushContent() {
if (!this.lastPushContent) {
return
}
if (this.lastPushContent.online) {
if (this.lastPushContent.want) {
Logger.debug(TAG, "推送 回执: " + this.lastPushContent.want)
PushManager.setClickWant(this.lastPushContent.want)
}
}
if (this.lastPushContent.pushLink) {
Logger.debug(TAG, "跳转对应页面: " + this.lastPushContent.pushLink)
PushContentParser.jumpWithPushLink(this.lastPushContent.pushLink)
}
this.lastPushContent = undefined
}
private dealWithCmdMessage(result: GTCmdMessage) {
let action: Number = result.action;
if (action === PushConst.BIND_ALIAS_RESULT) {
let bindAliasCmdMessage = result as BindAliasCmdMessage;
/* code 结果说明
0:成功
10099:SDK 未初始化成功
30001:绑定别名失败,频率过快,两次调⽤的间隔需⼤于 1s
30002:绑定别名失败,参数错误
30003:当前 cid 绑定别名次数超限
30004:绑定别名失败,未知异常
30005:绑定别名时,cid 未获取到
30006:绑定别名时,发⽣⽹络错误
30007:别名⽆效
30008:sn ⽆效 */
let code = bindAliasCmdMessage.code
if (code == 0) {
Logger.debug(TAG, "推送 Cmd BindAlias 成功 " + bindAliasCmdMessage.sn)
} else {
Logger.debug(TAG, "推送 Cmd BindAlias 失败 "
+ ",sn = "+bindAliasCmdMessage.sn
+ ",clinetId = "+bindAliasCmdMessage.clientId
+ ",pkgname = "+bindAliasCmdMessage.pkgName
+ ",appId = "+bindAliasCmdMessage.appId
+ ",action = "+result.action
+ ",code ="+bindAliasCmdMessage.code)
}
} else if (action === PushConst.UNBIND_ALIAS_RESULT) {
let unBindAliasCmdMessage = result as UnBindAliasCmdMessage
/* code 结果说明
0:成功
10099:SDK 未初始化成功
30001:解绑别名失败,频率过快,两次调⽤的间隔需⼤于 1s
30002:解绑别名失败,参数错误
30003:当前 cid 解绑别名次数超限
30004:解绑别名失败,未知异常
30005:解绑别名时,cid 未获取到
30006:解绑别名时,发⽣⽹络错误
30007:别名⽆效
30008:sn ⽆效*/
let code = unBindAliasCmdMessage.code
if (code == 0) {
Logger.debug(TAG, "推送 Cmd UnBindAlias 成功 " + unBindAliasCmdMessage.sn)
} else {
Logger.debug(TAG, "推送 Cmd UnBindAlias 失败 "
+ ",sn = "+unBindAliasCmdMessage.sn
+ ",clinetId = "+unBindAliasCmdMessage.clientId
+ ",pkgname = "+unBindAliasCmdMessage.pkgName
+ ",appId = "+unBindAliasCmdMessage.appId
+ ",action = "+result.action
+ ",code ="+unBindAliasCmdMessage.code)
}
} else if (action === PushConst.SET_TAG_RESULT) {
let setTagCmdMessage = result as SetTagCmdMessage
/* code 值说明
0:成功
10099:SDK 未初始化成功
20001:tag 数量过⼤(单次设置的 tag 数量不超过 100)
20002:调⽤次数超限(默认⼀天只能成功设置⼀次)
20003:标签重复
20004:服务初始化失败
20005:setTag 异常
20006:tag 为空
20007:sn 为空
20008:离线,还未登陆成功
20009:该 appid 已经在⿊名单列表(请联系技术⽀持处理)
20010:已存 tag 数⽬超限
20011:tag 内容格式不正确 */
let code = setTagCmdMessage.code
if (code == 0) {
Logger.debug(TAG, "推送 Cmd SetTag 成功 " + setTagCmdMessage.sn)
} else {
Logger.debug(TAG, "推送 Cmd SetTag 失败 "
+ ",sn = "+setTagCmdMessage.sn
+ ",clinetId = "+setTagCmdMessage.clientId
+ ",pkgname = "+setTagCmdMessage.pkgName
+ ",appId = "+setTagCmdMessage.appId
+ ",action = "+result.action
+ ",code ="+setTagCmdMessage.code)
}
}
}
private dealWithTransmitMessage(message: GTTransmitMessage) {
// const taskid = message.taskId
// const messageId = message.messageId
// /* 上报个推透传消息的展示回执。如果透传消息本地创建通知栏消息“展示”了,则调⽤此⽅法上报。
// */
// int gtactionid = 60001;//gtactionid传⼊60001表示个推渠道消息展示了
// boolean result = PushManager.sendFeedbackMessag(taskid, messageid, gtactionid);
// /**
// * 上报个推透传消息的点击回执。如果透传消息本地创建通知栏消息“点击”了,则调⽤此⽅法上报。
// */
// int gtactionid = 60002;//gtactionid传⼊60002表示个推渠道消息点击了
// boolean result = PushManager.sendFeedbackMessage(taskid, messageid, gtactionid);
}
private uploadPushInfo(cid: string) {
const url = HttpUrlUtils.getUploadPushInfoUrl()
let bean: Record<string, string | number> = {}
bean["deviceId"] = DeviceUtil.clientId()
bean["cid"] = cid
bean["userId"] = SPHelper.default.getSync(SpConstants.USER_ID, "") as string
bean["appVersion"] = AppUtils.getAppVersionName()
bean["platform"] = 3
HttpBizUtil.post<ResponseDTO<string>>(url, bean).then((data) => {
Logger.debug(TAG, "上传cid成功" + JSON.stringify(data))
}).catch((e: BusinessError) => {
Logger.debug(TAG, "上传cid失败" + JSON.stringify(e))
})
}
}
\ No newline at end of file
... ...
import Want from '@ohos.app.ability.Want';
import { Logger } from 'wdKit/Index';
import { JSON } from '@kit.ArkTS';
import { AppInfo } from '@mpaas/framework';
import { AppInnerLink } from 'wdRouter/Index';
export interface PushContentBean {
isPush: boolean // 是否为推送数据
want?: Want // want参数 (用来在消费时,回执)
online: boolean // 解析want,是否为在线消息(在线走的是个推通道,离线走的是华为厂商通道)
pushLink?: string // 解析want,对应pushLink参数
}
/*
* */
export class PushContentParser {
private static LAUNCH_PARAM_GETUI_DATA = "gtdata"
private static LAUNCH_PARAM_GETUI_TASKID = "taskid"
private static LAUNCH_PARAM_GETUI_NOTIFYID = "_push_notifyid"
private static PUSH_PARAM_PUSH_LINK = "pushLink"
static getPushLinkFromWant(want: Want) : PushContentBean {
// 个推在线消息
if (want && want.parameters && want.parameters[PushContentParser.LAUNCH_PARAM_GETUI_DATA]) {
/*
{
"age": 12,
"gtdata": {
"actionid": "10010",
"appid": "ZMi5AAXYHE84VN9p55YpW2",
"bigStyle": 0,
"checkpackage": "com.peopledailychina.hosactivity",
"content": "通知内容444",
"feedbackid": "0",
"isFloat": false,
"messageid": "44fd0876c9834214a6b7032b35d9826b",
"notifID": 62288,
"notifyStyle": 0,
"payload": "",
"taskid": "TEST_0516_03a84918e7df6191502497ed2cbef384",
"title": "测试通知444",
"wantUri": "{\"deviceId\":\"\",\"bundleName\":\"com.peopledailychina.hosactivity\",\"abilityName\":\"EntryAbility\",\"uri\":\"rmrbapp://rmrb.app:8080/openwith\",\"action\":\"com.test.pushaction\",\"parameters\":{\"pushLink\":\"Getui\",\"age\":12}}"
},
"isCallBySCB": false,
"moduleName": "phone",
"pushLink": "Getui",
"ohos.aafwk.param.callerAbilityName": "",
"ohos.aafwk.param.callerBundleName": "com.ohos.sceneboard",
"ohos.aafwk.param.callerPid": 44239,
"ohos.aafwk.param.callerToken": 537702494,
"ohos.aafwk.param.callerUid": 20020018,
"specifyTokenId": 537063794
}
},*/
let gtData = want.parameters[PushContentParser.LAUNCH_PARAM_GETUI_DATA] as Record<string, string | number | object>
if (gtData[PushContentParser.LAUNCH_PARAM_GETUI_TASKID] != undefined) {
let json = JSON.parse(gtData["wantUri"] as string) as Record<string, string | number>
if (json && json[PushContentParser.PUSH_PARAM_PUSH_LINK] != null) {
const pushLink = json[PushContentParser.PUSH_PARAM_PUSH_LINK] as string
return {
isPush: true, online: true, pushLink: pushLink, want: want
}
}
}
}
/*
{
"deviceId": "",
"bundleName": "com.peopledailychina.hosactivity",
"abilityName": "EntryAbility",
"moduleName": "phone",
"uri": "rmrbapp://rmrb.app:8080/openwith",
"type": "",
"flags": 0,
"action": "com.test.pushaction",
"parameters": {
"_push_notifyid": 1,
"age": 12, // 自定义
"debugApp": false,
"isCallBySCB": false,
"moduleName": "phone",
"pushLink": "Getui", // 自定义
"ohos.aafwk.param.callerAbilityName": "PushServiceInnerAbility",
"ohos.aafwk.param.callerBundleName": "com.huawei.hms.pushservice",
"ohos.aafwk.param.callerPid": 22808,
"ohos.aafwk.param.callerToken": 537908725,
"ohos.aafwk.param.callerUid": 20004,
"ohos.dlp.params.sandbox": false
},
"entities": [
]
* */
// 离线消息,华为直接推送
if (want && want.parameters && want.parameters[PushContentParser.LAUNCH_PARAM_GETUI_NOTIFYID]) {
if (want.parameters[PushContentParser.PUSH_PARAM_PUSH_LINK]) {
let pushLink = want.parameters[PushContentParser.PUSH_PARAM_PUSH_LINK] as string
return {
isPush: true, online: false, pushLink: pushLink, want: want
}
}
}
return {
isPush: false, online: false
}
}
static jumpWithPushLink(pushLink: string) {
AppInnerLink.jumpWithLink(pushLink)
}
}
\ No newline at end of file
... ...
... ... @@ -7,7 +7,6 @@ import window from '@ohos.window';
import { BusinessError } from '@ohos.base';
import { DeviceUtil, EmitterEventId, EmitterUtils, WindowModel } from 'wdKit';
import { ConfigurationConstant } from '@kit.AbilityKit';
import { WDPushNotificationManager } from 'wdHwAbility/Index';
import { StartupManager } from '../startupmanager/StartupManager';
let floatWindowClass: window.Window | null = null;
... ... @@ -28,7 +27,7 @@ export default class EntryAbility extends UIAbility {
// App活着情况下,点击推送通知进入
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
WDPushNotificationManager.getInstance().onWant(want)
StartupManager.sharedInstance().appOnNewWant(want, launchParam)
}
onDestroy(): void {
... ...
import { BottomNavigationComponent, LogoutViewModel, PermissionDesComponent } from 'wdComponent';
import { BreakpointConstants } from 'wdConstant';
import { HWLocationUtils, WDPushNotificationManager } from 'wdHwAbility/Index';
import { common } from '@kit.AbilityKit';
import { BreakpointSystem, EmitterEventId, EmitterUtils, Logger, MpaasUpgradeCheck, WindowModel } from 'wdKit';
import { promptAction, window } from '@kit.ArkUI';
... ... @@ -33,16 +32,6 @@ struct MainPage {
this.breakpointSystem.register()
let context = getContext(this) as common.UIAbilityContext
WDPushNotificationManager.getInstance().requestEnableNotifications(context).then((enabled) => {
if (enabled) {
WDPushNotificationManager.getInstance().fetchTokenAndBindProfileId()
// WDPushNotificationManager.getInstance().sendLocalNotification()
}
HWLocationUtils.startLocationService()
})
Logger.info(TAG, `aboutToAppear `);
EmitterUtils.receiveEvent(EmitterEventId.FORCE_USER_LOGIN_OUT, () => {
LogoutViewModel.clearLoginInfo()
... ...
import { AbilityConstant, common, Want } from '@kit.AbilityKit'
import { WDPushNotificationManager } from 'wdHwAbility/Index'
import { DeviceUtil,
EmitterEventId,
EmitterUtils,
... ... @@ -16,6 +15,8 @@ import { HostEnum, HostManager, WDHttp } from 'wdNetwork/Index'
import { registerRouter } from 'wdRouter/Index'
import { TrackingModule } from 'wdTracking/Index'
import { JSON } from '@kit.ArkTS'
import app from '@system.app'
import { GetuiPush, HWLocationUtils } from 'wdHwAbility/Index'
const TAG = "[StartupManager]"
... ... @@ -24,6 +25,8 @@ export class StartupManager {
private context?: common.UIAbilityContext
private constructor() {
}
private static _manger?: StartupManager
static sharedInstance(): StartupManager {
if (!StartupManager._manger) {
... ... @@ -36,6 +39,8 @@ export class StartupManager {
appOnCreate(want: Want, launchParam: AbilityConstant.LaunchParam, context: common.UIAbilityContext) {
Logger.debug(TAG, "App onCreate: " + `\nwant: ${want}\nlaunchParam: ${launchParam}`)
this.context = context
// 设置图片文件数据缓存上限为200MB (200MB=200*1024*1024B=209715200B)
app.setImageFileCacheSize(209715200)
// KV存储
SPHelper.init(context);
... ... @@ -57,10 +62,14 @@ export class StartupManager {
this.preInitUmentStat()
// 通知栏点击后启动
WDPushNotificationManager.getInstance().onWant(want)
GetuiPush.sharedInstance().onWant(want)
Logger.debug(TAG, "App onCreate: finised")
}
appOnNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) {
GetuiPush.sharedInstance().onNewWant(want)
}
appOnDestory() {
Logger.debug(TAG, "App onDestory")
NetworkManager.getInstance().release()
... ... @@ -88,13 +97,19 @@ export class StartupManager {
Logger.debug(TAG, "App 必要初始化完成")
}
// 到达主页后,初始化非必须部分
// 初次到达主页后,初始化非必须部分
appReachMainPage() : Promise<void> {
return new Promise((resolve) => {
Logger.debug(TAG, "App 进入首页,开始其他任务初始化")
Logger.debug(TAG, "App 初次进入首页,开始其他任务初始化")
LoginModule.reportDeviceInfo()
GetuiPush.sharedInstance().requestEnableNotifications(this.context!).then((enabled) => {
HWLocationUtils.startLocationService()
})
GetuiPush.sharedInstance().onReachMainPage()
//TODO:
resolve()
... ... @@ -127,7 +142,8 @@ export class StartupManager {
}
private initGeTuiPush() {
// Logger.debug(TAG, "App 初始化")
Logger.debug(TAG, "App 个推推送 初始化")
GetuiPush.sharedInstance().init(this.context!)
}
private initLocation() {
... ... @@ -167,4 +183,4 @@ export class StartupManager {
private initOthers() {
}
}
\ No newline at end of file
}
... ...
... ... @@ -14,7 +14,7 @@
"pages": "$profile:main_pages",
"abilities": [
{
"name": "EntryAbility",
"name": "EntryAbility", // 这里不能改动,和后台推送有绑定
"srcEntry": "./ets/entryability/EntryAbility.ets",
"description": "$string:EntryAbility_desc",
"icon": "$media:app_icon",
... ... @@ -28,8 +28,15 @@
"entity.system.home"
],
"actions": [
"action.system.home"
]
"action.system.home",
"com.test.pushaction"
],
"uris" : [{
"scheme": 'rmrbapp',
"host": 'rmrb.app',
'port': '8080',
"path": 'openwith'
}]
}
]
}
... ...