我无法理解共享内部txt文件。 (不是外在的!) 我注意到默认情况下这是不可能的,但我写了我的ContetProvider类
<提供商 机器人:名称=" MYPROVIDER" 机器人:当局=" com.mobilemerit.usbhost" 机器人:导出="真" />
public class myProvider extends ContentProvider {
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
File cacheDir = getContext().getCacheDir();
File privateFile = new File(cacheDir, "file.txt");
return ParcelFileDescriptor.open(privateFile, ParcelFileDescriptor.MODE_READ_WRITE);
}
然后
try {
InputStream is = c.getAssets().open("file.txt");
File cacheDir = c.getCacheDir();
File outFile = new File(cacheDir, "file.txt");
OutputStream os = new FileOutputStream(outFile.getAbsolutePath());
String content = "Hello Java Code Geeks";
byte[] buff = new byte[1024];
int len;
while ((len = is.read(buff)) > 0) {
os.write(buff, 0, len);
}
os.flush();
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace(); // TODO: should close streams properly here
}
Uri uri = Uri.parse("content://com.mobilemerit.usbhost/file.txt");
InputStream is = null;
StringBuilder result = new StringBuilder();
try {
is = c.getContentResolver().openInputStream(uri);
BufferedReader r = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = r.readLine()) != null) {
result.append(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try { if (is != null) is.close(); } catch (IOException e) { }
}
但是我写的新共享意图附加了一个不可能发送的file.txt。它似乎是附件"它无效"。我错了什么?我不能使用外部存储器
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://com.mobilemerit.usbhost/file.txt"));
startActivity(Intent.createChooser(intent, ""));
答案 0 :(得分:0)
如果唯一的目的是共享/通过电子邮件发送内部文件,则无需创建内容提供商。您可以使用setReadable
(1)方法让每个进程访问该文件。以下示例。
//open existing file
File emailFile= new File( getFilesDir(), "sampleFile.txt" );
//allow read for others
emailFile.setReadable( true, false );
Uri emailFileUri = Uri.fromFile( emailFile );
Intent intentToEmailFile = new Intent( Intent.ACTION_SEND );
intentToEmailFile.setType( "message/rfc822" );
intentToEmailFile.putExtra(android.content.Intent.EXTRA_STREAM, emailFileUri );
Intent chooserIntent = Intent.createChooser( intentToEmailFile, "Send email" );
startActivity( chooserIntent );
这会将内部文件正确附加到您选择的电子邮件客户端。