我正在尝试使用XmlPullParseFactory解析本地.xml文件。尽管已在清单文件中应用了权限,但我无法访问路径“/ storage / emulated / 0 / Download / testcards.xml”。
public void parseXML(){
XmlPullParserFactory parserFactory;
try{
parserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = parserFactory.newPullParser();
InputStream is = new FileInputStream(new File("/storage/emulated/0/Download/testcards.xml"));
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is,null);
processParsing(parser);
} catch(XmlPullParserException e){
} catch (IOException e) {
}
}
我的清单文件:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="demoapp1domain.demoapp1">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
.....
当我尝试运行我的程序时,我得到:
java.io.FileNotFoundException:/storage/emulated/0/Download/testcards.xml (权限被拒绝)
这是获取路径的代码:
public void startFileExplorer(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/xml");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "Select your flashcards .XML-file "), REQUEST_CHOOSER);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CHOOSER:
if (resultCode == RESULT_OK) {
final Uri uri = data.getData();
String myXMLFilePath = uri.getPath();
}
break;
}
}
知道为何拒绝许可?
android {
compileSdkVersion 26
defaultConfig {
applicationId "demoapp1domain.demoapp1"
minSdkVersion 21
targetSdkVersion 26
答案 0 :(得分:1)
感谢CommonsWare和Alex,显然你是对的! 它现在可以在运行时请求权限。
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
requestPermissions(permissions,PERMISSION_REQUEST_CODE);
InputStream is = new FileInputStream(new File("/storage/emulated/0/Download/testcards.xml"));