权限被拒绝,但在清单中设置了权限

2024-05-12

我收到此错误:

删除失败:ENOENT(没有此类文件或目录):/storage/emulated/0/screenShot.jpg
FileNotFoundException:/storage/emulated/0/screenShot.jpg:打开失败:EACCES(权限被拒绝)

运行此屏幕截图方法时(错误指向从 imageFile 创建 FileOutputStream,在“else”之后):

public void shareScreenshot(View v){
    Date now = new Date();
    android.text.format.DateFormat.format("yyyy-MM-dd_hh-mm-ss", now);

    CharSequence nowStr = DateFormat.format("yyyy-MM-dd_hh-mm-ss", now);

    try {
        // image naming and path  to include sd card  appending name you choose for file
        String mPath = Environment.getExternalStorageDirectory().toString() + "/" + "screenShot" + ".jpg";

        // create bitmap screen capture
        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        File imageFile = new File(mPath);
        if(imageFile.delete()){

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

            startShareIntent(imageFile);

        }else{

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

            startShareIntent(imageFile);
        }


    } catch (Throwable e) {
        // Several error may come out with file handling or OOM
        e.printStackTrace();
        Toast.makeText(this,"Something went wrong, try again.", Toast.LENGTH_SHORT).show();

    }
}

这是我的清单:

<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.android.vending.BILLING" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

要在运行时请求权限,请使用此函数来检查上面和下面的版本 23

public  boolean isPermissionGrantedForStorage() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { 
         //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

确保您的 Activity 实现OnRequestPermissionResult

现在回调将是

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }
}

更重要的是,您没有向 FileOutputStream 写入任何内容。不写怎么能期望存储图像!

理想情况下应该是这样

ByteArrayOutputStream bytearrayoutputstream;
File file;
FileOutputStream fileoutputstream;

@Override
 protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      bytearrayoutputstream = new ByteArrayOutputStream();
      // you code to access image and other logic ...
      Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
      bitmap.compress(Bitmap.CompressFormat.PNG, 60, bytearrayoutputstream);
      file = new File( Environment.getExternalStorageDirectory() + "/SampleImage.png");
     try 
      {
      file.createNewFile();
      fileoutputstream = new FileOutputStream(file);
      fileoutputstream.write(bytearrayoutputstream.toByteArray()); 
      fileoutputstream.close();
      } 
      catch (Exception e) 
      {
           e.printStackTrace();
      } 
}

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

权限被拒绝,但在清单中设置了权限 的相关文章

  • RecyclerView每隔几个项目都是相同的 - 可扩展项目

    我的 recyclerView 有问题 我正在使用此布局来扩展 recyclerView 中的 cardView https github com AAkira ExpandableLayout https github com AAkir
  • 无法禁用 Firestore 中的离线数据

    从我的数据中删除数据后Firestore Database 这需要我的Android app一段时间后才意识到数据已被删除 我认为这是由于自动数据缓存而发生的 我的应用程序与离线使用无关 我想禁用此功能 我已将其添加到我的自定义中Appli
  • 在 Android 上检测已接听的拨出电话

    我知道这个问题已经被问过很多次了 但没有答案 但我仍然希望有人终于解决了这个问题 问题 我有一台运行 Android 2 3 的未 root 设备 我需要创建一项服务 打电话 等待呼叫被应答 接听电话后挂断电话 有超时 和其他许多人一样 我
  • android studio更新到3.0后任务执行失败

    当我更新 Android Studio 3 0 时 出现错误 unable to merge with dex 然后我添加了mutiDexEnabled true并且还添加了com android support multidex 1 0
  • XAMARIN - 添加来自 youtube 的视频

    我搜索如何从 youtube 添加视频的信息 例如 我想从一些 YouTube 链接添加视频 我认为它应该在网络视图中 但我需要一些详细信息 因为我找不到有关我的问题的任何信息 您可以使用 webview 播放 youtube 视频 str
  • android新手需要了解“?android:attr/actionBarSize”

    我正在经历拉尔斯 沃格尔的教程 http www vogella com articles AndroidFragments article html在使用 Fragments 时 我遇到了以下代码 android layout margi
  • Android 应用程序主活动出现 ClassNotFoundException

    大多数设备都可以运行我的应用程序 但我收到此错误报告 java lang RuntimeException Unable to instantiate activity ComponentInfo com company app com c
  • 意图过滤器到底是什么?

    我读过很多关于意图过滤器的文章 但我真的无法理解它们到底是做什么的 那么 如果有人可以用一个清晰 的例子向我解释意图过滤器的作用到底是什么 thanks 我认为这是有据可查的here http developer android com g
  • Android 上 Java 库中的代码出现 NoClassDefFoundError

    我的用户经常遇到错误 应用程序在启动期间崩溃 当应该加载 MainActivity 时 VM 显然找不到该类 我不明白为什么 该应用程序的架构是 我的免费版和专业版都使用一个通用项目 不知道是否相关 请参阅下面的堆栈跟踪 有什么想法吗 ja
  • 不同风格的模块文件

    我正在尝试在同一个应用程序中实现播放服务和华为服务 但希望能够按风格配置使用哪一个 每种风格都使用自己的 applicationIdSuffix 因此 对于每种不同的风格 华为插件都会失败 我无法编译 我的应用程序模块包含agconnect
  • 获取包含位图支持的画布的 Android 视图上的点的像素颜色值

    我正在尝试找出获取给定点上像素颜色值的最佳方法View http developer android com reference android view View html 我可以通过三种方式写入视图 我设置了背景图像View setBa
  • Eclipse Android 模拟器 - 键盘不工作

    我刚刚更新到最新的 SDK 版本 16 使用最新版本的 API 16 创建了新版本的 AVD 并且我的硬件键盘在模拟器上不再工作 甚至我的其他 avd 使用旧版本的 sdk 任何想法如何解决这一问题 您的 AVD 的 键盘支持 硬件属性是否
  • 拥有可重用对话框的最佳方法是什么?

    在 Android 中创建可重用对话框的最佳方法是什么 阅读通过对话框开发指南 http developer android com guide topics ui dialogs html 我知道我可以使用AlertDialog Buil
  • 可下载字体例外

    我决定使用可下载字体 https developer android com guide topics ui look and feel downloadable fonts html在我的项目中 IS 按照指南中的建议实施了所有内容 当我
  • 应用程序运行时相对布局中的元素显示不同

    我有一个ListView在片段内创建 并且它有一个搜索过滤器 问题是 XML 布局在 android studio 中显示正常 但在模拟器或手机中运行时 它显示不同 与我对齐时不正确 并且当我单击SearchView它位于选项卡导航下方 谁
  • 使用磁场计算旋转矩阵

    在获取旋转矩阵值时它包含public static boolean getRotationMatrix float R float I float gravity float geomagnetic 这里我如何计算float gravity
  • 如何在没有 OpenCv Manager 的情况下运行 OpenCV 代码

    我正在使用 OpenCV4Android 版本 2 4 10 并在 Samsung Galayx GT I9300 上测试我的代码 我遇到的问题是 我必须从 Play 商店下载 Opencv Manager 以便我的 opencv 代码运行
  • Android 布局仅使一个视图将自己绘制为横向,但其他所有视图都使用纵向

    我的活动布局中的主要视图元素是 VideoView 我的视频被渲染为设备的横向分辨率 但视频中的所有内容都是横向的 因此仍然需要在设备处于纵向位置时观看 即使我必须将活动设置为android screenOrientation landsc
  • 活动构建变体没有测试工件

    我基于 调试 构建变体创建了一个名为 bitrise 的新构建类型 使用 debug 构建变体时 经过检测的 androidTests 构建并运行良好 但是当我切换到新的 bitrise 构建变体时 出现以下错误 Process finis
  • 带有包含布局的导航抽屉布局

    我认为我的问题实际上很简单 但我不知道如何解决 有一个工作导航抽屉 代码如下

随机推荐