Skip to content

Instantly share code, notes, and snippets.

@gnsx
Last active October 30, 2018 08:51
Show Gist options
  • Save gnsx/a227ac962c248e06ebac3b8b3552f17e to your computer and use it in GitHub Desktop.
Save gnsx/a227ac962c248e06ebac3b8b3552f17e to your computer and use it in GitHub Desktop.
C# script for Unity to share via Android
/*
Credit:
https://medium.com/@agrawalsuneet/native-android-text-sharing-in-unity-app-23f7f8e69978
*/
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class NativeTextShare : MonoBehaviour {
public Button shareButton;
private bool isFocus = false;
private bool isProcessing = false;
void Start () {
shareButton.onClick.AddListener (ShareText);
}
void OnApplicationFocus (bool focus) {
isFocus = focus;
}
private void ShareText () {
#if UNITY_ANDROID
if (!isProcessing) {
StartCoroutine (ShareTextInAnroid ());
}
#else
Debug.Log("No sharing set up for this platform.");
#endif
}
#if UNITY_ANDROID
public IEnumerator ShareTextInAnroid () {
var shareSubject = "I challenge you to beat my high score in Fire Block";
var shareMessage = "I challenge you to beat my high score in Fire Block. " +
"Get the Fire Block app from the link below. \nCheers\n\n" +
"http://onelink.to/fireblock";
isProcessing = true;
if (!Application.isEditor) {
//Create intent for action send
AndroidJavaClass intentClass =
new AndroidJavaClass ("android.content.Intent");
AndroidJavaObject intentObject =
new AndroidJavaObject ("android.content.Intent");
intentObject.Call<AndroidJavaObject>
("setAction", intentClass.GetStatic<string> ("ACTION_SEND"));
//put text and subject extra
intentObject.Call<AndroidJavaObject> ("setType", "text/plain");
intentObject.Call<AndroidJavaObject>
("putExtra", intentClass.GetStatic<string> ("EXTRA_SUBJECT"), shareSubject);
intentObject.Call<AndroidJavaObject>
("putExtra", intentClass.GetStatic<string> ("EXTRA_TEXT"), shareMessage);
//call createChooser method of activity class
AndroidJavaClass unity = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity =
unity.GetStatic<AndroidJavaObject> ("currentActivity");
AndroidJavaObject chooser =
intentClass.CallStatic<AndroidJavaObject>
("createChooser", intentObject, "Share your high score");
currentActivity.Call ("startActivity", chooser);
}
yield return new WaitUntil (() => isFocus);
isProcessing = false;
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment