我正在尝试创建一个临时文件并共享它。所以我创建了这个类:
public class GenerateFile {
public static File writeToFile(Context mcoContext, String sBody) {
String fileName = "LOG FILE_" + String.valueOf(System.currentTimeMillis()) +".txt";
File file = new File(mcoContext.getCacheDir(), fileName);
try{
FileWriter writer = new FileWriter(file);
writer.append(sBody);
writer.flush();
writer.close();
return file;
}catch (Exception e){
Toast.makeText(mcoContext, "File write failed: " + e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
生成一个文件,之后我将在这里分享:
String logContent = "123";
File filePath = new File(file.getAbsolutePath(), "external_files");
filePath.mkdir();
Uri uri = FileProvider.getUriForFile(StatusActivity.this, getPackageName(), filePath);
Intent intent = ShareCompat.IntentBuilder.from(StatusActivity.this)
.setStream(uri) // uri from FileProvider
.setType("text/html")
.getIntent()
.setAction(Intent.ACTION_VIEW) //Change if needed
.setDataAndType(uri, "text/*")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
在清单中已经有这个权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="com.sec.android.provider.badge.permission.WRITE"/>
<uses-permission android:name="com.sec.android.provider.badge.permission.READ"/>
和提供者声明
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="android.getqardio.com.gmslocationtest"
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>
<files-path
name="share"
path="external_files"/>
</paths>
但是当我尝试通过邮件或电报“无法附加文件”或“不支持的附件”共享它时,它会生成消息。在我看来,该文件还没有创建。