Programing

Android에서 이미지를 공유하기 위해 "Share image using"공유 의도를 사용하는 방법은 무엇입니까?

lottogame 2020. 10. 28. 07:40
반응형

Android에서 이미지를 공유하기 위해 "Share image using"공유 의도를 사용하는 방법은 무엇입니까?


그 앱에 이미지 갤러리 앱이 있습니다. 모든 이미지를 drawable-hdpi 폴더에 넣었습니다. 내 활동에서 이미지를 다음과 같이 호출했습니다.

private Integer[] imageIDs = {
        R.drawable.wall1, R.drawable.wall2,
        R.drawable.wall3, R.drawable.wall4,
        R.drawable.wall5, R.drawable.wall6,
        R.drawable.wall7, R.drawable.wall8,
        R.drawable.wall9, R.drawable.wall10
};

이제 공유 의도를 사용 하여이 이미지를 공유하는 방법을 알고 싶습니다.

     Button shareButton = (Button) findViewById(R.id.share_button);
     shareButton.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {

        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        Uri screenshotUri = Uri.parse(Images.Media.EXTERNAL_CONTENT_URI + "/" + imageIDs);

        sharingIntent.setType("image/jpeg");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        startActivity(Intent.createChooser(sharingIntent, "Share image using"));  

         }
    });

그리고 공유 버튼을 클릭 할 때도 공유 버튼이 있습니다. 공유 상자가 열립니다.하지만 대부분의 서비스가 충돌하거나 일부 서비스를 클릭하면 다음과 같이 말합니다. 이미지를 열 수 없습니다. 어떻게이 문제를 해결할 수 있거나 이미지를 공유 할 수있는 다른 형식 코드가 있습니까? ????

편집하다 :

아래 코드를 사용해 보았습니다. 그러나 작동하지 않습니다.

Button shareButton = (Button) findViewById(R.id.share_button);
     shareButton.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {

        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        Uri screenshotUri = Uri.parse("android.resource://com.android.test/*");
        try {
            InputStream stream = getContentResolver().openInputStream(screenshotUri);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        sharingIntent.setType("image/jpeg");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        startActivity(Intent.createChooser(sharingIntent, "Share image using"));  

         }
    });

누군가가 위의 코드를 수정하거나 적절한 예제를 제공해도 괜찮다면 drawable-hdpi 폴더에서 내 이미지를 어떻게 공유합니까?


Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
    f.createNewFile();
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(bytes.toByteArray());
} catch (IOException e) {                       
        e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));

superM에서 제안한 솔루션은 오랫동안 저에게 효과적 이었지만 최근에는 4.2 (HTC One)에서 테스트 한 후 작동을 멈췄습니다. 이것이 해결 방법이라는 것을 알고 있지만 모든 장치 및 버전에서 나를 위해 일한 유일한 방법이었습니다.

문서에 따르면 개발자는 바이너리 콘텐츠를 보내기 위해 "시스템 MediaStore를 사용"하도록 요청 받았습니다 . 그러나 이것은 미디어 콘텐츠가 장치에 영구적으로 저장된다는 (단점) 단점이 있습니다.

이것이 귀하를위한 옵션 인 경우 권한을 부여 WRITE_EXTERNAL_STORAGE하고 시스템 전체의 MediaStore를 사용할 수 있습니다.

Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");

ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
        values);


OutputStream outstream;
try {
    outstream = getContentResolver().openOutputStream(uri);
    icon.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
    outstream.close();
} catch (Exception e) {
    System.err.println(e.toString());
}

share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Image"));

먼저 권한 추가

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

해상도에서 비트 맵 사용

Bitmap b =BitmapFactory.decodeResource(getResources(),R.drawable.userimage);
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("image/jpeg");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            String path = MediaStore.Images.Media.insertImage(getContentResolver(),
                    b, "Title", null);
            Uri imageUri =  Uri.parse(path);
            share.putExtra(Intent.EXTRA_STREAM, imageUri);
            startActivity(Intent.createChooser(share, "Select"));

블루투스 및 기타 메신저를 통해 테스트

매력처럼 작동합니다.


이 작업을 수행하는 가장 쉬운 방법은 MediaStore를 사용하여 공유하려는 이미지를 임시로 저장하는 것입니다.

Drawable mDrawable = mImageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable) mDrawable).getBitmap();

String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Image"));

From : 의도와 콘텐츠 공유


갤러리에서 이미지를 공유하는 데 사용할 수있는 간단하고 쉬운 코드입니다.

 String image_path;
            File file = new File(image_path);
            Uri uri = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent .setType("image/*");
            intent .putExtra(Intent.EXTRA_STREAM, uri);
            context.startActivity(intent );

Android에서 이미지를 progamatically 공유하는 방법 때로는 뷰의 스냅 샷을 찍고 공유하고 싶으므로 다음 단계를 따르십시오. 1. mainfest 파일에 권한 추가

<uses-permission    
   android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2. 아주 먼저보기의 스크린 샷을 찍습니다. 예를 들어 Imageview, Textview, Framelayout, LinearLayout 등입니다.

예를 들어 oncreate ()에서이 메서드를 호출하여 스크린 샷을 찍을 이미지보기가 있습니다.

 ImageView image= (ImageView)findViewById(R.id.iv_answer_circle);
     ///take a creenshot
    screenShot(image);

스크린 샷을 찍은 후 버튼
클릭 또는 원하는 곳 에서 이미지 공유 방법

shareBitmap(screenShot(image),"myimage");

생성 후이 두 가지 방법을 정의 ##

    public Bitmap screenShot(View view) {
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
            view.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);
    return bitmap;
}

//////// this method share your image
private void shareBitmap (Bitmap bitmap,String fileName) {
    try {
        File file = new File(getContext().getCacheDir(), fileName + ".png");
        FileOutputStream fOut = new FileOutputStream(file);
        bitmap.compress(CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
        file.setReadable(true, false);
        final Intent intent = new Intent(     android.content.Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        intent.setType("image/png");
        startActivity(intent);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

다음은 나를 위해 일한 솔루션입니다. 한 가지 문제는 공유 또는 앱이 아닌 비공개 위치 ( http://developer.android.com/guide/topics/data/data-storage.html#InternalCache )에 이미지를 저장해야한다는 것입니다.

많은 제안이 Apps"비공개"캐시 위치 에 저장하라고 말하지만 , 물론 이것은 사용되는 일반 공유 파일 의도를 포함하여 다른 외부 응용 프로그램을 통해 액세스 할 수 없습니다. 이를 시도하면 실행되지만 예를 들어 dropbox는 파일을 더 이상 사용할 수 없다고 알려줍니다.

/ * STEP 1-아래 파일 저장 기능을 사용하여 비트 맵 파일을 로컬에 저장합니다. * /

localAbsoluteFilePath = saveImageLocally(bitmapImage);

/ * 2 단계-공유 파일 의도에 대한 비공개 절대 파일 경로 공유 * /

if (localAbsoluteFilePath!=null && localAbsoluteFilePath!="") {

    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    Uri phototUri = Uri.parse(localAbsoluteFilePath);

    File file = new File(phototUri.getPath());

    Log.d(TAG, "file path: " +file.getPath());

    if(file.exists()) {
        // file create success

    } else {
        // file create fail
    }
    shareIntent.setData(phototUri);
    shareIntent.setType("image/png");
    shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
    activity.startActivityForResult(Intent.createChooser(shareIntent, "Share Via"), Navigator.REQUEST_SHARE_ACTION);
}   

/ * 이미지 저장 기능 * /

    private String saveImageLocally(Bitmap _bitmap) {

        File outputDir = Utils.getAlbumStorageDir(Environment.DIRECTORY_DOWNLOADS);
        File outputFile = null;
        try {
            outputFile = File.createTempFile("tmp", ".png", outputDir);
        } catch (IOException e1) {
            // handle exception
        }

        try {
            FileOutputStream out = new FileOutputStream(outputFile);
            _bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();

        } catch (Exception e) {
            // handle exception
        }

        return outputFile.getAbsolutePath();
    }

/ * 3 단계-공유 파일 의도 결과 처리. 원격 임시 파일 등이 필요합니다. * /

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

            // deal with this with whatever constant you use. i have a navigator object to handle my navigation so it also holds all mys constants for intents
        if (requestCode== Navigator.REQUEST_SHARE_ACTION) {
            // delete temp file
            File file = new File (localAbsoluteFilePath);
            file.delete();

            Toaster toast = new Toaster(activity);
            toast.popBurntToast("Successfully shared");
        }


    }   

누군가에게 도움이되기를 바랍니다.


내 응용 프로그램에서 다른 응용 프로그램으로보기 또는 이미지를 공유하기 위해 다른 옵션을 검색하는 데 지쳤습니다. 그리고 마침내 해결책을 얻었습니다.

1 단계 : 의도 처리 블록을 공유합니다. 이것은 당신의 전화에 응용 프로그램 목록과 함께 당신의 창을 팝업합니다

public void share_bitMap_to_Apps() {

    Intent i = new Intent(Intent.ACTION_SEND);

    i.setType("image/*");
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    /*compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] bytes = stream.toByteArray();*/


    i.putExtra(Intent.EXTRA_STREAM, getImageUri(mContext, getBitmapFromView(relative_me_other)));
    try {
        startActivity(Intent.createChooser(i, "My Profile ..."));
    } catch (android.content.ActivityNotFoundException ex) {

        ex.printStackTrace();
    }


}

2 단계 : 뷰를 BItmap으로 변환

public static Bitmap getBitmapFromView(View view) {
    //Define a bitmap with the same size as the view
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(),      view.getHeight(), Bitmap.Config.ARGB_8888);
    //Bind a canvas to it
    Canvas canvas = new Canvas(returnedBitmap);
    //Get the view's background
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        //has background drawable, then draw it on the canvas
        bgDrawable.draw(canvas);
    else
        //does not have background drawable, then draw white background on the canvas
        canvas.drawColor(Color.WHITE);
    // draw the view on the canvas
    view.draw(canvas);
    //return the bitmap
    return returnedBitmap;
}

3 단계 :

비트 맵 이미지에서 URI를 가져 오려면

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

SuperM 대답은 나를 위해 일했지만 Uri.parse () 대신 Uri.fromFile ()을 사용했습니다.

Uri.parse ()를 사용하면 Whatsapp에서만 작동했습니다.

이것은 내 코드입니다.

sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mFile));

Uri.parse ()의 출력 :
/storage/emulated/0/Android/data/application_package/Files/17072015_0927.jpg

Uri.fromFile의 출력 :
file : ///storage/emulated/0/Android/data/application_package/Files/17072015_0927.jpg


나는 단지 같은 문제가 있었다.
다음은 기본 코드에 명시 적 파일 작성을 사용하지 않는 답변입니다 (API가 처리하도록 함).

Drawable mDrawable = myImageView1.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image I want to share", null);
Uri uri = Uri.parse(path);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Image"));

이것이 경로입니다 ... Drawable 개체에 이미지 ID를 추가하기 만하면됩니다. 필자의 경우 (위의 코드) 드로어 블은 ImageView에서 추출되었습니다.


이 시도,

Uri imageUri = Uri.parse("android.resource://your.package/drawable/fileName");
      Intent intent = new Intent(Intent.ACTION_SEND);
      intent.setType("image/png");

      intent.putExtra(Intent.EXTRA_STREAM, imageUri);
      startActivity(Intent.createChooser(intent , "Share"));

ref :-http: //developer.android.com/training/sharing/send.html#send-multiple-content

ArrayList<Uri> imageUris = new ArrayList<Uri>();
imageUris.add(imageUri1); // Add your image URIs here
imageUris.add(imageUri2);

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share images to.."));

인 텐트를 통한 텍스트 및 이미지 공유를위한 완벽한 솔루션은 다음과 같습니다.

공유 버튼에서 다음을 클릭하십시오.

Bitmap image;
shareimagebutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            URL url = null;
            try {
                url = new URL("https://firebasestorage.googleapis.com/v0/b/fir-notificationdemo-dbefb.appspot.com/o/abc_text_select_handle_middle_mtrl_light.png?alt=media&token=c624ab1b-f840-479e-9e0d-6fe8142478e8");
                image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            shareBitmap(image);
        }
    });

그런 다음 shareBitmap (image) 메서드를 만듭니다.

private void shareBitmap(Bitmap bitmap) {

    final String shareText = getString(R.string.share_text) + " "
            + getString(R.string.app_name) + " developed by "
            + "https://play.google.com/store/apps/details?id=" + getPackageName() + ": \n\n";

    try {
        File file = new File(this.getExternalCacheDir(), "share.png");
        FileOutputStream fOut = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
        file.setReadable(true, false);
        final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Intent.EXTRA_TEXT, shareText);
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        intent.setType("image/png");
        startActivity(Intent.createChooser(intent, "Share image via"));

    } catch (Exception e) {
        e.printStackTrace();
    }

}

그리고 그냥 시험 해봐 .. !!


Strring temp="facebook",temp="whatsapp",temp="instagram",temp="googleplus",temp="share";

    if(temp.equals("facebook"))
    {
        Intent intent = getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
        if (intent != null) {

            Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
            shareIntent.setType("image/png");
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/folder name/abc.png"));
            shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            shareIntent.setPackage("com.facebook.katana");
            startActivity(shareIntent);

        }
        else
        {
            Toast.makeText(MainActivity.this, "Facebook require..!!", Toast.LENGTH_SHORT).show();
        }
    }
    if(temp.equals("whatsapp"))
    {

        try {
            File filePath = new File("/sdcard/folder name/abc.png");
            final ComponentName name = new ComponentName("com.whatsapp", "com.whatsapp.ContactPicker");
            Intent oShareIntent = new Intent();
            oShareIntent.setComponent(name);
            oShareIntent.setType("text/plain");
            oShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Website : www.google.com");
            oShareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(filePath));
            oShareIntent.setType("image/jpeg");
            oShareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            MainActivity.this.startActivity(oShareIntent);


        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "WhatsApp require..!!", Toast.LENGTH_SHORT).show();
        }
    }
    if(temp.equals("instagram"))
    {
        Intent intent = getPackageManager().getLaunchIntentForPackage("com.instagram.android");
        if (intent != null)
        {
            File filePath =new File("/sdcard/folder name/"abc.png");
            Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
            shareIntent.setType("image");
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/Chitranagari/abc.png"));
            shareIntent.setPackage("com.instagram.android");
            startActivity(shareIntent);

        }
        else
        {
            Toast.makeText(MainActivity.this, "Instagram require..!!", Toast.LENGTH_SHORT).show();

        }
    }
    if(temp.equals("googleplus"))
    {

        try
        {

            Calendar c = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
            String strDate = sdf.format(c.getTime());
            Intent shareIntent = ShareCompat.IntentBuilder.from(MainActivity.this).getIntent();
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, "Website : www.google.com");
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/folder name/abc.png"));
            shareIntent.setPackage("com.google.android.apps.plus");
            shareIntent.setAction(Intent.ACTION_SEND);
            startActivity(shareIntent);
        }catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "Googleplus require..!!", Toast.LENGTH_SHORT).show();
        }
    }
    if(temp.equals("share")) {

        File filePath =new File("/sdcard/folder name/abc.png");  //optional //internal storage
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_TEXT, "Website : www.google.com");
        shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(filePath));  //optional//use this when you want to send an image
        shareIntent.setType("image/jpeg");
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(Intent.createChooser(shareIntent, "send"));

    }

위의 모든 솔루션이 나를 위해 작동하지 Android Api 26 & 27 (Oreo)않습니다 Error: exposed beyond app through ClipData.Item.getUri. 내 상황에 맞는 해결책은

  1. FileProvider.getUriForFile(Context,packagename,File)as를 사용하여 경로 uri 가져 오기
void shareImage() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this,getPackageName(),deleteFilePath));
        startActivity(Intent.createChooser(intent,"Share with..."));
    }
  1. 정의 <provider>귀하의에 Manifest.xml
<provider
     android:name="android.support.v4.content.FileProvider"
     android:authorities="com.example.stickerapplication"
      android:exported="false"
      android:grantUriPermissions="true">
      <meta-data
          android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/file_paths">
       </meta-data>
</provider>
  1. 마지막 단계는 resource디렉토리에 대한 파일 을 정의 하는 것입니다.
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="." />
</paths>
*Note this solution is for `external storage` `uri`

참고 URL : https://stackoverflow.com/questions/7661875/how-to-use-share-image-using-sharing-intent-to-share-images-in-android

반응형