암시적 인텐트로 데이터 공유하기(ShareCompat) - 안드로이드 개발 패턴 시즌2 에피소드6


출처: 안드로이드 개발자 유튜브 채널

  암시적 인텐트를 사용해 데이터를 공유해야 할 경우 데이터 타입, 파일의 수 등을 고려해야한다. 엑스트라로 인텐트에 데이터를 저장해서 데이터를 공유할 수도 있다. 하지만 언급한 여러 고려사항을 처리 하려면 복수의 코드라인을 작성해야한다.



  암시적 인텐트를 통해 데이터를 쉽게 공유할 수 있는 헬퍼 클래스인 ShareCompat를 사용하면 데이터 공유를 좀 더 쉽게 할 수 있다. ShareCompat과 내부 클래스인 IntentBuilder를 사용하면 여러 고려사항을 빠르게 처리할 수 있다.


  • 텍스트 공유하기(MIME type: text/plain)

Intent shareIntent = ShareCompat.IntentBuilder
        .from(activity)
        .setType("text/plain")
        .setText("shareText")
        .getIntent();
if (shareIntent.resolveActivity(getPackageManager()) != null){
    startActivity(shareIntent);}

  • HTML text 공유하기(MIME type: text/html)
Intent shareIntent = ShareCompat.IntentBuilder
        .from(activity)
        .setType("text/html")
        .setHtmlText(shareHTMLText)
        .setSubject("Subject")
        .addEmailTo("email address")
        .getIntent();if (intent.resolveActivity(getPackageManager()) != null){
    startActivity(shareIntent);}

  • Image 공유하기(MIME type: image/png)
File imageFile = ...;

Intent shareIntent = ShareCompat.IntentBuilder
        .from(activity)
        .setType("image/png")
        .setStream(uriToImage)
        .getIntent();if (intent.resolveActivity(getPackageManager()) != null){
    startActivity(shareIntent);}



데이터 받기


데이터를 받을때는 ShareCompat의 IntentReader를 사용한다. 데이터를 받는 어플리케이션의 onCreate()에 아래의 예와 유사한 코드로 데이터를 받는다.

ShareCompat.IntentReader intentReader = 
        ShareCompat.IntentReader.from(this);

if (intentReader.isShareIntent()){
    String[] emailTo = intentReader.getEmailTo();    String subject = intentReader.getSubject();    String text = intentReader.getHtmlText(); }



파일과 이미지를 저장소 허가없이 공유하기

파일, 이미지를 공유할 때 URI를 파일 경로를 저장하여 사용할 경우 READ_STORAGE퍼미션을 요구하게된다. 퍼미션 없이 파일을 공유하려면 FileProvider를 사용하면된다. FileProvider는 URI를 이용하면서 파일과 이미지를 저장소 허가 없이 공유할 수 있게 해주기 때문이다.(Uri based Permission)


[보내는 측]

File imageFile = ...;

Uri uriToImage = FileProvider.getUriForFile(context, FILES_AUTHORITY, newFile);

Intent shareIntent = ShareCompat.IntentBuilder
        .from(activity)
        .setType(getContentResolver().getType(uriToImage))
        .setStream(uriToImage)
        .getIntent();

shareIntent.setData(uriToImage);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);



[받는 측 onCreate()]

Uri uri = ShareCompat.IntentReader.from(activity).getStream();
Bitmap bitmap = null;
try {
    // Works with content://, file://, or android.resource:// URIs
    InputStream inputStream = 
      getContentResolver().openInputStream(uri);
    bitmap = BitmapFactory.decodeStream(inputStream);
} catch(FileNotFoundException e) {
  // Inform the user that things have gone horribly wrong
}














댓글

이 블로그의 인기 게시물

API 요청 URL(URI) 만들기(조합하기) -Uri.Builder사용하기-

TextView에 글자를 넣어주는 방법(setText, append)

텍스트 뷰의 배경을 원형 이미지로 지정하고, 배경 색상 채우기(안드로이드)