简体   繁体   English

图片未共享到Apps

[英]Image not being shared to Apps

I want my users to be able to share an image and select an app to share it to whether its something like their native messenger app, or twitter. 我希望我的用户能够共享图像并选择一个应用程序来共享它,例如其本机Messenger应用程序或Twitter。 Whenever I go to select the app I want to share the image to, I get a message saying "This media can't be loaded" or something like that. 每当我选择要共享图像的应用程序时,都会收到一条消息,提示“无法加载此媒体”或类似的消息。 Here is the sharing code in BitmapUtils.java 这是BitmapUtils.java中的共享代码

static void shareImage(Context context, String imagePath) {
    // Create the share intent and start the share activity
    File imageFile = new File(imagePath);
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("image/*");
    Uri photoURI = FileProvider.getUriForFile(context, FILE_PROVIDER_AUTHORITY, imageFile);
    shareIntent.putExtra(Intent.EXTRA_STREAM, photoURI);
    context.startActivity(shareIntent);
}

Here is my file provider code in my Manifest file: 这是清单文件中的文件提供程序代码:

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

Here is the file_paths file which contains the file paths. 这是包含文件路径的file_paths文件。

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-cache-path name="my_cache" path="." />
    <external-path name="my_images" path="Pictures/" />
</paths>

Here is the share method that is invoked inside the MainActivity class. 这是在MainActivity类内部调用的share方法。

/**
 * OnClick method for the share button, saves and shares the new bitmap.
 */
@OnClick(R.id.share_button)
public void shareMe() {
    // Delete the temporary image file
    BitmapUtils.deleteImageFile(this, mTempPhotoPath);

    // Share the image
    BitmapUtils.shareImage(this, mTempPhotoPath);
}

If you need anymore information that I forgot to show I'll be happy to supply it. 如果您需要其他我忘记显示的信息,我们将很乐意提供。 I'm trying to fix this issue and get my images to share to different apps(I know Facebook has a certain way of sharing images, but I will tackle that later) 我正在尝试解决此问题,并让我的图像共享到其他应用程序(我知道Facebook有某种共享图像的方式,但我稍后会解决)

You can also replicate this issue by downloading the Hide me, Emoji App on the google play store, taking a picture and trying to share it across your apps. 您还可以通过在Google Play商店下载“隐藏我,表情符号”应用程序,拍照并尝试在您的应用程序之间共享来复制此问题。 https://play.google.com/store/apps/details?id=com.aaronapp.hideme https://play.google.com/store/apps/details?id=com.aaronapp.hideme

Try with adding flag Intent.FLAG_GRANT_READ_URI_PERMISSION to Intent 尝试将标志Intent.FLAG_GRANT_READ_URI_PERMISSION添加到Intent

The file you want to share with another app, you need to allow the client app to access the file. 要与另一个应用程序共享的文件,需要允许客户端应用程序访问该文件。 To allow access, grant permissions to the client app by adding the content URI to an Intent and then setting permission flags on the Intent. 要允许访问,请通过将内容URI添加到Intent,然后在Intent上设置权限标志来授予对客户端应用程序的权限。

// Grant temporary read permission to the content URI
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

The permissions you grant are temporary and expire automatically when the receiving app's task stack is finished. 您授予的权限是临时的,并且在接收应用程序的任务堆栈完成后会自动过期。

This will allow you to read files from Internal or external sdcard. 这将允许您从内部或外部sdcard读取文件。

Add this in manifest.xml 在manifest.xml中添加它

<!-- this is For Access External file Storage -->
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.demo.test.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths"/>
</provider>

file_paths.xml file_paths.xml

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

Please try this code, this is working in my case 请尝试此代码,这在我的情况下有效

File filePath = new File(FIlePath);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
ArrayList<Uri> uriArrayList = new ArrayList<>();
uriArrayList.add(getUriFromFilePath(filePath));
intent.setType("image/*");
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriArrayList);
startActivity(intent);



public Uri getUriFromFilePath(Context theCtx, File theSrcPath) {
        Uri requirdUri = null;
        // observation
        // SDKversion: 25 -- Uri.fromFile Not working, So we have to use Provider


        // FileProvider.getUriForFile will not work when the file is located in external Sdcard.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            requirdUri = FileProvider.getUriForFile(theCtx,
                    theCtx.getApplicationContext().getPackageName() + PROVIDER_FILE_EXTENSION,
                    theSrcPath);
        } else {
            requirdUri = Uri.fromFile(theSrcPath);
        }

        return requirdUri;
    }

I have done following changes in your code, i had tested app after changes and able to share image now. 我已经完成了您代码中的更改,更改后我已经测试了应用程序,现在可以共享图像了。 Please check and let me know. 请检查并让我知道。

  1. in MainActivity, shareMe method you have delete the temp file before sharing that why the error was occured. 在MainActivity的shareMe方法中,您在共享错误发生原因之前已删除了临时文件。 now i have delete the Temp file after sharing. 现在我已经共享后删除了Temp文件。

    Modified code in MainActivity.java MainActivity.java中的已修改代码

public static final int REQUEST_CODE_SHARE_FILE = 100;
public void shareMe()
{
       // BitmapUtils.deleteImageFile(this, mTempPhotoPath); delete temp file in on activity result.
        BitmapUtils.shareImage(MainActivity.this, mTempPhotoPath);
}   

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        //If the image capture activity was called and was successful
        if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK)
        {
            processAndSetImage();
        }
        else if(requestCode == REQUEST_CODE_SHARE_FILE)
        {
            BitmapUtils.deleteImageFile(this, mTempPhotoPath);
        }else {
            BitmapUtils.deleteImageFile(this, mTempPhotoPath);
        }
    }

Modified code in BitmapUtils.java BitmapUtils.java中的修改后的代码

 static void shareImage(Activity activity, String imagePath) {
        // Create the share intent and start the share activity
        File imageFile = new File(imagePath);
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        Uri photoURI = FileProvider.getUriForFile(activity, FILE_PROVIDER_AUTHORITY, imageFile);
        shareIntent.putExtra(Intent.EXTRA_STREAM, photoURI);
        activity.startActivityForResult(shareIntent,MainActivity.REQUEST_CODE_SHARE_FILE);
    }
  1. I am testing your app on the device with Android version 6.0 and app gets crashed every time. 我正在使用Android 6.0版的设备测试您的应用,每次应用都会崩溃。 Inside detectFacesandOverlayEmoji method, on line number 32(SparseArray faces = detector.detect(frame);) 在detectFacesandOverlayEmoji方法内,在第32行上(SparseArray faces = detector.detect(frame);)

    a) Sometimes app remains open without showing anything in logcat. a)有时应用保持打开状态,而Logcat中未显示任何内容。 b) Sometimes app crashed with following error in logcat. b)有时应用程序崩溃并在logcat中出现以下错误。

05-24 11:00:27.192 17880-17880/com.aaronapp.hideme E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: com.aaronapp.hideme, PID: 17880
                                                                     java.lang.OutOfMemoryError: Failed to allocate a 51916812 byte allocation with 16765168 free bytes and 36MB until OOM
                                                                         at com.google.android.gms.vision.Frame.zzTM(Unknown Source)
                                                                         at com.google.android.gms.vision.Frame.getGrayscaleImageData(Unknown Source)
                                                                         at com.google.android.gms.vision.face.FaceDetector.detect(Unknown Source)
                                                                         at com.aaronapp.hideme.HideMe.detectFacesandOverlayEmoji(HideMe.java:32)
                                                                         at com.aaronapp.hideme.MainActivity.processAndSetImage(MainActivity.java:153)
                                                                         at com.aaronapp.hideme.MainActivity.onActivityResult(MainActivity.java:133)
                                                                         at android.app.Activity.dispatchActivityResult(Activity.java:6428)
                                                                         at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
                                                                         at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
                                                                         at android.app.ActivityThread.-wrap16(ActivityThread.java)
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:148)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Make use of Picasso, sharing you a working code from my project. 利用Picasso,与您分享我项目中的有效代码。

Put this in your App level gradle, 将此放入您的应用程序级别gradle,

implementation 'com.squareup.picasso:picasso:2.71828'

Code used is given below, 下面给出了使用的代码,

static void shareImage(Context context, String imagePath) {
    // Create the share intent and start the share activity
    Picasso.with(getApplicationContext())
                .load(imagePath)
                .into(new Target() {
                  @Override
                  public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

                    Intent i = new Intent(Intent.ACTION_SEND);
                    i.setType("image/*");
                    i.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(bitmap));
                    if (!TextUtils.isEmpty(des)) {
                      i.putExtra(Intent.EXTRA_TEXT, des);
                    }
                    startActivity(Intent.createChooser(i, "Share Image"));
                  }

                  @Override
                  public void onBitmapFailed(Drawable errorDrawable) {

                  }

                  @Override
                  public void onPrepareLoad(Drawable placeHolderDrawable) {
                  }
                });
      }


public Uri getLocalBitmapUri(Bitmap bmp) {
        Uri bmpUri = null;
        try {
          File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES),
            "share_image_" + System.currentTimeMillis() + ".png");
          FileOutputStream out = new FileOutputStream(file);
          bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
          out.close();
          bmpUri = Uri.fromFile(file);
        } catch (IOException e) {
          e.printStackTrace();
        }
        return bmpUri;
     }

Hope it may help you. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM