H5 + 開發App(分享功能)


我們開發App有一個不可少的功能,就是分享功能。讓用戶將app分享到他的社交圈。比如微信 QQ 微博等等。

 

 准備工作:我們要先去申請相關的權限,

這是傳送門http://ask.dcloud.net.cn/article/36。有一些配置說明和權限申請地址

    騰訊已經轉移到QQ 互聯上去了,官網給的地址已經不可以用了。申請完將SDK配置好。也就是填上appid 和appsecret。

 如果沒有申請權限的情況下。可以真機調試但是不可以打包生成apk文件。

 

代碼實現的基本原理。

 1. 獲取分享服務對象列表獲取分享服務列表可以調用plus.share.getServices()接口。

2用戶分享信息前需要對分享平台是否授權過進行判斷,這個我們自己基本是知道的我們那些有授權那些沒有。

 3配置我們的分享消息

 4 分享按鈕點擊事件。

 下面是我的dome代碼,判斷授權和 界面彈出吐司提示函數不是必要的,只是開發時的提示有助於開發。實際項目中可以不使用。

//分享功能
document.getElementById('share').addEventListener('tap', function(event) {
shareHref();
})
var Intent = null,
File = null,
Uri = null,
main = null;
var shares = null;
var shareImageUrl = '';
mui.plusReady(function() {
updateSerivces();
if(plus.os.name == "Android") {
Intent = plus.android.importClass("android.content.Intent");
File = plus.android.importClass("java.io.File");
Uri = plus.android.importClass("android.net.Uri");
main = plus.android.runtimeMainActivity();
}
})
/**
* 更新分享服務
*/
function updateSerivces() {
plus.share.getServices(function(s) {
shares = {};
for(var i in s) {
var t = s[i];
shares[t.id] = t;
}
outSet("獲取分享服務列表成功");
}, function(e) {
outSet("獲取分享服務列表失敗:" + e.message);
});
}
/**
* 分享操作
*/
function shareAction(id, ex) {
var s = null;
if(!id || !(s = shares[id])) {
outLine("無效的分享服務!");
return;
}
if(s.authenticated) {
outSet("---已授權---");
shareMessage(s, ex);
} else {
outSet("---未授權---");
s.authorize(function() {
shareMessage(s, ex);
}, function(e) {
outLine("認證授權失敗");
});
}
}
/**
* 發送分享消息
*/
function shareMessage(s, ex) {
var msg = {
content: '快和我一起來玩鋤禾農場吧',
href: 'http://www.chnc.shop/chnc/1.html?id='+AppID,
title: '鋤禾農場',
content: '快和我一起來玩鋤禾農場吧',
thumbs: ["img/mmexp.png"],
pictures: ["img/mmexp.png"],
extra: {
scene: ex
}
};
s.send(msg, function() {
outLine("分享成功!");
}, function(e) {
outLine("分享失敗!");
});
}
/**
* 分享按鈕點擊事件
*/
function shareHref() {
var ids = [{
id: "weixin",
ex: "WXSceneSession" /*微信好友*/
}, {
id: "weixin",
ex: "WXSceneTimeline" /*微信朋友圈*/
}, {
id: "qq" /*QQ好友*/
}, {
id: "tencentweibo" /*騰訊微博*/
}, {
id: "sinaweibo" /*新浪微博*/
}],
bts = [{
title: "發送給微信好友"
}, {
title: "分享到微信朋友圈"
}, {
title: "分享到QQ"
}, {
title: "分享到騰訊微博"
}, {
title: "分享到新浪微博"
}];
plus.nativeUI.actionSheet({
cancel: "取消",
buttons: bts
},
function(e) {
var i = e.index;
if(i > 0) {
shareAction(ids[i - 1].id, ids[i - 1].ex);
}
}
);
}
function outSet(msg) {
console.log(msg);
}
// 界面彈出吐司提示
function outLine(msg) {
mui.toast(msg);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM