Unity项目中调用Android方法实现分享功能

                                                   Unity项目中调用Android方法实现分享功能

解决方案来源: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("setAction", intentClass.GetStatic("ACTION_SEND"));
            AndroidJavaClass uriClass = new AndroidJavaClass("android.net.Uri");
            AndroidJavaObject uriObject = uriClass.CallStatic("parse", "file://" + destination);
            intentObject.Call("putExtra", intentClass.GetStatic("EXTRA_STREAM"),
                uriObject);
            intentObject.Call("putExtra", intentClass.GetStatic("EXTRA_TEXT"),
                "Can you beat my score?");
            intentObject.Call("setType", "image/jpeg");
            AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject currentActivity = unity.GetStatic("currentActivity");
            AndroidJavaObject chooser = intentClass.CallStatic("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;
    }
}

未完待续.....

 

你可能感兴趣的:(Unity游戏开发)