Как сохранить растровое изображение и поделиться из кеша? - PullRequest
0 голосов
/ 07 апреля 2019

У меня есть метод, который разделяет растровое изображение из приложения со сторонними приложениями для социальных сетей.Я пытаюсь сохранить мое растровое изображение в папке кэша и поделиться им оттуда.Это мой метод:

public void shareMeme(Bitmap bitmap) {
    String path = Objects.requireNonNull(getContext()).getCacheDir().getAbsolutePath();
    Uri uri = Uri.parse(path);

    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/*");
    share.putExtra(Intent.EXTRA_STREAM, uri);
    share.putExtra(Intent.EXTRA_TEXT, "This is my Meme");
    getContext().startActivity(Intent.createChooser(share, "Share Your Meme!"));

    Toast.makeText(getContext(), "The Cache drive is: " + path, Toast.LENGTH_LONG).show();
}

Метод получает растровое изображение из другого метода через свои параметры.Я хочу знать, как включить параметры shareMeme(Bitmap bitmap) в приведенный выше код.

ОБНОВЛЕНИЕ

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.omar.memegenerator">

    ...

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

</manifest>

новый shareMeme(Bitmap bitmap) метод:

    public void shareMeme(Bitmap bitmap) {
    String path = Objects.requireNonNull(getContext()).getCacheDir().getAbsolutePath();
    File file = new File(path + "/Memes/" + timeStamp + counter + ".jpg");
    Uri uri = FileProvider.getUriForFile(getContext(), "com.example.omar.memegenerator.fileprovider", file);
    try {
        OutputStream stream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        stream.flush();
        stream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/*");
    share.putExtra(Intent.EXTRA_STREAM, uri);
    share.putExtra(Intent.EXTRA_TEXT, "This is my Meme");
    share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    getContext().startActivity(Intent.createChooser(share, "Share Your Meme!"));

    Toast.makeText(getContext(), "The Cache drive is: " + path, Toast.LENGTH_LONG).show();
}

Трассировка стека:

2019-04-09 05:08:51.324 19288-19288/com.example.omar.memegenerator E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.omar.memegenerator, PID: 19288
    java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.example.omar.memegenerator/cache/Memes/201904090.jpg
        at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:739)
        at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:418)
        at com.example.omar.memegenerator.TopImageFragment.shareMeme(TopImageFragment.java:232)
        at com.example.omar.memegenerator.TopImageFragment$6.onReceive(TopImageFragment.java:303)
        at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:313)
        at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:121)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6703)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)

1 Ответ

1 голос
/ 07 апреля 2019

Шаг # 1: Используйте compress() на Bitmap, чтобы сохранить его в файл в getCacheDir()

Шаг # 2: Добавьте FileProvider в ваш проект, настроенный для обслуживания файлов из getCacheDir()

Шаг № 3: Используйте FileProvider.getUriForFile() вместо существующего кода, чтобы получить Uri для ввода EXTRA_STREAM

Шаг # 4: Добавьте Intent.FLAG_GRANT_READ_URI_PERMISSION кIntent до вызова startActivity(), чтобы получатель имел права доступа к вашему контенту

...