Android: udostępniaj zwykły tekst za pomocą intencji (we wszystkich aplikacjach do przesyłania wiadomości)

146

Próbuję udostępnić jakiś tekst, używając intencji:

Intent i = new Intent(android.content.Intent.ACTION_SEND);
i.setType("text/plain");  
i.putExtra(android.content.Intent.EXTRA_TEXT, "TEXT");

i wypaczanie za pomocą selektora:

startActivity(Intent.createChooser(sms, getResources().getString(R.string.share_using)));

to działa! ale tylko dla aplikacji e-mail.
potrzebuję ogólnego zamiaru dla wszystkich aplikacji do obsługi wiadomości: e-maile, sms, komunikatory (Whatsapp, Viber, Gmail, SMS ...) próbowałem używać android.content.Intent.ACTION_VIEW i próbowałem i.setType("vnd.android-dir/mms-sms");nic nie pomogło ...

( "vnd.android-dir/mms-sms"udostępniane tylko przez sms!)

skgskg
źródło

Odpowiedzi:

313

Użyj kodu jako:

    /*Create an ACTION_SEND Intent*/
    Intent intent = new Intent(android.content.Intent.ACTION_SEND);
    /*This will be the actual content you wish you share.*/
    String shareBody = "Here is the share content body";
    /*The type of the content is text, obviously.*/
    intent.setType("text/plain");
    /*Applying information Subject and Body.*/
    intent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.share_subject));
    intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
    /*Fire!*/
    startActivity(Intent.createChooser(intent, getString(R.string.share_using)));
Arpit Garg
źródło
6
Ale nie rozumiem, co robi różnicę? Tylko zewnętrzny ciąg ciała?
skgskg
1
nie ma różnicy. Na emulatorze otworzyła się aplikacja do obsługi wiadomości, ale na telefonie i tablecie zostałem poproszony o wybranie z listy aplikacji. Prawdopodobnie chodzi o zainstalowanie tych dodatkowych aplikacji na emulatorze.
Piyush-Ask Any Difference
Świetna odpowiedź! Czy ktoś może powiedzieć, dlaczego to nie działa, jeśli pominiesz sharingIntent.setType("text/plain");część?
NecipAllef
Jak ustawić osobny tekst tylko dla whatsup
salih kallai
1
Dodaj następujący fragment w intencji sharingIntent.setPackage ("com.whatsapp");
Arpit Garg
62

Nowym sposobem na zrobienie tego byłoby użycie ShareCompat.IntentBuilder w następujący sposób:

// Create and fire off our Intent in one fell swoop
ShareCompat.IntentBuilder
        // getActivity() or activity field if within Fragment
        .from(this) 
        // The text that will be shared
        .setText(textToShare)
        // most general text sharing MIME type
        .setType("text/plain") 
        .setStream(uriToContentThatMatchesTheArgumentOfSetType)
        /*
         * [OPTIONAL] Designate a URI to share. Your type that 
         * is set above will have to match the type of data
         * that your designating with this URI. Not sure
         * exactly what happens if you don't do that, but 
         * let's not find out.
         * 
         * For example, to share an image, you'd do the following:
         *     File imageFile = ...;
         *     Uri uriToImage = ...; // Convert the File to URI
         *     Intent shareImage = ShareCompat.IntentBuilder.from(activity)
         *       .setType("image/png")
         *       .setStream(uriToImage)
         *       .getIntent();
         */
        .setEmailTo(arrayOfStringEmailAddresses)
        .setEmailTo(singleStringEmailAddress)
        /*
         * [OPTIONAL] Designate the email recipients as an array
         * of Strings or a single String
         */ 
        .setEmailTo(arrayOfStringEmailAddresses)
        .setEmailTo(singleStringEmailAddress)
        /*
         * [OPTIONAL] Designate the email addresses that will be 
         * BCC'd on an email as an array of Strings or a single String
         */ 
        .addEmailBcc(arrayOfStringEmailAddresses)
        .addEmailBcc(singleStringEmailAddress)
        /* 
         * The title of the chooser that the system will show
         * to allow the user to select an app
         */
        .setChooserTitle(yourChooserTitle)
        .startChooser();

Jeśli masz więcej pytań dotyczących korzystania z ShareCompat, bardzo polecam ten wspaniały artykuł Iana Lake'a , rzecznika programistów Androida w Google, aby uzyskać pełniejszy opis interfejsu API. Jak zauważysz, część tego przykładu pożyczyłem z tego artykułu.

Jeśli ten artykuł nie zawiera odpowiedzi na wszystkie pytania, w witrynie Android Developers zawsze znajduje się sam Javadoc dla ShareCompat.IntentBuilder . Dodałem więcej do tego przykładu użycia API na podstawie komentarza Clemantiano.

lustig
źródło
1
Oprócz tej odpowiedzi istnieją również metody ustawiania odbiorców adresów e-mail, takie jak setEmailBcc () , setEmailCc () i setEmailTo () .
clementiano
Dziękuję za udostępnienie, ale nie działa idealnie dla mnie, czasami pojawia się ten wyjątek java.lang.IllegalArgumentException: Usługa niezarejestrowana: ActivityInfo {67f62c5 com.google.android.apps.hangouts.phone.ShareIntentActivity}
berrytchaks
32

To świetny przykład udostępniania intencji w systemie Android:

* Udostępnij intencjom w systemie Android

//Share text:

Intent intent2 = new Intent(); intent2.setAction(Intent.ACTION_SEND);
intent2.setType("text/plain");
intent2.putExtra(Intent.EXTRA_TEXT, "Your text here" );  
startActivity(Intent.createChooser(intent2, "Share via"));

//via Email:

Intent intent2 = new Intent();
intent2.setAction(Intent.ACTION_SEND);
intent2.setType("message/rfc822");
intent2.putExtra(Intent.EXTRA_EMAIL, new String[]{EMAIL1, EMAIL2});
intent2.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");
intent2.putExtra(Intent.EXTRA_TEXT, "Your text here" );  
startActivity(intent2);

//Share Files:

//Image:

boolean isPNG = (path.toLowerCase().endsWith(".png")) ? true : false;

Intent i = new Intent(Intent.ACTION_SEND);
//Set type of file
if(isPNG)
{
    i.setType("image/png");//With png image file or set "image/*" type
}
else
{
    i.setType("image/jpeg");
}

Uri imgUri = Uri.fromFile(new File(path));//Absolute Path of image
i.putExtra(Intent.EXTRA_STREAM, imgUri);//Uri of image
startActivity(Intent.createChooser(i, "Share via"));
break;

//APK:

File f = new File(path1);
if(f.exists())
{

   Intent intent2 = new Intent();
   intent2.setAction(Intent.ACTION_SEND);
   intent2.setType("application/vnd.android.package-archive");//APk file type  
   intent2.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f) );  
   startActivity(Intent.createChooser(intent2, "Share via"));
}
break;
hungtdo
źródło
9

Użyj poniższej metody, po prostu podaj temat i treść jako argumenty metody

public static void shareText(String subject,String body) {
    Intent txtIntent = new Intent(android.content.Intent.ACTION_SEND);
    txtIntent .setType("text/plain");
    txtIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
    txtIntent .putExtra(android.content.Intent.EXTRA_TEXT, body);
    startActivity(Intent.createChooser(txtIntent ,"Share"));
}
Arunendra
źródło
4

Poniżej znajduje się kod, który działa zarówno z aplikacją e-mail, jak i komunikatorami. Jeśli udostępniasz przez e-mail, zarówno temat, jak i treść są dodawane.

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");

                String shareString = Html.fromHtml("Medicine Name:" + medicine_name +
                        "<p>Store Name:" + store_name “+ "</p>" +
                        "<p>Store Address:" + store_address + "</p>")  .toString();
                                      sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Medicine Enquiry");
                sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareString);

                if (sharingIntent.resolveActivity(context.getPackageManager()) != null)
                    context.startActivity(Intent.createChooser(sharingIntent, "Share using"));
                else {
                    Toast.makeText(context, "No app found on your phone which can perform this action", Toast.LENGTH_SHORT).show();
                }
Ravi Yadav
źródło
1

Obrazy lub dane binarne:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/jpg");
Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri.toString());
startActivity(Intent.createChooser(sharingIntent, "Share image using"));

lub HTML:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<p>This is the text shared.</p>"));
startActivity(Intent.createChooser(sharingIntent,"Share using"));

źródło
0

Ten kod służy do udostępniania przez sms

     String smsBody="Sms Body";
     Intent sendIntent = new Intent(Intent.ACTION_VIEW);
     sendIntent.putExtra("sms_body", smsBody);
     sendIntent.setType("vnd.android-dir/mms-sms");
     startActivity(sendIntent);
Milon
źródło
0

100% działający kod do udostępniania Gmaila

    Intent intent = new Intent (Intent.ACTION_SEND);
    intent.setType("message/rfc822");
    intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
    intent.putExtra(Intent.EXTRA_SUBJECT, "Any subject if you want");
    intent.setPackage("com.google.android.gm");
    if (intent.resolveActivity(getPackageManager())!=null)
        startActivity(intent);
    else
        Toast.makeText(this,"Gmail App is not installed",Toast.LENGTH_SHORT).show();
Jar Droid
źródło