I am trying to create a share button in Unity. Just one button that when is pressed it will show the social media applications that is installed on your phone, and allows the user to share. I keep finding tutorials over how to create a facebook share button or a twitter share button. But I just want to create a simple share button that allows you to share with every social media application. Here is an example:
EXAMPLE
I found a few assets, but not for sure if they will work right.
Assets: https://www.assetstore.unity3d.com/en/#!/content/37320
This asset allows you to share an image, I don't need to share an image, just text. But I thought it wouldn't be hard to modify it and only do text.
There's two ways of doing this.
1. Create a native plugin, write wrapper code in Unity to call the native code (Probably the most widely used way to call native functions)
2. Write the code entirely in Unity, and use AndroidJavaObject to invoke the functions.
Option 1 - Native Java Code + Unity Wrapper
Here's a link I found on SO for the code for Sharing.
Here's a link to one of my older answers about plugins. You can modify the code there to fit your needs.
Option 2 - No native code.
This way is a little more interesting. We use Unity's AndroidJavaClass & AndroidJavaObject to eliminate the need of JARs altogether. Just stick the below code in a C# script, and call the function. (NOTE, I haven't tried this code, there may be errors. If there are, let me know and I'll edit my response)
private static AndroidJavaObject activity = null;
private static void CreateActivity () {
#if UNITY_ANDROID && !UNITY_EDITOR
if(activity == null)
activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").
GetStatic<AndroidJavaObject>("currentActivity");
#endif
}
public static void ShareActivity (string title, string subject, string body) {
CreateActivity();
AndroidJavaObject sharingIntent = new AndroidJavaObject("android.content.Intent", "android.intent.action.SEND")
.Call<AndroidJavaObject>("setType", "text/plain")
.Call<AndroidJavaObject>("putExtra", "android.intent.extra.TEXT", body)
.Call<AndroidJavaObject>("putExtra", "android.intent.extra.SUBJECT", subject);
AndroidJavaObject intent = new AndroidJavaObject("android.content.Intent", activity)
.CallStatic<AndroidJavaObject>("createChooser", sharingIntent, title);
activity.Call("startActivity", intent);
}
Don't forget to add the activity to your AndroidManifest.xml!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.InteropServices;
public class socioshare : MonoBehaviour
{
string subject = "Hey I am playing this awesome new game called SoccerCuby,do give it try and enjoy \n";
string body = "https://play.google.com/store/apps/details?id=com.KaliAJStudios.SoccerCuby";
public void OnAndroidTextSharingClick()
{
//FindObjectOfType<AudioManager>().Play("Enter");
StartCoroutine(ShareAndroidText());
}
IEnumerator ShareAndroidText()
{
yield return new WaitForEndOfFrame();
//execute the below lines if being run on a Android device
//Reference of AndroidJavaClass class for intent
AndroidJavaClass intentClass = new AndroidJavaClass("android.content.Intent");
//Reference of AndroidJavaObject class for intent
AndroidJavaObject intentObject = new AndroidJavaObject("android.content.Intent");
//call setAction method of the Intent object created
intentObject.Call<AndroidJavaObject>("setAction", intentClass.GetStatic<string>("ACTION_SEND"));
//set the type of sharing that is happening
intentObject.Call<AndroidJavaObject>("setType", "text/plain");
//add data to be passed to the other activity i.e., the data to be sent
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_SUBJECT"), subject);
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TITLE"), "TITLE");
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TEXT"), subject);
intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TEXT"), body);
//get the current activity
AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");
//start the activity by sending the intent data
AndroidJavaObject jChooser = intentClass.CallStatic<AndroidJavaObject>("createChooser", intentObject, "Share Via");
currentActivity.Call("startActivity",jChooser);
}
}
unable to display the 1st string i.e "subject" in the message. the 2nd string "body" is being displayed accurately.rest everything is working Fine.
Related
I would like to share image to Facebook for Android platform without using Native share sheet (chooser) and my intent is
click the custom designed button.
move to facebook app
open facebook share page or post directly.
but I can't find any method neither in the documentation or in the any website.
and I don't want to set up Fb SDK because of the version compatibility in the future.
It would be so thankful with Unity JNI way or Native Android way to implement this which meets the condition.
I tried as following methods.
facebook native android sharing
JNI (but it's implementation of using Chooser).
using AndroidJavaClass intentClass = new AndroidJavaClass("android.content.Intent");
using AndroidJavaObject intent = new AndroidJavaObject("android.content.Intent");
using AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
using AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");
using AndroidJavaObject unityContext = currentActivity.Call<AndroidJavaObject>("getApplicationContext");
intent.Call<AndroidJavaObject>("setPackage", "com.facebook.katana");
intent.Call<AndroidJavaObject>("setAction", intentClass.GetStatic<string>("ACTION_SEND"));
intent.Call<AndroidJavaObject>("setType", "image/*");
using var file = new AndroidJavaObject("java.io.File", path);
using var fileProvider = new AndroidJavaClass("androidx.core.content.FileProvider");
string packageName = unityContext.Call<string>("getPackageName");
string authority = packageName + ".fileprovider";
using var uri = fileProvider.CallStatic<AndroidJavaObject>("getUriForFile", unityContext, authority, file);
intent.Call<AndroidJavaObject>("addFlags", intentClass.GetStatic<int>("FLAG_GRANT_READ_URI_PERMISSION"));
intent.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_STREAM"), uri);
using var chooser = intentClass.CallStatic<AndroidJavaObject>("createChooser", intent, "Share Image to Facebook");
currentActivity.Call("startActivity", chooser);
I have been trying to integrate the Adobe Creative SDK in my app. I have added one extra activity which launches camera and gallery and saves the image in an ImageView.
I successfully passed the image to another activity but for using the Adobe Creative SDK you need an uri path.
After providing the uri path I am getting an error -
'AdobeImageIntent()' has private access in 'com.adobe.creativesdk.aviary.AdobeImageIntent'
here is the onCreate method -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
Bundle extras = getIntent().getExtras();
Bitmap bmp = (Bitmap) extras.getParcelable("imageBitmap");
String path = bmp.toString();
Uri imageUri = Uri.parse(path);
Intent imageEditorIntent = new AdobeImageIntent().Builder(this)
.setData(imageUri)
.withOutput(Uri.parse("file://" + getFilesDir() + "my-pic-name.jpg")) // output file destination
.withOutputFormaat(Bitmap.CompressFormat.JPEG)
.withOutputSize(MegaPixels.Mp5)
.withOutputQuality(90)
.build();
startActivityForResult(imageEditorIntent,1);
Intent cdsIntent = AdobeImageIntent.createCdsInitIntent(getBaseContext(),"CDS");
startService(cdsIntent);
imageView = (ImageView) findViewById(R.id.imageView);
}
why I am getting this error?
Thanks for help!
Hope I would get answers!!
Replace
Intent imageEditorIntent = new AdobeImageIntent().Builder(this)
^^^^^
with:
Intent imageEditorIntent = new AdobeImageIntent.Builder(this)
^^^^^
Possible issues with the code above
Try removing the cdsIntent and see if your code runs.
Without more information, it's hard to know, but it could be that both your cdsIntent and your imageView assignments are coming too late in onCreate().
Taking a photo from your app
You can create a new camera Intent and start it like this:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(cameraIntent, 400); // Can be any int
}
The results from the camera will come back to you in onActivityResult().
Handling the results from the camera Intent
How to handle the results will depend on what your app does. Google has a nice overview on the subject on the Android Developer Portal.
If you have further questions beyond the scope of this one, it may be good to make a new question to help get this one more focused.
I am doing an android share intent for Pinterest but is not fully working. I am able to attach the image but I can't send text to the "description" field in the share window. I've tried different types (text/plain, image/*, image/png) and also tried the ACTION_SEND_MULTIPLE intent type but still no luck. Google chrome share intent works perfectly so I'm sure Pinterest supports this functionality. Here is my code:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_TEXT, text);
if(file != null) intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setClassName(packageName, name);
this.startActivity(intent);
Any idea? thanks!
I found a way to share to Pinterest with plain Android intents (without using the Pinterest SDK), with help from Pin It button developer docs.
Basically you just open an URL like this with Intent.ACTION_VIEW; the official Pinterest app kindly supports these URLs. (I've earlier used a very similar approach for sharing to Twitter.)
https://www.pinterest.com/pin/create/button/
?url=http%3A%2F%2Fwww.flickr.com%2Fphotos%2Fkentbrew%2F6851755809%2F
&media=http%3A%2F%2Ffarm8.staticflickr.com%2F7027%2F6851755809_df5b2051c9_z.jpg
&description=Next%20stop%3A%20Pinterest
And for smoother user experience, set the intent to open directly in Pinterest app, if installed.
A complete example:
String shareUrl = "https://stackoverflow.com/questions/27388056/";
String mediaUrl = "http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png";
String description = "Pinterest sharing using Android intents"
String url = String.format(
"https://www.pinterest.com/pin/create/button/?url=%s&media=%s&description=%s",
urlEncode(shareUrl), urlEncode(mediaUrl), urlEncode(description));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
filterByPackageName(context, intent, "com.pinterest");
context.startActivity(intent);
Util methods used above:
public static void filterByPackageName(Context context, Intent intent, String prefix) {
List<ResolveInfo> matches = context.getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
if (info.activityInfo.packageName.toLowerCase().startsWith(prefix)) {
intent.setPackage(info.activityInfo.packageName);
return;
}
}
}
public static String urlEncode(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
}
catch (UnsupportedEncodingException e) {
Log.wtf("", "UTF-8 should always be supported", e);
return "";
}
}
This is the result on a Nexus 5 with Pinterest app installed:
And if Pinterest app is not installed, sharing works just fine via a browser too:
for some reason pinterest app doesn't comply to the standard (Intent.EXTRA_TEXT) so we have to add it separately
if(appInfo.activityInfo.packageName.contains("com.pinterest"){
shareIntent.putExtra("com.pinterest.EXTRA_DESCRIPTION","your description");
}
File imageFileToShare = new File(orgimagefilePath);
Uri uri = Uri.fromFile(imageFileToShare);
Intent sharePintrestIntent = new Intent(Intent.ACTION_SEND);
sharePintrestIntent.setPackage("com.pinterest");
sharePintrestIntent.putExtra("com.pinterest.EXTRA_DESCRIPTION", text);
sharePintrestIntent.putExtra(Intent.EXTRA_STREAM, uri);
sharePintrestIntent.setType("image/*");
startActivityForResult(sharePintrestIntent, PINTEREST);
I'm trying to send a mail along with multiple files attached to it, however I can't get them to be added to the mail.
I proceed like this:
private void SendMail (List<Data> ToSend)
{
var Attachments = new List<Android.Net.Uri>();
Intent i = new Intent (Android.Content.Intent.ActionSendMultiple);
i.SetType ("message/rfc822");
i.PutExtra (Android.Content.Intent.ExtraEmail, new String[]{"try#mail.com"});
i.PutExtra (Android.Content.Intent.ExtraSubject, "Test");
i.PutExtra (Android.Content.Intent.ExtraText, "Test Test...");
foreach (var content in ToSend) {
Java.IO.File myFile = new Java.IO.File(content.attachmentloc);
// attachmentloc is a string containing the absolute path to the file to attach.
var uri = Android.Net.Uri.FromFile(myFile);
Attachments.Add (uri);
}
i.PutParcelableArrayListExtra(Android.Content.Intent.ExtraStream, Attachments.ToArray());
StartActivityForResult(Intent.CreateChooser(i, "Send mail..."), 0);
}
I checked and the path in the string is good.. however the method .Exists (When used on the Java.IO.File in the foreach) returns false. might be the reason why ?
Thanks for the help.
EDIT:
When trying to add a single attachment, it works just fine.
However whenever I call a function that imply there will be more than one attachment, it fails.
Aka:
Intent i = new Intent (Android.Content.Intent.ActionSend);
var uri = Android.Net.Uri.Parse (ex._FileLocation);
i.PutExtra(Intent.ExtraStream, uri);
Works just fine however replacing
Intent i = new Intent (Android.Content.Intent.ActionSend);
By
Intent i = new Intent (Android.Content.Intent.ActionSendMultiple);
Leads to the same fail and so does replacing:
var uri = Android.Net.Uri.Parse (ex._FileLocation);
i.PutExtra(Intent.ExtraStream, uri);
By
var Attachments = new List<Android.Net.Uri> ();
foreach (var ex in ToSend) {
var uri = Android.Net.Uri.Parse (ex._FileLocation);
Attachments.Add (uri);
//o
}
i.PutParcelableArrayListExtra (Android.Content.Intent.ExtraStream, Attachments.ToArray ());
... I'm using the default mail application (not gmail)
I also tried setting the intent type to " * / * " (without spaces) as suggested somewhere else.
Also tried AddFlags (ActivityFlags.GrantReadUriPermission);
As it works with a single attachment, I know the URIs are valid for sure...
I'd really need help.
I personally found no valid answer to this problem.
Only answer I found is a workaround: compress all the file into a single .zip archive and send that archive as the single attachment.
might be, the mail activity has not enough rights to read your file. Try to add myFile.setReadable(true, false) either when creating file, or here before adding to Attachments array.
I'm attempting to add a shared intent to post to Google Plus and can't seem to resolve the issue of passing the new ShareCompat.IntentBuilder (Android support library class) to the startActivity method. I'm started out using this example. My app is compiled using Android 2.2 platform. Is it possible that there is another supporting way to start the Activity to launch the shared intent.
IntentBuilder shareIntent = ShareCompat.IntentBuilder.from(MyActivity.this);
shareIntent.setText(message);
shareIntent.setSubject(subject);
if (mFullFileName != null) {
File imageFile = new File(mFullFileName);
if (imageFile.exists()) {
shareIntent.setStream(Uri.fromFile(imageFile));
shareIntent.setType("image/jpeg");
}
} else {
shareIntent.setType("*.*");
}
shareIntent.getIntent();
// doesn't compile only accepts Intent and not the Intentbuilder
startActivity(shareIntent);
Thats an example from my code, but if you want some reference material tap on the hyperlink for an article.
public void shareText(String text) {
String mimeType = "text/plain";
String title = "Example title";
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
.setType(mimeType)
.setText(text)
.getIntent();
if (shareIntent.resolveActivity(getPackageManager()) != null){
startActivity(shareIntent);
}
}
Blog post on ShareCompat.IntentBuilder and sharing intents
ShareCompat.IntentBuilder.from(ActivityName.this) is deprecated, use the constructor of IntentBuilder like this:
Kotlin:
ShareCompat
.IntentBuilder(this#YourActivity)
.setType("text/plain")
.setChooserTitle("Share text with: ")
.setText("Desired text to share")
.startChooser()
Java:
new ShareCompat
.IntentBuilder(YourActivity.this)
.setType("text/plain")
.setChooserTitle("Share text with: ")
.setText("Desired text to share")
.startChooser();
Funny, I just figured it out... the example given was suppose create an Intent and not an IntentBuilder object.. had to change my code to chain the object creation.
Intent i = ShareCompat.IntentBuilder.from(MyActivity.this)
.setText(message)
.setSubject(subject)
.setStream(Uri.fromFile(imageFile))
.setType("image/jpeg")
.getIntent()
.setPackage("com.google.android.apps.plus");