S
S
Staspost2020-05-18 17:16:01
Android
Staspost, 2020-05-18 17:16:01

How to add sharing to social networks in Unity?

I'm trying to add to the application the ability to share in social networks (Vkontakte, Instagram, etc.) player achievements and game screenshots.
All the tutorials I found are already out of date. I have added the following code:

using System.Collections;
using UnityEngine;

public class NativeShare : MonoBehaviour
{
    private string text = "Тестовый текст";
    public string ScreenshotName = "screenshot.png"; // "имя" скриншота
    public string url = "https://play.google.com/"; //url приложения (например на маркете)
    private string urlApp = "https://play.google.com";

    /// <summary>
    /// Метод для кнопки. 
    /// </summary>
    ///<param name="text">Текст которым делимся</param>
    public void ShareScreenshotWithText(string text)
    {
        ScreenCapture.CaptureScreenshot(ScreenshotName);
        StartCoroutine(DelayedShare(text, url));
    }

    /// <summary>
    /// Небольшая пауза для скриншота и вызов метода "Поделиться"
    /// </summary>
    /// <param name="text">Текст которым делимся</param>
    /// <param name="urlApp">Ссылка на приложение</param>
    /// <returns></returns>
    private IEnumerator DelayedShare(string text, string urlApp)
    {
        yield return new WaitForSeconds(0.25f);
        string screenShotPath = Application.persistentDataPath + "/" + ScreenshotName;
        Share(text, screenShotPath, urlApp);
    }

    //"Делимся"
    private void Share(string shareText, string imagePath, string url, string subject = "")
    {
        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://" + imagePath);
        intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_STREAM"), uriObject);
        intentObject.Call<AndroidJavaObject>("setType", "image/png");

        intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TEXT"), shareText + "\n" + url);

        AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");

        AndroidJavaObject jChooser = intentClass.CallStatic<AndroidJavaObject>("createChooser", intentObject, subject);
        currentActivity.Call("startActivity", jChooser);
    }
}

It works on Android version 5, but it doesn't work on version 8. After reading about the problem, I found that starting from Android version 7, this code no longer works.
It gives the following errors:
5ec297fe995af779449477.png
I didn’t find anything suitable in the assets either: either there are reviews that the code doesn’t work either, or there are no necessary social networks, they rummage only on Twitter and Facebook, but I need VK and Instagram.
Maybe someone knows how to make the existing code work, or some plugin that works exactly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mopsicus, 2020-05-19
@mopsicus

You can try my plugins for iOS and Android: https://github.com/mopsicus/unity-share-plugin-ios...
Facebook
Twitter
Vkontakte
Odnoklassniki
WhatsApp
Viber
Telegram
Haven't updated for a long time, maybe something has fallen off already, but the source code is all Yes, you can tweak and update

S
Staspost, 2020-05-19
@Staspost

I found a good tutorial , did it, but the project is not going, swears at custom gradle, at the end of the build a message is displayed:

"the attribute [email protected]=android.support.v4.app.CoreComponentFactory in androidx.core:core1.0.0 collides whith another value" .

As I understand it, there is a conflict between androidx and android.support.v4, they are not supported at the same time.
I tried to replace the line "implementation 'com.android.support:appcompat-v7:28.0.0" in the above tutorial with "implementation 'androidx.core.content.FileProvider'", but the project still doesn't build, an error is thrown
"Build completed with a result of 'Failed' UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)".

I also found that I need to add a file to the Plugins folder
support-v4-24.1.1.aar

which can be taken in the SDK (in the above example, it was stored at: AndroidSDK\extras\android\m2repository\com\android\support\support-v4\24.1.1)
But I have only the intel folder in the extras folder, and the support file I didn’t find -v4-24.1.1.aar anywhere at all, probably it’s not shipped now (I downloaded SDK-24, it’s not in it either).
An example of my gradle file:
// Android Resolver Repos Start
([rootProject] + (rootProject.subprojects as List)).each {
    ext {
        it.setProperty("android.useAndroidX", true)
        it.setProperty("android.enableJetifier", true)
    }
}
([rootProject] + (rootProject.subprojects as List)).each { project ->
    project.repositories {
        def unityProjectPath = $/file:///**DIR_UNITYPROJECT**/$.replace("\\", "/")
        maven {
            url "https://maven.google.com"
        }
        maven {
            url (unityProjectPath + "/Assets/GeneratedLocalRepo/Firebase/m2repository") // Assets/Firebase/Editor/AnalyticsDependencies.xml:18, Assets/Firebase/Editor/AppDependencies.xml:20
        }
        maven {
            url (unityProjectPath + "/Assets/GeneratedLocalRepo/GooglePlayGames/Editor/m2repository") // Assets/GooglePlayGames/Editor/GooglePlayGamesPluginDependencies.xml:11
        }
        mavenLocal()
        jcenter()
        mavenCentral()
    }
}
// Android Resolver Repos End
apply plugin: 'com.android.library'
**APPLY_PLUGINS**

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
// Android Resolver Dependencies Start

    implementation 'com.google.firebase:firebase-analytics:17.3.0' // Assets/Firebase/Editor/AppDependencies.xml:15
    implementation 'com.google.firebase:firebase-analytics-unity:6.14.0' // Assets/Firebase/Editor/AnalyticsDependencies.xml:18
    implementation 'com.google.firebase:firebase-app-unity:6.14.0' // Assets/Firebase/Editor/AppDependencies.xml:20
    implementation 'com.google.firebase:firebase-common:19.3.0' // Assets/Firebase/Editor/AppDependencies.xml:13
    implementation 'com.google.games:gpgs-plugin-support:0.10.08' // Assets/GooglePlayGames/Editor/GooglePlayGamesPluginDependencies.xml:11
// Android Resolver Dependencies End
**DEPS**}

// Android Resolver Exclusions Start
android {
  packagingOptions {
      exclude ('/lib/armeabi/*' + '*')
      exclude ('/lib/mips/*' + '*')
      exclude ('/lib/mips64/*' + '*')
      exclude ('/lib/x86/*' + '*')
      exclude ('/lib/x86_64/*' + '*')
  }
}
// Android Resolver Exclusions End
android {
    compileSdkVersion **APIVERSION**
    buildToolsVersion '**BUILDTOOLS**'

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        minSdkVersion **MINSDKVERSION**
        targetSdkVersion **TARGETSDKVERSION**
        ndk {
            abiFilters **ABIFILTERS**
        }
        versionCode **VERSIONCODE**
        versionName '**VERSIONNAME**'
        consumerProguardFiles 'proguard-unity.txt'**USER_PROGUARD**
    }

    lintOptions {
        abortOnError false
    }

    aaptOptions {
        ignoreAssetsPattern = "!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~"
    }**PACKAGING_OPTIONS**
}**REPOSITORIES****SOURCE_BUILD_SETUP**
**EXTERNAL_SOURCES**
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'	
}

How do I get it to work and where can I find the support-v4-24.1.1.aar file?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question