1

我无法理解共享内部 txt 文件。(不是外部的!)我注意到默认情况下这是不可能的,但我写了我的 ContetProvider 类

< 提供者 android:name="myProvider" android:authorities="com.mobilemerit.usbhost" android:exported="true" />

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, ""));
4

1 回答 1

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 );

这会将内部文件正确附加到您选择的电子邮件客户端。

于 2015-05-27T17:49:02.727 回答