2014-08-27 3 views
0

나는 정확하게 이메일에 이미지를 첨부하고 전송 다음과 같은 코드가 있습니다열기 공유 이미지

Intent sharingIntent = new Intent(Intent.ACTION_SEND); 

sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
// Set tht type to image/* and add the extra text field for the message to send 
sharingIntent.setType(Application2.instance().getResString(R.string.share_intent_type_text_image)); 
sharingIntent.putExtra(Intent.EXTRA_TEXT, String.format(Application2.instance().getResString(R.string.share_intent_body_question), question.question)); 

if (destFile != null) 
{ 
    Uri uri = Uri.fromFile(destFile); 
    sharingIntent.putExtra(Intent.EXTRA_STREAM, uri); 

    ((ActivityMain) getActivity()).startActivity(Intent.createChooser(sharingIntent, "Share via")); 
} 

R.string.share_intent_type_text_image는 "이미지/PNG"

destFile로 정의되어 이미지가 잡고있다 응용 프로그램의 외부 캐시 디렉토리에서 (((ActivityMain) getActivity()).getExternalCacheDir()

그러나 Gmail에서 파일을 열려고하면 Info -이 첨부 파일을 열어 볼 수있는 응용 프로그램이 없음 대화 상자가 나타납니다. 내 PC를 통해 파일을 다운로드했고 확장명은 .File로 나타납니다. 페인트와 다른 이미지 뷰어로 열 수 있습니다.

누구나 전에 경험할 수 있습니까?

+0

'destFile'의 가치는 무엇입니까? – CommonsWare

+0

https://developer.android.com/reference/android/support/v4/content/FileProvider.html – Simon

+0

@Simon을 살펴 보시고 테스트 해보고 결과를 게시하겠습니다. 이게 정확히 내가 필요로하는 것 같아! 그냥 메모, 이미지는 다른 많은 애플 리케이션을 위해 잘 작동합니다. 또한'destFile'에 대한 설명을 추가했습니다. –

답변

1

FileProvider 문제를 고려하고, 또한, 나는 ContentProvider 솔루션 가서는 치료를 작동합니다. 기본적으로 내부 캐시를 아무런 문제없이 사용할 수 있지만 공유하려는 임시 파일을 참조하는 데 사용할 수있는 URI가 타사 앱에도 제공됩니다. 내부 캐시를 사용하므로 불필요한 WRITE_EXTERNAL_STORAGE 요청할 수 없습니다.

추가 된 최대 캐시 크기 제한 (예 : checkSize()에서 클래스 끝까지 모든 것을 삭제하여 클래스에서 제거 할 수 있습니다. 예를 들어, 공유 후 모든 파일을 직접 삭제할 수 있는지 장치에 남아 있지 않은 경우)는 각 호출시 누적 된 최대 크기를 확인하고 필요한 경우 캐시 절반을 지우고 (가장 오래된 파일 삭제) 작동합니다.새 파일 및

TemporaryFile.getPublicUri(file) 

을 만들 때마다 당신이에 공개 열린 우리당을 얻을 원할 때마다 간단 할 수없는 그것을 사용

public class TemporaryFile extends ContentProvider { 
    private static final long MAX_SIZE = 512 * 1024; 
    // commented out on purpose so that you don't forget to rewrite it... 
    // public static final String AUTHORITY = "com.example.tempfile"; 

    private UriMatcher uriMatcher; 

    @Override 
    public boolean onCreate() { 
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); 
    uriMatcher.addURI(AUTHORITY, "*", 1); 
    return true; 
    } 

    @Override 
    public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { 
    if (uriMatcher.match(uri) == 1) { 
     final String file = getContext().getCacheDir() + File.separator + uri.getLastPathSegment(); 
     return ParcelFileDescriptor.open(new File(file), ParcelFileDescriptor.MODE_READ_ONLY); 
    } 
    else 
     throw new FileNotFoundException(uri.toString()); 
    } 

    @Override 
    public int update (Uri uri, ContentValues values, String selection, String[] selectionArgs) { 
    return 0; 
    } 

    @Override 
    public int delete (Uri uri, String selection, String[] selectionArgs) { 
    return 0; 
    } 

    @Override 
    public Uri insert(Uri uri, ContentValues values) { 
    return null; 
    } 

    @Override 
    public String getType(Uri uri) { 
    return null; 
    } 

    @Override 
    public Cursor query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { 
    return null; 
    } 

    public static File getFile(Context context, String prefix, String extension) throws IOException { 
    checkSize(context); 
    File file = File.createTempFile(prefix, extension, context.getCacheDir()); 
    file.setReadable(true); 
    file.deleteOnExit(); 
    return file; 
    } 

    public static Uri getPublicUri(File file) { 
    return Uri.withAppendedPath(Uri.parse("content://" + AUTHORITY), file.getName()); 
    } 

    public static void checkSize(Context context) throws IOException { 
    File dir = context.getCacheDir(); 
    if (getDirSize(dir) > MAX_SIZE) 
     cleanDir(dir, MAX_SIZE/2); 
    } 

    private static long getDirSize(File dir) { 
    long size = 0; 
    for (File file : dir.listFiles()) 
     if (file.isFile()) 
     size += file.length(); 
    return size; 
    } 

    private static void cleanDir(File dir, long atLeast) { 
    long deleted = 0; 

    File[] files = dir.listFiles(); 
    Arrays.sort(files, new Comparator<File>() { 
     public int compare(File f1, File f2) { 
     return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified()); 
     } 
    }); 

    for (File file : files) { 
     deleted += file.length(); 
     file.delete(); 
     if (deleted >= atLeast) 
     break; 
    } 
    } 
} 

, 단지

File file = TemporaryFile.getFile(this, "prefix", ".extension"); 

전화 파일, 예. 데이터 또는 Intent.EXTRA_STREAM이라는 의도로 전달합니다.

공급자 인, 필요한 매니페스트 항목을 추가하는 것을 잊지 마세요 중 하나

<provider 
    android:name=".TemporaryFile" 
    android:authorities="com.example.tempfile" 
    android:exported="true" 
    tools:ignore="ExportedContentProvider" > 
</provider> 
0

이 작동하지만 외부 저장 용량과 관련 권한이 필요합니다. 앱을 다운로드 할 때 앱이 데이터를 읽거나 쓸 수 있어야한다는 요청이 표시되어 사용자를 멀게 할 수 있습니다. 그것이 중요하다면 필자의 첫 번째 게시물에서 제안 된 Simon으로 FileProvider를 사용하십시오.

유용한 링크 :
https://developer.android.com/reference/android/support/v4/content/FileProvider.html

나는 사이먼은 아무 소용이 내 최초의 게시물에 제안 파일 공급자를 사용하려고했습니다. 이에서
How to use support FileProvider for sharing content to other apps?

:에서 https://developer.android.com/reference/android/support/v4/content/FileProvider.html
뿐만 아니라 다른 스레드 : 난에서 가이드를 수행 한 후에도 문제를 추적 할 수 없습니다

final ProviderInfo info = context.getPackageManager() 
      .resolveContentProvider(authority, PackageManager.GET_META_DATA); 

: 나는 다음 줄에 NullPointerException이받은 요점 나는 사용되는 이미지에 대해 설정된 파일 유형이 없다는 것을 깨달았습니다. 파일에 .png를 추가하기 만하면 Gmail에서뿐만 아니라 이미 작동했던 이전 앱에서도 첨부 파일이 올바르게 작동합니다.

내부 파일을 공유하는 방법에 대해 궁금한 사람이 있으면 다음 코드를 제공했습니다. 그것은 완전하지 않으며 오류를 완벽하게 처리하지는 않지만 시작으로 누군가에게 유용 할 수 있습니다. 내가 수집 한 임시 파일의 최대 캐시 크기를 구현하고 싶었 기 때문에

// Copy image file to external memory and send with the intent 
File srcFile = getImage(); 
File destDir = new File(((ActivityMain) getActivity()).getExternalCacheDir(), 
     Application2.instance().getResString(R.string.temporary_external_image_path)); 
if(!destDir.exists()) 
{ 
    destDir.mkdirs(); 
} 

if(destDir != null && srcFile != null) 
{ 
    File destFile = new File(destDir, srcFile.getName()); 

    if (!destFile.exists()) 
    { 
     try 
     { 
      Application2.instance().copy(srcFile, destFile); 
     } 
     catch (IOException e) 
     { 
      if (BuildConfig.DEBUG) Log.e("Failed to copy file '" + srcFile.getName() + "'"); 
     } 
    } 

    if (destFile != null) 
    { 
     Uri uri = Uri.fromFile(destFile); 
     sharingIntent.putExtra(Intent.EXTRA_STREAM, uri); 

     ((ActivityMain) getActivity()).startActivity(Intent.createChooser(sharingIntent, "Share via")); 
    } 
}