59

我的 android 应用程序中有一个文件列表,我希望能够获取选定的项目并通过电子邮件或任何其他共享应用程序发送它们。这是我的代码。

Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_EMAIL, getListView().getCheckedItemIds());
                    sendIntent.setType("text/plain");
                    startActivity(sendIntent);
4

10 回答 10

61

这是在android中共享文件的代码

Intent intentShareFile = new Intent(Intent.ACTION_SEND);
File fileWithinMyDir = new File(myFilePath);

if(fileWithinMyDir.exists()) {
    intentShareFile.setType("application/pdf");
    intentShareFile.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+myFilePath));

    intentShareFile.putExtra(Intent.EXTRA_SUBJECT,
                        "Sharing File...");
    intentShareFile.putExtra(Intent.EXTRA_TEXT, "Sharing File...");

    startActivity(Intent.createChooser(intentShareFile, "Share File"));
}
于 2015-02-24T11:11:59.583 回答
27
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(exportPath));

您也可以制作zip file所有文件并附加 zip 文件以在 android 中发送多个文件

于 2013-08-01T05:11:05.070 回答
14

这适用于每个文件!

private void shareFile(File file) {

    Intent intentShareFile = new Intent(Intent.ACTION_SEND);

    intentShareFile.setType(URLConnection.guessContentTypeFromName(file.getName()));
    intentShareFile.putExtra(Intent.EXTRA_STREAM,
        Uri.parse("file://"+file.getAbsolutePath()));

    //if you need
    //intentShareFile.putExtra(Intent.EXTRA_SUBJECT,"Sharing File Subject);
    //intentShareFile.putExtra(Intent.EXTRA_TEXT, "Sharing File Description");

    startActivity(Intent.createChooser(intentShareFile, "Share File"));

}

谢谢图沙尔伴侣!

于 2018-08-06T19:19:35.703 回答
12

对于那些尝试使用 Kotlin 的人来说,方法如下:

像下面这样开始意图:

 fun startFileShareIntent(filePath: String) { // pass the file path where the actual file is located.
        val shareIntent = Intent(Intent.ACTION_SEND).apply {
            type = FILE_TYPE  // "*/*" will accepts all types of files, if you want specific then change it on your need.
            flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
            flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
            putExtra(
                Intent.EXTRA_SUBJECT,
                "Sharing file from the AppName"
            )
            putExtra(
                Intent.EXTRA_TEXT,
                "Sharing file from the AppName with some description"
            )
            val fileURI = FileProvider.getUriForFile(
                context!!, context!!.packageName + ".provider",
                File(filePath)
            )
            putExtra(Intent.EXTRA_STREAM, fileURI)
        }
        startActivity(shareIntent)
    }

在应用程序标签内的清单中:

    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>

res-->xml--> provider_paths.xml下

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="files" path="." />
    <external-path name="external_files" path="."/>
</paths>
于 2020-07-16T06:01:26.220 回答
4

首先你应该定义文件提供者,见https://medium.com/@ali.dev/open-a-file-in-another-app-with-android-fileprovider-for-android-7-42c9abb198c1

该代码检查设备是否包含可以接收文件的应用程序,请参阅如何检查是否可以从某些活动中处理意图?.

fun sharePdf(file: File, context: Context) {
    val uri = getUriFromFile(file, context)

    if (uri != null) {
        val intent = Intent().apply {
            action = Intent.ACTION_SEND
            type = "application/pdf" // For PDF files.
            putExtra(Intent.EXTRA_STREAM, uri)
            putExtra(Intent.EXTRA_SUBJECT, file.name)
            putExtra(Intent.EXTRA_TEXT, file.name)
            // Grant temporary read permission to the content URI.
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        // Validate that the device can open your File.
        val activityInfo = intent.resolveActivityInfo(context.packageManager, intent.flags)
        if (activityInfo?.exported == true) {
            context.startActivity(Intent.createChooser(intent,
                "Share PDF file")
        }
    }
}

fun getUriFromFile(file: File, context: Context): Uri? =
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Uri.fromFile(file)
    } else {
        try {
            FileProvider.getUriForFile(context, context.packageName + ".provider", file)
        } catch (e: Exception) {
            throw if (e.message?.contains("ProviderInfo.loadXmlMetaData") == true) {
                Error("FileProvider is not set or doesn't have needed permissions")
            } else {
                e
            }
        }
    }
于 2019-07-22T08:14:11.283 回答
3

以下是共享或保存文本文件的示例:

private void shareFile(String filePath) {

    File f = new File(filePath);

    Intent intentShareFile = new Intent(Intent.ACTION_SEND);
    File fileWithinMyDir = new File(filePath);

    if (fileWithinMyDir.exists()) {
        intentShareFile.setType("text/*");
        intentShareFile.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + filePath));
        intentShareFile.putExtra(Intent.EXTRA_SUBJECT, "MyApp File Share: " + f.getName());
        intentShareFile.putExtra(Intent.EXTRA_TEXT, "MyApp File Share: " + f.getName());

        this.startActivity(Intent.createChooser(intentShareFile, f.getName()));
    }
}
于 2018-03-06T22:40:20.680 回答
3
File directory = new File(Environment.getExternalStorageDirectory() + File.separator + BuildConfig.APPLICATION_ID + File.separator + DIRECTORY_VIDEO);
            String fileName = mediaModel.getContentPath().substring(mediaModel.getContentPath().lastIndexOf('/') + 1, mediaModel.getContentPath().length());
            File fileWithinMyDir = new File(directory, fileName);
            if (fileWithinMyDir.exists()) {
                Uri fileUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", fileWithinMyDir);
                Intent intent = ShareCompat.IntentBuilder.from(this)
                        .setStream(fileUri) // uri from FileProvider
                        .setType("text/html")
                        .getIntent()
                        .setAction(Intent.ACTION_SEND) //Change if needed
                        .setDataAndType(fileUri, "video/*")
                        .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivity(intent);
于 2018-05-22T12:08:21.910 回答
2

使用ACTION_SEND_MULTIPLE向某人提供多个数据

intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayUri);
intent.setType("text/plain");
startActivity(intent);

是要发送的arrayUri文件的 Uri 数组列表。

于 2013-08-01T05:16:09.380 回答
1
val uriArrayList: ArrayList<Uri> = ArrayList()
GlobalScope.launch(Dispatchers.IO) {
    runCatching {
        itemsList!!.forEach {
            uriArrayList.add(
                FileProvider.getUriForFile(
                    mContext,
                    APPLICATION_ID + ".provider",
                    File(it.path)
                )
            )
        }

    }.onSuccess {
        requireActivity().runOnUiThread {
            if (uriArrayList.size > 0) {
                val intent = Intent()
                intent.action = Intent.ACTION_SEND_MULTIPLE
                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriArrayList)
                intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                intent.type = "image/*|application/pdf/*"
                startActivity(Intent.createChooser(intent, resources.getString(R.string.share)))
            }
        }
    }
        .onFailure {
            Log.e("SHARING_FAILED", it)
        }
}

首先,您必须在应用清单文件中编写提供程序代码,以便在 android 7.0 及更高版本上共享

<provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>

这里 provider_paths 是:

    <?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="/storage/emulated/0" path="."/>
    <root-path name="root" path="." />
    <files-path name="files" path="."/>
</paths>
于 2020-06-08T04:49:34.223 回答
-5

阅读这篇关于向其他应用发送内容的文章

Intent sendIntent = new Intent();

sendIntent.setAction(Intent.ACTION_SEND);

sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");

sendIntent.setType("text/plain");

startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
于 2013-08-01T05:17:51.407 回答