Android 图像视图中的图像在共享时仅显示黑色图像?

Android 图像视图中的图像在共享时仅显示黑色图像?,android,android-studio,Android,Android Studio,我正在尝试共享在imageview中显示的图像。 但当共享时,它会显示一个黑屏,提交时会显示“共享失败” 显示 LogCat 06-18 13:47:36.906 4429-4429/com.austurn.keikonew.keiko W/System.err: java.io.IOException: Permission denied at java.io.UnixFileSystem.createFileExclusively0(Native Method)

我正在尝试共享在imageview中显示的图像。 但当共享时,它会显示一个黑屏,提交时会显示“共享失败”

显示 LogCat

06-18 13:47:36.906 4429-4429/com.austurn.keikonew.keiko W/System.err: java.io.IOException: Permission denied
        at java.io.UnixFileSystem.createFileExclusively0(Native Method)
        at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
        at java.io.File.createNewFile(File.java:948)
06-18 13:47:36.907 4429-4429/com.austurn.keikonew.keiko W/System.err:     at com.austurn.keikonew.keiko.ThreeFragment$10.onClick(ThreeFragment.java:2122)
        at android.view.View.performClick(View.java:5637)
        at android.view.View$PerformClick.run(View.java:22429)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
06-18 13:47:36.909 4429-4429/com.austurn.keikonew.keiko W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
06-18 13:47:36.911 4429-4429/com.austurn.keikonew.keiko W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
06-18 13:47:37.034 4429-4440/com.austurn.keikonew.keiko I/art: Background partial concurrent mark sweep GC freed 1063(81KB) AllocSpace objects, 0(0B) LOS objects, 3% free, 122MB/126MB, paused 26.566ms total 119.644ms
06-18 13:47:37.121 4429-4452/com.austurn.keikonew.keiko D/EGL_emulation: eglMakeCurrent: 0xa43052a0: ver 3 1 (tinfo 0xa43032a0)
06-18 13:47:40.471 4429-4452/com.austurn.keikonew.keiko D/EGL_emulation: eglMakeCurrent: 0xa43052a0: ver 3 1 (tinfo 0xa43032a0)
Gradle详细信息如下

 collageImage.setImageBitmap(bmap1);
    Drawable mDrawable = collageImage.getDrawable();
    Bitmap bitmap = ((BitmapDrawable)mDrawable).getBitmap();
    File root = Environment.getExternalStorageDirectory();
    File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.png");
    cachePath.mkdirs();
    try {
        cachePath.createNewFile();
        FileOutputStream ostream = new FileOutputStream(cachePath);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
        ostream.close();
    } catch (Exception e) {
       e.printStackTrace();
    }
    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/png");
    share.putExtra(Intent.EXTRA_STREAM,
    Uri.parse("file:///sdcard/DCIM/Camera/image.png"));
    Intent openThree = new Intent(createChooser(share, "Share Image"));
    startActivity(openThree);
    Toast.makeText(v.getContext(), "Selected: ", Toast.LENGTH_LONG).show();
compileSdkVersion 28
defaultConfig {
    applicationId "com.austurn.keikonew.keiko"
    minSdkVersion 15
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
 Bitmap bitmap = ((BitmapDrawable)mDrawable).getBitmap();

                if (Build.VERSION.SDK_INT >= 23)
                {
                    if (checkPermission())
                    {

                        try {
                            File file = new File(getActivity().getExternalCacheDir(),"logicchip.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_STREAM, Uri.fromFile(file));
                            intent.setType("image/png");
                            startActivity(Intent.createChooser(intent, "Share image via"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        requestPermission(); // Code for permission
                    }
                }
                else
                {

                }


 private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }


    private void requestPermission() {

        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Toast.makeText(getActivity(), "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    }




    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.e("value", "Permission Granted, Now you can use local drive .");
                } else {
                    Log.e("value", "Permission Denied, You cannot use local drive .");
                }
                break;
        }
    }
它在以前的版本和Android Studio的早期版本中工作。但问题发生在版本更新之后

添加Android 6.0(API级别23)及更高版本的运行时权限代码,以下是

这是
WRITE\u EXTERNAL\u STORAGE

if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
    Log.d(TAG,"Permission is granted");

    return true;
}
像这样请求许可

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);

对于更新版本,您必须执行以下操作: 例如:

if (checkSelfPermission(Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            1);
                }
else {
                    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    profile_file_name = "profile_" + System.currentTimeMillis() + ".jpg";
                    File f = new File(android.os.Environment.getExternalStorageDirectory(), profile_file_name);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getApplicationContext(), "com.example.hp.imageuploadapp.provider", f));
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

                    startActivityForResult(intent, 1);
                }



public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 1) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            profile_file_name = "profile_" + System.currentTimeMillis() + ".jpg";
            File f = new File(android.os.Environment.getExternalStorageDirectory(), profile_file_name);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getApplicationContext(), "com.example.hp.imageuploadapp.provider", f));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            startActivityForResult(intent, 1);} 
else {
            Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
        }


    }
}
<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>   
if(checkSelfPermission(Manifest.permission.CAMERA)
!=PackageManager.PERMISSION\u已授予| checkSelfPermission(Manifest.PERMISSION.WRITE\u EXTERNAL\u STORAGE)!=PackageManager.PERMISSION\u已授予| checkSelfPermission(Manifest.PERMISSION.READ\u EXTERNAL\u STORAGE)!=PackageManager.PERMISSION\u已授予){
requestPermissions(新字符串[]{Manifest.permission.CAMERA,Manifest.permission.READ\u EXTERNAL\u STORAGE,Manifest.permission.WRITE\u EXTERNAL\u STORAGE},
1);
}
否则{
Intent Intent=新Intent(android.provider.MediaStore.ACTION\u IMAGE\u CAPTURE);
profile_file_name=“profile_u”+System.currentTimeMillis()+”.jpg”;
文件f=新文件(android.os.Environment.getExternalStorageDirectory(),profile\u File\u name);
intent.putExtra(MediaStore.EXTRA_输出,FileProvider.getUriForFile(getApplicationContext(),“com.example.hp.imageuploadapp.provider”,f));
intent.addFlags(intent.FLAG\授予\读取\ URI\权限);
addFlags(intent.FLAG\u GRANT\u WRITE\u URI\u权限);
startActivityForResult(意向,1);
}
public void onRequestPermissionsResult(int-requestCode,@NonNull-String[]permissions,@NonNull-int[]grantResults){
super.onRequestPermissionsResult(请求代码、权限、授权结果);
if(requestCode==1){
如果(grantResults[0]==PackageManager.PERMISSION\u已授予和&grantResults[1]==PackageManager.PERMISSION\u已授予和&grantResults[2]==PackageManager.PERMISSION\u已授予){
Toast.makeText(这是“授予相机权限”,Toast.LENGTH_LONG.show();
Intent Intent=新Intent(android.provider.MediaStore.ACTION\u IMAGE\u CAPTURE);
profile_file_name=“profile_u”+System.currentTimeMillis()+”.jpg”;
文件f=新文件(android.os.Environment.getExternalStorageDirectory(),profile\u File\u name);
intent.putExtra(MediaStore.EXTRA_输出,FileProvider.getUriForFile(getApplicationContext(),“com.example.hp.imageuploadapp.provider”,f));
intent.addFlags(intent.FLAG\授予\读取\ URI\权限);
addFlags(intent.FLAG\u GRANT\u WRITE\u URI\u权限);
startActivityForResult(意图,1);}
否则{
Toast.makeText(这是“相机权限被拒绝”,Toast.LENGTH_LONG.show();
}
}
}

并在清单文件中添加上述内容

对于上述代码,您需要应用运行时读写权限,并且您的目标是Nougat,这就是为什么您需要使用文件提供程序应用读路径权限。并且需要在Android清单中注册提供者


检查这个

谢谢大家给我一些线索。我把所有的东西都搜索了一遍,结果都成功了。我的代码如下

 collageImage.setImageBitmap(bmap1);
    Drawable mDrawable = collageImage.getDrawable();
    Bitmap bitmap = ((BitmapDrawable)mDrawable).getBitmap();
    File root = Environment.getExternalStorageDirectory();
    File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.png");
    cachePath.mkdirs();
    try {
        cachePath.createNewFile();
        FileOutputStream ostream = new FileOutputStream(cachePath);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
        ostream.close();
    } catch (Exception e) {
       e.printStackTrace();
    }
    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/png");
    share.putExtra(Intent.EXTRA_STREAM,
    Uri.parse("file:///sdcard/DCIM/Camera/image.png"));
    Intent openThree = new Intent(createChooser(share, "Share Image"));
    startActivity(openThree);
    Toast.makeText(v.getContext(), "Selected: ", Toast.LENGTH_LONG).show();
compileSdkVersion 28
defaultConfig {
    applicationId "com.austurn.keikonew.keiko"
    minSdkVersion 15
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
 Bitmap bitmap = ((BitmapDrawable)mDrawable).getBitmap();

                if (Build.VERSION.SDK_INT >= 23)
                {
                    if (checkPermission())
                    {

                        try {
                            File file = new File(getActivity().getExternalCacheDir(),"logicchip.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_STREAM, Uri.fromFile(file));
                            intent.setType("image/png");
                            startActivity(Intent.createChooser(intent, "Share image via"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        requestPermission(); // Code for permission
                    }
                }
                else
                {

                }


 private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }


    private void requestPermission() {

        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Toast.makeText(getActivity(), "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    }




    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.e("value", "Permission Granted, Now you can use local drive .");
                } else {
                    Log.e("value", "Permission Denied, You cannot use local drive .");
                }
                break;
        }
    }

你的目标是奥利奥吗?如果是,则需要使用文件提供程序授予运行时路径权限。并且需要在清单中注册提供者。检查此链接:。不,我用牛轧糖。我是否需要授予运行时权限。感谢来自牛轧糖的sameerYes,这是必需的。