joe*_*er1 17 permissions android sd-card denied
我试图从照片库中选择一个图像文件并写入SD卡.以下是导致异常的代码.在尝试创建FileOutputStream时,它似乎抛出此异常.我将以下行添加到嵌套在application元素中的清单文件中.我找不到问题的解决方案:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
public boolean saveSelectedImage( Uri selectedImage, int imageGroup,
int imageNumber )
{
boolean exception = false;
InputStream input = null;
OutputStream output = null;
if( externalStorageIsWritable() )
{
try
{
ContentResolver content = ctx.getContentResolver();
input = content.openInputStream( selectedImage );
if(input != null) Log.v( CLASS_NAME, "Input Stream Opened successfully");
File outFile = null;
File root = Environment.getExternalStorageDirectory( );
if(root == null) Log.v(CLASS_NAME, "FAILED TO RETRIEVE DIRECTORY");
else Log.v(CLASS_NAME, "ROOT DIRECTORY is:"+root.toString());
output = new FileOutputStream( root+"/Image"+ imageGroup + "_" + imageNumber + ".png" );
if(output != null) Log.e( CLASS_NAME, "Output Stream Opened successfully");
// output = new FileOutputStream
// ("/sdcard/Image"+imageGroup+"_"+imageNumber+".png");
byte[] buffer = new byte[1000];
int bytesRead = 0;
while ( ( bytesRead = input.read( buffer, 0, buffer.length ) ) >= 0 )
{
output.write( buffer, 0, buffer.length );
}
} catch ( Exception e )
{
Log.e( CLASS_NAME, "Exception occurred while moving image: ");
e.printStackTrace();
exception = true;
} finally
{
// if(input != null)input.close();
// if(output != null)output.close();
// if (exception ) return false;
}
return true;
} else
return false;
}
Run Code Online (Sandbox Code Playgroud)
Sau*_*abh 24
这就是清单文件的样子
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".WriteCBTextToFileActivity"
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>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Run Code Online (Sandbox Code Playgroud)
我有这个问题,这里的答案没有解决它,因为我犯了一个非常愚蠢的错误.
确保你给你的Android模拟器一张SD卡......我把SD卡的大小留空了,所以当然找不到任何东西.最重要的是,我在SD卡中指定了一个尚未创建的目录,所以一定要考虑这个案例.
(您可以通过转到Android虚拟设备管理器,编辑您选择的模拟器,并为SD卡大小输入一些值来更改AVD的SD卡设置)
您还必须确保外部存储子系统处于正确状态; 使用Environment.getExternalStorageState()和寻找Environment.MEDIA_MOUNTED是唯一安全的状态.
将异常处理限制IOException在这些部分的周围也是一个好主意,因此不要过度恢复特定于IO的问题,例如未安装的媒体.
如果您需要事件,则广播意图(Intent.ACTION_MEDIA_xxx)具有您可以注册的相同信息IntentListener.
另请注意,使用USB进行调试时可能会禁用外部存储!
设备启动期间还有一段延长的时间,其中外部存储不可用.如果你在启动时做服务,这是一个问题.
通常,您的应用程序在访问时必须知道外部存储状态,并处理它不可用或在访问时不可用的情况.
小智 0
您可以尝试:
String myPath=Environment.getExternalStorageDirectory()+"/Image"+ imageGroup + "_" + imageNumber + ".png";
File myFile = new File();
input = new FileInputStream(myFile);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62494 次 |
| 最近记录: |