1

파일을 내부 저장소에 저장합니다.콘텐츠 제공자가있는 내부 저장소의 Android Intent.ACTION_SEND

Uri notificationUri = Uri.parse("content://com.package.example/file.txt"); 
    Intent shareIntent = new Intent(Intent.ACTION_SEND); 
    shareIntent.putExtra(Intent.EXTRA_STREAM, notificationUri); 
    shareIntent.setType("text/plain"); 
    context.startActivity(Intent.createChooser(shareIntent, context.getResources().getText(R.string.chooser))); 

선택된 응용 프로그램은 이제 개인 파일에 대한 액세스를 필요 :

FileOutputStream outputStream; 
    String filename = "file.txt"; 

    File cacheDir = context.getCacheDir(); 
    File outFile = new File(cacheDir, filename); 
    outputStream = new FileOutputStream(outFile.getAbsolutePath()); 
    outputStream.write(myString.getBytes()); 
    outputStream.flush(); 
    outputStream.close(); 

가 그럼이 파일을 공유 할 "shareIntent"를 만드는 오전 : 그것은 개체에 대한 몇 가지 정보 만 .txt 파일입니다 그래서 나는 콘텐츠 제공자를 만들었다.

@Override 
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { 
    File privateFile = new File(getContext().getCacheDir(), uri.getPath()); 
    return ParcelFileDescriptor.open(privateFile, ParcelFileDescriptor.MODE_READ_ONLY); 
} 

매니페스트 : 난 그냥 openFile 방법을 변경

<provider 
     android:name=".ShareContentProvider" 
     android:authorities="com.package.example" 
     android:grantUriPermissions="true" 
     android:exported="true"> 
    </provider> 

단지 0 바이트를 가지고 있기 때문에이 파일을 첨부 할 수 있다고, 그것이 말하는 파일을 공유 메일 앱을 여는. 블루투스를 통해 공유도 실패했습니다. 하지만 콘텐츠 공급자의 privateFile을 읽을 수 있으므로 콘텐츠가 존재합니다. 문제가 무엇입니까?

+0

사용자 정의 ContentProvider에서'query()'메소드가 호출됩니까? – pskink

+0

예가 openFile 전에 3 번 호출됩니다. 첫 번째 인수는 항상 : content : //com.package.example/file.txt – L3n95

+2

이고 투영 열은 _display_name 및 _size입니까? BTW 왜 'android.support.v4.content.FileProvider'을 사용하지 않으시겠습니까? – pskink

답변

4

고마워요. FileProvider는 완벽하게 작동 :

Gradle을 의존성 :

compile 'com.android.support:support-v4:25.0.0'

매니페스트 : XML 폴더에

<provider 
     android:name="android.support.v4.content.FileProvider" 
     android:authorities="com.package.example" 
     android:exported="false" 
     android:grantUriPermissions="true"> 
     <meta-data 
      android:name="android.support.FILE_PROVIDER_PATHS" 
      android:resource="@xml/file_paths" /> 
    </provider> 

file_paths.xml :

<?xml version="1.0" encoding="utf-8"?> 
<paths xmlns:android="http://schemas.android.com/apk/res/android"> 
    <cache-path name="cache" path="/" /> 
</paths> 

공유 의도 :

0123을
File file = new File(context.getCacheDir(), filename); 

    Uri contentUri = FileProvider.getUriForFile(context, "com.package.example", file); 

    Intent shareIntent = new Intent(Intent.ACTION_SEND); 
    shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri); 
    shareIntent.setType("text/plain"); 
    context.startActivity(Intent.createChooser(shareIntent, context.getResources().getText(R.string.chooser))); 
+0

또한 이것을 의도에 추가해야 할 수도 있습니다. shareIntent.setFlags (Intent.FLAG_GRANT_READ_URI_PERMISSION); –