web-dev-qa-db-fra.com

Comment puis-je partager plusieurs fichiers via une intention?

Voici mon code, mais il s’agit d’une solution à fichier unique.

Puis-je partager plusieurs fichiers et uploads comme je le fais pour des fichiers uniques ci-dessous?

Button btn = (Button)findViewById(R.id.hello);

    btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_SEND);

                String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/pic.png";
                File file = new File(path);

                MimeTypeMap type = MimeTypeMap.getSingleton();
                intent.setType(type.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path)));

                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
                intent.putExtra(Intent.EXTRA_TEXT, "1111"); 
                startActivity(intent);
            }
        }); 
26
osmund sadler

Oui, mais vous devrez utiliser Intent.ACTION_SEND_MULTIPLE au lieu de Intent.ACTION_SEND.

Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putExtra(Intent.EXTRA_SUBJECT, "Here are some files.");
intent.setType("image/jpeg"); /* This example is sharing jpeg images. */

ArrayList<Uri> files = new ArrayList<Uri>();

for(String path : filesToSend /* List of the files you want to send */) {
    File file = new File(path);
    Uri uri = Uri.fromFile(file);
    files.add(uri);
}

intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
startActivity(intent);

Cela pourrait certainement être simplifié, mais j'ai laissé quelques lignes afin que vous puissiez décomposer chaque étape nécessaire.

UPDATE: à partir de l'API 24, le partage des URI de fichiers provoque une exception FileUriExposedException. Pour remédier à cela, vous pouvez basculer votre compileSdkVersion à 23 ou moins, ou vous pouvez utiliser les URI de contenu avec FileProvider .

UPDATE (à la mise à jour): Google a récemment annoncé que de nouvelles applications et mises à jour d'applications seraient nécessaires pour cibler l'une des dernières versions d'Android en vue de son lancement sur le Play Store. Cela dit, le ciblage de l'API 23 ou inférieure n'est plus une option valide si vous envisagez de publier l'application dans le magasin. Vous devez choisir la route FileProvider.

75
Michael Celey

Voici une petite version améliorée improvisée par la solution de MCeley. Ceci pourrait être utilisé pour envoyer la liste de fichiers hétérogène (comme une image, un document et une vidéo en même temps), par exemple pour télécharger des documents téléchargés, des images en même temps.

public static void shareMultiple(List<File> files, Context context){

    ArrayList<Uri> uris = new ArrayList<>();
    for(File file: files){
        uris.add(Uri.fromFile(file));
    }
    final Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
    intent.setType("*/*");
    intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
    context.startActivity(Intent.createChooser(intent, context.getString(R.string.ids_msg_share)));
}
4
A.B.
/* 
 manifest file outside the applicationTag write these permissions
     <uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission Android:name="Android.permission.READ_EXTERNAL_STORAGE" /> */

    File pictures = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                            //Get a top-level public external storage directory for placing files of a particular type. 
                            // This is where the user will typically place and manage their own files, 
                            // so you should be careful about what you put here to ensure you don't 
                            // erase their files or get in the way of their own organization...
                            // pulled from Standard directory in which to place pictures that are available to the user to the File object

                            String[] listOfPictures = pictures.list();
                            //Returns an array of strings with the file names in the directory represented by this file. The result is null if this file is not a directory.

                            Uri uri=null; 
                            ArrayList<Uri> arrayList = new ArrayList<>();
                            if (listOfPictures!=null) {
                                for (String name : listOfPictures) {
                                    uri = Uri.parse("file://" + pictures.toString() + "/" + name );
                                    arrayList.add(uri);
                                }
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                                intent.putExtra(Intent.EXTRA_STREAM, arrayList);
                                //A content: URI holding a stream of data associated with the Intent, used with ACTION_SEND to supply the data being sent.
                                intent.setType("image/*"); //any kind of images can support.
                                chooser = Intent.createChooser(intent, "Send Multiple Images");//choosers title
                                 startActivity(chooser);
                            }
1
Emre Kilinc Arslan