Совместное использование изображения в приложении Android с намерением отправляет его как текстовый файл, а не как фотографию - PullRequest
0 голосов
/ 30 декабря 2018

Я пытаюсь сделать снимок экрана программно, а затем поделиться им с другим приложением, используя Intent.Проблема, с которой я сталкиваюсь, заключается в том, что фотография отправляется в виде текстового файла.

Слушатель кнопок выглядит следующим образом:

shareButton = rootView.findViewById(R.id.shareButton);
    shareButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Bitmap screenshot = Screenshot.takeScreenshot(view.getRootView());
            String filename = "eduMediaPlayerScreenshot";
            String sharePath = Screenshot.storeScreenshot(screenshot, filename);
            Intent intent = Screenshot.shareScreenshot(sharePath, view.getRootView());
            startActivity(intent);
        }
    });

А класс Screenshot выглядит так:

    public class Screenshot {

    public static Bitmap takeScreenshot(View view) {
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache(true);
        Bitmap screenshot = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
        return screenshot;
    }

    public static String storeScreenshot(Bitmap screenshot, String filename) {
        String path = Environment.getExternalStorageDirectory().toString() + "/" + filename;
        OutputStream out = null;
        File imageFile = new File(path);

        try {
            out = new FileOutputStream(imageFile);
            screenshot.compress(Bitmap.CompressFormat.JPEG, 99, out);
            out.flush();

        } catch (FileNotFoundException e) {
            Log.i("Exception:", "File not found.");

        } catch (IOException e) {
            Log.i("Exception:", "Cannot write to output file.");

        } finally {

            try {
                if (out != null) {
                    out.close();
                    return imageFile.toString();
                }

            } catch (Exception e) {
                Log.i("Exception:", "No output file to close.");
            }

        }
        return null;
    }

    public static Intent shareScreenshot(String sharePath, View view) {
        File file = new File(sharePath);
        Uri uri = FileProvider.getUriForFile(view.getContext(),
                BuildConfig.APPLICATION_ID + ".provider", file);
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        return intent;
    }
}

Общая фотография выглядит так: not-заместитель лучших фото

1 Ответ

0 голосов
/ 03 января 2019

Поскольку Android по умолчанию не распознает изображение без расширения, вы должны добавить .jpg в конец имени файла в приведенном выше намерении.Без этого должен быть указан тип MIME.Подробнее об этом здесь .

Это код, который вы можете использовать.

shareButton = rootView.findViewById(R.id.shareButton);
shareButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Bitmap screenshot = Screenshot.takeScreenshot(view.getRootView());
        String filename = "eduMediaPlayerScreenshot.jpg";
        String sharePath = Screenshot.storeScreenshot(screenshot, filename);
        Intent intent = Screenshot.shareScreenshot(sharePath, view.getRootView());
        startActivity(intent);
    }
});
...