版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
解决方案来源:http://resocoder.com/2017/03/31/social-sharing-tutorial-unity-android-code/
项目中要实现分享功能,一般情况下都是外接分享SDK,这样能快速集成到开发中,而且有的分享插件功能强大,不仅在各个平台都可以分享,而且能够在后台查看分享的数据,具有数据统计的功能,比如:Mob的社会化分享SDK,但是对于个人开发者来说,这些可能有点麻烦,但是有一种调用Android原生的分享功能,这样就好办了,下面看下代码:
using UnityEngine;
using System.Collections;
using System.IO;
public class NativeShareScript : MonoBehaviour {
public GameObject CanvasShareObj;
private bool isProcessing = false;
private bool isFocus = false;
public void ShareBtnPress()
{
if (!isProcessing)
{
CanvasShareObj.SetActive(true);
StartCoroutine(ShareScreenshot());
}
}
IEnumerator ShareScreenshot()
{
isProcessing = true;
yield return new WaitForEndOfFrame();
Application.CaptureScreenshot("screenshot.png", 2);
string destination = Path.Combine(Application.persistentDataPath, "screenshot.png");
yield return new WaitForSecondsRealtime(0.3f);
if (!Application.isEditor)
{
AndroidJavaClass intentClass = new AndroidJavaClass("android.content.Intent");
AndroidJavaObject intentObject = new AndroidJavaObject("android.content.Intent");
intentObject.Call<AndroidJavaObject>("setAction", intentClass.GetStatic<string>("ACTION_SEND"));
AndroidJavaClass uriClass = new AndroidJavaClass("android.net.Uri");
AndroidJavaObject uriObject = uriClass.CallStatic<AndroidJavaObject>("parse", "file://" + destination);
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_STREAM"),
uriObject);
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TEXT"),
"Can you beat my score?");
intentObject.Call<AndroidJavaObject>("setType", "image/jpeg");
AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject chooser = intentClass.CallStatic<AndroidJavaObject>("createChooser",
intentObject, "Share your new score");
currentActivity.Call("startActivity", chooser);
yield return new WaitForSecondsRealtime(1);
}
yield return new WaitUntil(() => isFocus);
CanvasShareObj.SetActive(false);
isProcessing = false;
}
private void OnApplicationFocus(bool focus)
{
isFocus = focus;
}
}
未完待续.....
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有