197 lines
7.6 KiB
C#
197 lines
7.6 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.IO;
|
|
using UnityEngine;
|
|
using UnityEngine.Android;
|
|
using UnityEngine.UI;
|
|
|
|
public class ShareScreenshotButton : MonoBehaviour
|
|
{
|
|
public Button screenshotButton;
|
|
private string fileName;
|
|
|
|
// Start is called before the first frame update
|
|
void Start()
|
|
{
|
|
if (!AndroidVersionIs11OrAbove() && !Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
|
|
{
|
|
// Si no tiene permisos, solicitarlos
|
|
Permission.RequestUserPermission(Permission.ExternalStorageWrite);
|
|
}
|
|
|
|
// Asignar la función al evento onClick del botón
|
|
screenshotButton.onClick.AddListener(TakeScreenshotAndShare);
|
|
}
|
|
|
|
public void CheckPermissions()
|
|
{
|
|
// Este método puede ser llamado en cualquier momento para verificar permisos
|
|
if (Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
|
|
{
|
|
Debug.Log("Permiso concedido para escribir en almacenamiento.");
|
|
}
|
|
else
|
|
{
|
|
Debug.Log("Permiso denegado para escribir en almacenamiento.");
|
|
}
|
|
}
|
|
|
|
public void TakeScreenshotAndShare()
|
|
{
|
|
fileName = "Screenshot_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".png";
|
|
// Iniciar la rutina para capturar y compartir la pantalla
|
|
StartCoroutine(CaptureAndShareScreenshot());
|
|
}
|
|
|
|
private IEnumerator CaptureAndShareScreenshot()
|
|
{
|
|
// Esperar al final del frame para asegurarse de que todo esté dibujado
|
|
yield return new WaitForEndOfFrame();
|
|
|
|
// Tomar la captura de pantalla y guardarla en la carpeta temporal del dispositivo
|
|
Texture2D screenshot = new(Screen.width, Screen.height, TextureFormat.RGB24, false);
|
|
screenshot.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
|
|
screenshot.Apply();
|
|
|
|
byte[] imageBytes = screenshot.EncodeToPNG();
|
|
|
|
if (AndroidVersionIs11OrAbove())
|
|
{
|
|
SaveImageToGalleryAndShare(imageBytes, fileName);
|
|
}
|
|
else
|
|
{
|
|
SaveImageToExternalStorageAndShare(imageBytes, fileName);
|
|
}
|
|
}
|
|
|
|
private bool AndroidVersionIs11OrAbove()
|
|
{
|
|
return (Application.platform == RuntimePlatform.Android && SystemInfo.operatingSystem.StartsWith("Android OS") && int.Parse(SystemInfo.operatingSystem.Split(' ')[2]) >= 11);
|
|
}
|
|
|
|
// Guardar en MediaStore (Android 11 o superior) y compartir
|
|
private void SaveImageToGalleryAndShare(byte[] imageBytes, string fileName)
|
|
{
|
|
try
|
|
{
|
|
AndroidJavaClass mediaStoreClass = new("android.provider.MediaStore$Images$Media");
|
|
AndroidJavaObject contentResolver = GetContentResolver();
|
|
AndroidJavaObject contentValues = new("android.content.ContentValues");
|
|
|
|
contentValues.Call("put", "title", fileName);
|
|
contentValues.Call("put", "mime_type", "image/png");
|
|
contentValues.Call("put", "relative_path", "Pictures/Screenshots");
|
|
|
|
AndroidJavaObject uri = contentResolver.Call<AndroidJavaObject>("insert", mediaStoreClass.GetStatic<AndroidJavaObject>("EXTERNAL_CONTENT_URI"), contentValues);
|
|
if (uri != null)
|
|
{
|
|
AndroidJavaObject outputStream = contentResolver.Call<AndroidJavaObject>("openOutputStream", uri);
|
|
outputStream.Call("write", imageBytes);
|
|
outputStream.Call("flush");
|
|
outputStream.Call("close");
|
|
|
|
Debug.Log("Captura guardada en la galería.");
|
|
ShareScreenshot(uri);
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError("No se pudo guardar la imagen en MediaStore.");
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Debug.LogError("Error al guardar la captura en MediaStore: " + ex.Message);
|
|
}
|
|
}
|
|
|
|
// Guardar en almacenamiento externo (para Android 8 a 10) y compartir
|
|
private void SaveImageToExternalStorageAndShare(byte[] imageBytes, string fileName)
|
|
{
|
|
try
|
|
{
|
|
string directory = GetExternalStorageDirectory();
|
|
|
|
if (!Directory.Exists(directory))
|
|
{
|
|
Directory.CreateDirectory(directory);
|
|
}
|
|
|
|
string filePath = Path.Combine(directory, fileName);
|
|
File.WriteAllBytes(filePath, imageBytes);
|
|
Debug.Log("Captura guardada en: " + filePath);
|
|
|
|
ShareScreenshot(new AndroidJavaObject("java.io.File", filePath));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Debug.LogError("Error al guardar la captura: " + ex.Message);
|
|
}
|
|
}
|
|
|
|
// Método para obtener la ruta del almacenamiento externo
|
|
private string GetExternalStorageDirectory()
|
|
{
|
|
AndroidJavaClass environment = new("android.os.Environment");
|
|
string directory = environment.CallStatic<AndroidJavaObject>("getExternalStoragePublicDirectory", environment.GetStatic<string>("DIRECTORY_PICTURES")).Call<string>("getAbsolutePath");
|
|
|
|
return directory;
|
|
}
|
|
|
|
// Compartir la captura de pantalla
|
|
private void ShareScreenshot(AndroidJavaObject fileOrUri)
|
|
{
|
|
try
|
|
{
|
|
AndroidJavaClass intentClass = new("android.content.Intent");
|
|
AndroidJavaObject intentObject = new("android.content.Intent");
|
|
|
|
intentObject.Call<AndroidJavaObject>("setAction", intentClass.GetStatic<string>("ACTION_SEND"));
|
|
intentObject.Call<AndroidJavaObject>("setType", "image/png");
|
|
|
|
// Obtener el contexto de Unity
|
|
AndroidJavaClass unityPlayer = new("com.unity3d.player.UnityPlayer");
|
|
AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
|
|
|
|
// Si es Android 11 o superior, usa el URI; si es anterior, usa FileProvider
|
|
if (AndroidVersionIs11OrAbove())
|
|
{
|
|
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_STREAM"), fileOrUri);
|
|
intentObject.Call<AndroidJavaObject>("addFlags", 1 << 1); // FLAG_GRANT_READ_URI_PERMISSION
|
|
}
|
|
else
|
|
{
|
|
AndroidJavaClass fileProviderClass = new AndroidJavaClass("androidx.core.content.FileProvider");
|
|
|
|
AndroidJavaObject uri = fileProviderClass.CallStatic<AndroidJavaObject>(
|
|
"getUriForFile",
|
|
currentActivity,
|
|
currentActivity.Call<string>("getPackageName") + ".fileprovider",
|
|
fileOrUri
|
|
);
|
|
|
|
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_STREAM"), uri);
|
|
intentObject.Call("addFlags", intentClass.GetStatic<int>("FLAG_GRANT_READ_URI_PERMISSION"));
|
|
//intentObject.Call<AndroidJavaObject>("addFlags", 1 << 1); // FLAG_GRANT_READ_URI_PERMISSION
|
|
}
|
|
|
|
AndroidJavaObject chooser = intentClass.CallStatic<AndroidJavaObject>("createChooser", intentObject, "Share Screenshot");
|
|
currentActivity.Call("startActivity", chooser);
|
|
|
|
Debug.Log("Cuadro de diálogo de compartir lanzado.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Debug.LogError("Error al compartir la captura: " + ex.Message);
|
|
}
|
|
}
|
|
|
|
// Obtener ContentResolver para Android
|
|
private AndroidJavaObject GetContentResolver()
|
|
{
|
|
AndroidJavaClass unityPlayer = new("com.unity3d.player.UnityPlayer");
|
|
AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
|
|
return currentActivity.Call<AndroidJavaObject>("getContentResolver");
|
|
}
|
|
}
|