Файл снимка экрана не виден в галерее в Oreo - PullRequest
0 голосов
/ 28 мая 2018

Я пытаюсь сделать снимок экрана и открыть его с помощью средства просмотра изображений, версия Android 7.0 и ниже работает плавно, но выше 7 и выше она не работает.Я создаю каталог и сохраняю скриншот в эту папку. Скриншот сохраняется в эту папку, но не просматривается в y галерее, я могу найти файл с помощью средства просмотра файлов.мой код

MainActivity.java

private static final int PERMISSION_REQUEST_CODE = 1;

 private void takeScreenshot() {
        Date now = new Date();
        android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

        try {
            // image naming and path  to include sd card  appending name you choose for file

            File dir = new File(Environment.getExternalStorageDirectory(), "file status");
            try {
                if (dir.mkdir()) {
                    Toast.makeText(ApplicationStatus.this, "in.", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(ApplicationStatus.this, "ot.", Toast.LENGTH_LONG).show();

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
 String mPath = Environment.getExternalStorageDirectory().toString() + "/" + "file status" + "/" + now + ".jpg";
 View v1 = relativeLayout;
            v1.setDrawingCacheEnabled(true);
            Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
            v1.setDrawingCacheEnabled(false);

            File imageFile = new File(mPath);


            FileOutputStream outputStream = new FileOutputStream(imageFile);
            int quality = 100;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            outputStream.flush();
            outputStream.close();

            openScreenshot(imageFile);
        } catch (Throwable e) {
            // Several error may come out with file handling or DOM
            e.printStackTrace();
        }
    }
private void openScreenshot(File imageFile) {
        try {
            Toast.makeText(ApplicationStatus.this, "dir:." + imageFile, Toast.LENGTH_LONG).show();
            File file = new File(String.valueOf(imageFile));
            if (file.exists()) {
                Toast.makeText(ApplicationStatus.this, "dir:.true", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(ApplicationStatus.this, "dir:.false", Toast.LENGTH_LONG).show();
            }


            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);

            Uri uri = FileProvider.getUriForFile(ApplicationStatus.this, BuildConfig.APPLICATION_ID + ".provider", imageFile);
            intent.setDataAndType(uri, "image/*");
            startActivity(intent);
        } catch (Exception e) {
            Log.e("MYAPP", "exception", e);
        }
    }
  private void requestAppPermissions() {
        if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            return;
        }

        if (hasReadPermissions() && hasWritePermissions()) {
            return;
        }

        ActivityCompat.requestPermissions(this,
                new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                }, PERMISSION_REQUEST_CODE); // your request code
    }

    private boolean hasReadPermissions() {
        return (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
    }

    private boolean hasWritePermissions() {
        return (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
    }
}

res / xml / provider_path.xml

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

манифест

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

 <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

1 Ответ

0 голосов
/ 28 мая 2018

Решение использует MediaScannerConnection после сохранения изображения в памяти.

        // Tell the media scanner about the new file so that it is
        // immediately available to the user.

        MediaScannerConnection.scanFile(this,
                new String[] { file.toString() }, null,
                new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
                Log.i("ExternalStorage", "Scanned " + path + ":");
                Log.i("ExternalStorage", "-> uri=" + uri);
            }
        });

Проверьте ссылку

...