返回首页
最新
HarmonyOS 5 新闻应用 - 敲击分享功能实现案例
摘要
本文详细介绍了在 HarmonyOS 5.0 新闻应用中实现敲击分享功能的过程。使用 KnockManager 类来管理敲击分享事件,从而实现新闻内容的分享。
```typescript
export class KnockManager {
private static instance: KnockManager
private ctx?: common.UIAbilityContext
private isBind: boolean = false
private news?: NewsModel
static getInstance(ctx: common.UIAbilityContext, news: NewsModel) {
if (!KnockManager.instance) {
KnockManager.instance = new KnockManager(ctx, news)
}
return KnockManager.instance
}
constructor(ctx: common.UIAbilityContext, news: NewsModel) {
this.ctx = ctx
}
// 处理敲击逻辑
knockCallback(target: harmonyShare.SharableTarget) {
if (this.news && this.ctx) {
// 示例封面是媒体资源,写入沙盒
const media = this.ctx.resourceManager.getMediaContentSync(this.news.cover as Resource)
const filePath = this.ctx.filesDir + '/share_' + Date.now() + '.png'
const file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
fileIo.writeSync(file.fd, media.buffer)
const uri = fileUri.getUriFromPath(filePath)
// 创建分享数据
const shareData: systemShare.SharedData = new systemShare.SharedData({
utd: uniformTypeDescriptor.UniformDataType.HYPERLINK,
content: 'https://edition.cnn.com/2025/06/20/sport/lionel-messi-club-world-cup-inter-miami-spt',
thumbnailUri: uri,
title: this.news.title,
description: this.news.company,
})
// 敲击分享
target.share(shareData)
}
}
bindEvent() {
if (!this.isBind) {
harmonyShare.on('knockShare', (target) => {
this.knockCallback(target)
})
this.isBind = true
}
}
unBindEvent() {
harmonyShare.off('knockShare')
this.isBind = false
}
}
```
HarmonyOS 5 新闻应用 - 系统分享功能实现案例
摘要
本文详细介绍了在 HarmonyOS 5.0 新闻应用中实现系统分享功能的过程。通过使用 BarButton 组件和 systemShare 模块,实现了新闻链接的分享功能。
```javascript
BarButton({ icon: $r('sys.media.ohos_ic_public_share') })
.onClick(() => {
// 系统分享
const data = new systemShare.SharedData({
utd: uniformTypeDescriptor.UniformDataType.HYPERLINK,
title: 'NewsAPP',
content: ' `https://edition.cnn.com/` '
})
const controller = new systemShare.ShareController(data)
const ctx = this.getUIContext().getHostContext() as common.UIAbilityContext
controller.show(ctx, {
previewMode: systemShare.SharePreviewMode.DETAIL,
selectionMode: systemShare.SelectionMode.SINGLE
})
})
```
长时间潜水,我一直很享受这里的技术讨论,但最近我觉得有必要多评论几句。<p>通常,这里的体验是积极的,但有时讨论似乎停滞不前,我对一些评论有几点看法,然后过几个小时或一天再回来,发现我的评论被投了负分,却没有任何新的回复。<p>1)这感觉不像是自然流量。正常的投票(无论是赞成还是反对)是稳定的,而反对票则是集中出现,有时甚至在一两个小时后就出现。<p>2)我觉得这使得讨论贬值为一种受欢迎程度的竞争。如果你不同意我的观点,那也没关系,但你应该能够清晰地表达你的不同意见。如果人们只是不同意,并觉得有必要让我知道,他们应该在脑中充分处理我所写的内容,以形成一个连贯的理由。