web-dev-qa-db-fra.com

Android - Partager sur Facebook, Twitter, Mail, etc.

Je dois développer une application qui a la fonction de partage. Je dois partager sur Facebook, Twitter, email et peut-être d'autres services.

Comment puis-je faire ceci? Il y a une bibliothèque sur le net? Pour le développement iOS, il y avait ShareKit, mais pour Android?

Merci :)

56
Andrea Mario Lufino

La réponse de Paresh Mayani est généralement correcte. Utilisez simplement une intention de diffusion pour laisser le système et toutes les autres applications choisir de quelle manière le contenu sera partagé.

Pour partager du texte, utilisez le code suivant:

String message = "Text I want to share.";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, message);

startActivity(Intent.createChooser(share, "Title of the dialog the system will open"));
78
Janusz

oui vous pouvez ... vous avez juste besoin de connaître le nom exact du paquet de l'application:

  • Facebook - "com.facebook.katana"
  • Twitter - "com.Twitter.Android"
  • Instagram - "com.instagram.Android"
  • Pinterest - "com.pinterest"

Et vous pouvez créer l'intention comme ça

Intent intent = context.getPackageManager().getLaunchIntentForPackage(application);
if (intent != null) {
     // The application exists
     Intent shareIntent = new Intent();
     shareIntent.setAction(Intent.ACTION_SEND);
     shareIntent.setPackage(application);

     shareIntent.putExtra(Android.content.Intent.EXTRA_TITLE, title);
     shareIntent.putExtra(Intent.EXTRA_TEXT, description);
     // Start the specific social application
     context.startActivity(shareIntent);
} else {
    // The application does not exist
    // Open GooglePlay or use the default system picker
}
32
Ionut Negru

Je pense que vous voulez donner le bouton Partager, en cliquant sur l’option média/site Web appropriée à partager. Sous Android, vous devez créer createChooser pour la même chose.

Partage de texte:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Android.content.Intent.EXTRA_TEXT, "This is the text that will be shared.");
startActivity(Intent.createChooser(sharingIntent,"Share using"));

Partage d'objets binaires (images, vidéos, etc.)

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(path);

sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));

Pour info, le code ci-dessus sont référés à partir de partage de contenu dans Android en utilisant ACTION_SEND Intent)

27
Paresh Mayani

Utilisez ceci

Facebook - "com.facebook.katana"
Twitter - "com.Twitter.Android"
Instagram - "com.instagram.Android"
Pinterest - "com.pinterest"



SharingToSocialMedia("com.facebook.katana")


public void SharingToSocialMedia(String application) {

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_STREAM, bmpUri);

    boolean installed = checkAppInstall(application);
    if (installed) {
        intent.setPackage(application);
        startActivity(intent);
    } else {
        Toast.makeText(getApplicationContext(),
                "Installed application first", Toast.LENGTH_LONG).show();
    }

}


 private boolean checkAppInstall(String uri) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
    }

    return false;
}
6
Sunil Chaudhary

ACTION_SEND fonctionnera correctement pour tous et le corps du texte sera affiché au mur dans Twitter, G mail .. mais il échouera pour la page Face Book ... Son bogue est connu dans Facebook Android = SDK .. mais ils ne l'ont toujours pas corrigé

3
RAJESH

Je pense que le code suivant va aider ....

public void btnShareClick(View v) {
    // shareBtnFlag = 1;
    Dialog d = new Dialog(DrawAppActivity.this);
    d.requestWindowFeature(d.getWindow().FEATURE_NO_TITLE);
    d.setCancelable(true);

    d.setContentView(R.layout.sharing);

    final Button btnFacebook = (Button) d.findViewById(R.id.btnFacebook);
    final Button btnEmail = (Button) d.findViewById(R.id.btnEmail);

    btnEmail.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            if (!btnEmail.isSelected()) {
                btnEmail.setSelected(true);
            } else {
                btnEmail.setSelected(false);
            }
            saveBtnFlag = 1;
            // Check if email id is available-------------
            AccountManager manager = AccountManager
                    .get(DrawAppActivity.this);
            Account[] accounts = manager.getAccountsByType("com.google");
            Account account = CommonFunctions.getAccount(manager);
            if (account.name != null) {
                emailSendingTask eTask = new emailSendingTask();
                eTask.execute();
                if (CommonFunctions.createDirIfNotExists(getResources()
                        .getString(R.string.path)))

                {
                    tempImageSaving(
                            getResources().getString(R.string.path),
                            getCurrentImage());
                }

                Intent sendIntent;
                sendIntent = new Intent(Intent.ACTION_SEND);
                sendIntent.setType("application/octet-stream");
                sendIntent.setType("image/jpeg");
                sendIntent.putExtra(Intent.EXTRA_EMAIL,
                        new String[] { account.name });
                sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Drawing App");
                sendIntent.putExtra(Intent.EXTRA_TEXT, "Check This Image");
                sendIntent.putExtra(Intent.EXTRA_STREAM,
                        Uri.parse("file://" + tempPath.getPath()));

                List<ResolveInfo> list = getPackageManager()
                        .queryIntentActivities(sendIntent,
                                PackageManager.MATCH_DEFAULT_ONLY);

                if (list.size() != 0) {

                    startActivity(Intent.createChooser(sendIntent,
                            "Send Email Using:"));

                }

                else {
                    AlertDialog.Builder confirm = new AlertDialog.Builder(
                            DrawAppActivity.this);
                    confirm.setTitle(R.string.app_name);
                    confirm.setMessage("No Email Sending App Available");
                    confirm.setPositiveButton("Set Account",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    dialog.dismiss();
                                }
                            });
                    confirm.show();
                }
            } else {
                AlertDialog.Builder confirm = new AlertDialog.Builder(
                        DrawAppActivity.this);
                confirm.setTitle(R.string.app_name);
                confirm.setMessage("No Email Account Available!");
                confirm.setPositiveButton("Set Account",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                Intent i = new Intent(
                                        Settings.ACTION_SYNC_SETTINGS);
                                startActivity(i);
                                dialog.dismiss();
                            }
                        });
                confirm.setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {

                                dialog.dismiss();
                            }
                        });
                confirm.show();
            }
        }

    });

    btnFacebook.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            if (!btnFacebook.isSelected()) {
                btnFacebook.setSelected(true);
            } else {
                btnFacebook.setSelected(false);
            }
            saveBtnFlag = 1;
            // if (connection.isInternetOn()) {

            if (Android.os.Environment.getExternalStorageState().equals(
                    Android.os.Environment.MEDIA_MOUNTED)) {
                getCurrentImage();
                Intent i = new Intent(DrawAppActivity.this,
                        FaceBookAuthentication.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivity(i);
            }

            else {
                ShowAlertMessage.showDialog(DrawAppActivity.this,
                        R.string.app_name, R.string.Sd_card,
                        R.string.button_retry);
            }
        }
    });
    d.show();

}

public void tempImageSaving(String tmpPath, byte[] image) {
    Random Rand = new Random();

    tempfile = new File(Environment.getExternalStorageDirectory(), tmpPath);
    if (!tempfile.exists()) {
        tempfile.mkdirs();
    }

    tempPath = new File(tempfile.getPath(), "DrawApp" + Rand.nextInt()
            + ".jpg");
    try {
        FileOutputStream fos1 = new FileOutputStream(tempPath.getPath());
        fos1.write(image);

        fos1.flush();
        fos1.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    sendBroadcast(new Intent(
            Intent.ACTION_MEDIA_MOUNTED,
            Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}

public byte[] getCurrentImage() {

    Bitmap b = drawingSurface.getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    b.compress(Bitmap.CompressFormat.PNG, 100, stream);

    byteArray = stream.toByteArray();

    return byteArray;
}

private class emailSendingTask extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(DrawAppActivity.this);
        progressDialog.setTitle(R.string.app_name);
        progressDialog.setMessage("Saving..Please Wait..");
        // progressDialog.setIcon(R.drawable.icon);
        progressDialog.show();

    }

    @Override
    protected String doInBackground(String... urls) {

        String response = "";
        try {

            if (Android.os.Environment.getExternalStorageState().equals(
                    Android.os.Environment.MEDIA_MOUNTED)) {

                response = "Yes";

            } else {
                ShowAlertMessage.showDialog(DrawAppActivity.this,
                        R.string.app_name, R.string.Sd_card,
                        R.string.button_retry);

            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return response;

    }

    @Override
    protected void onPostExecute(String result) {

        if (result.contains("Yes")) {
            getCurrentImage();

        }
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://"
                        + Environment.getExternalStorageDirectory())));

        progressDialog.cancel();
    }
}

private class ImageSavingTask extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(DrawAppActivity.this);
        progressDialog.setTitle(R.string.app_name);
        progressDialog.setMessage("Saving..Please Wait..");
        // progressDialog.setIcon(R.drawable.icon);
        progressDialog.show();

    }

    @Override
    protected String doInBackground(String... urls) {

        String response = "";
        try {

            if (Android.os.Environment.getExternalStorageState().equals(
                    Android.os.Environment.MEDIA_MOUNTED)) {

                response = "Yes";

            } else {
                ShowAlertMessage.showDialog(DrawAppActivity.this,
                        R.string.app_name, R.string.Sd_card,
                        R.string.button_retry);

            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return response;

    }

    @Override
    protected void onPostExecute(String result) {

        if (result.contains("Yes")) {
            getCurrentImage();

            if (CommonFunctions.createDirIfNotExists(getResources()
                    .getString(R.string.path)))

            {
                saveImageInSdCard(getResources().getString(R.string.path),
                        getCurrentImage());
            }
        }
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://"
                        + Environment.getExternalStorageDirectory())));

        progressDialog.cancel();
    }
}

Pour une application facebook, utilisez le SDK facebook

1
Robo

Le ACTION_SEND Ne vous donnera que des options pour l'envoi en utilisant GMail, YahooMail ... etc (Toute application installée sur votre téléphone pouvant exécuter ACTION_SEND). Si vous souhaitez partager sur Facebook ou Twitter, vous devez placer des boutons personnalisés pour chacun et utiliser leur propre SDK, tel que SDK Facebook ou Twitter4J .

1
Ovidiu Latcu

CA aidera

1- Première définition de ces constantes

 public static final String FACEBOOK_PACKAGE_NAME = "com.facebook.katana";
    public static final String Twitter_PACKAGE_NAME = "com.Twitter.Android";
    public static final String INSTAGRAM_PACKAGE_NAME = "com.instagram.Android";
    public static final String PINTEREST_PACKAGE_NAME = "com.pinterest";
    public static final String WHATS_PACKAGE_NAME =  "com.whatsapp";

2- Deuxième utilisation Cette méthode

 public static void shareAppWithSocial(Context context, String application, String title, 
 String description) {

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setPackage(application);

        intent.putExtra(Android.content.Intent.EXTRA_TITLE, title);
        intent.putExtra(Intent.EXTRA_TEXT, description);
        intent.setType("text/plain");

        try {
            // Start the specific social application
            context.startActivity(intent);
        } catch (Android.content.ActivityNotFoundException ex) {
            // The application does not exist
            Toast.makeText(context, "app have not been installed.", Toast.LENGTH_SHORT).show();
        }


    }
0
Islam Alshnawey

Cela vous permettra de partager votre application sur whats app etc:

try
            { Intent i = new Intent(Intent.ACTION_SEND);  
              i.setType("text/plain");
              i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
              String sAux = "\nLet me recommend you this application\n\n";
              sAux = sAux + "https://play.google.com/store/apps/details?id=Orion.Soft \n\n";
              i.putExtra(Intent.EXTRA_TEXT, sAux);  
              startActivity(Intent.createChooser(i, "choose one"));
0
Farhad Ullah
sharingIntent = new Intent(Android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Android.content.Intent.EXTRA_SUBJECT,"your subject" );
sharingIntent.putExtra(Android.content.Intent.EXTRA_TEXT, "your text");
startActivity(Intent.createChooser(sharingIntent, ""));
0
Manju S B

Create Choose Editable

Intent sendIntent = new Intent(Intent.ACTION_SEND);
            sendIntent.setType("text/plain");
            sendIntent.putExtra(Intent.EXTRA_SUBJECT, "My application name");
            String sAux = "\nLet me recommend you this application\n\n";
            sAux = sAux + "https://play.google.com/store/apps/details?id=the.package.id \n\n";
            sendIntent.putExtra(Intent.EXTRA_TEXT, sAux);
            startActivity(Intent.createChooser(sendIntent, "choose one"));

=============================================== ============

Create Choose Default

            Intent sendIntent = new Intent(Intent.ACTION_SEND);
            sendIntent.setType("text/plain");
            sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
            startActivity(sendIntent);

=============================================== ===============

envoi multipièces

Envoyer plusieurs éléments de contenu

Pour partager plusieurs éléments de contenu, utilisez l'action ACTION_SEND_MULTIPLE avec une liste d'URI pointant vers le contenu. Le type MIME varie en fonction de la composition du contenu que vous partagez. Par exemple, si vous partagez 3 images JPEG, le type est toujours "image/jpeg". Pour un mélange de types d’images, cela devrait être "image/*" pour correspondre à une activité qui gère tout type d’image. Vous ne devriez utiliser que "*/*" si vous partagez une grande variété de types. Comme indiqué précédemment, il appartient à l’application destinataire d’analyser et de traiter vos données. Voici un exemple:

ArrayList<Uri> imageUris = new ArrayList<Uri>();
imageUris.add(imageUri1); // Add your image URIs here
imageUris.add(imageUri2);

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share images to.."));

=============================================== ==============

Partager avec Facebook

    ShareLinkContent shareLinkContent = new ShareLinkContent.Builder()
            .setQuote("Application of social rating share with your friend")
            .setContentUrl(Uri.parse("https://google.com"))
            .build();
    if (ShareDialog.canShow(ShareLinkContent.class)) {
        sd.show(shareLinkContent);
    }

=============================================== ============

Partager avec SMS

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.putExtra("Body", "Application of social rating share with your friend");
    intent.setType("vnd.Android-dir/mms-sms");
    startActivity(intent);

=============================================== ============

Partager avec mail

    Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", "", null));
    emailIntent.putExtra(Intent.EXTRA_EMAIL, "Address");
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Application of social rating share with your friend");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "Body");
    startActivity(Intent.createChooser(emailIntent, "Send Email..."));

=============================================== ===========

Partager avec WhatsApp

    Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
    whatsappIntent.setType("text/plain");
    whatsappIntent.setPackage("com.whatsapp");
    whatsappIntent.putExtra(Intent.EXTRA_TEXT, "Application of social rating share with your friend");
    try {
        Objects.requireNonNull(getActivity()).startActivity(whatsappIntent);
    } catch (Android.content.ActivityNotFoundException ex) {
        Toast.makeText(getActivity(), "WhatsApp have not been installed.", Toast.LENGTH_SHORT).show();
    }
0
Prince
String message = "This is testing."
Intent shareText = new Intent(Intent.ACTION_SEND);
shareText .setType("text/plain");
shareText .putExtra(Intent.EXTRA_TEXT, message);

startActivity(Intent.createChooser(shareText , "Title of the dialog the system will open"));
0
Avanish Singh