AndroidStudio中如何成功访问data/themes/0/descriptions.xml且询问用户给予全部文件访问权限并且截取两个之间的文本

AndroidStudio中如何成功访问data/themes/0/descriptions.xml且询问用户给予全部文件访问权限并且截取两个之间的文本

以下回复参考:皆我百晓生、券券喵儿等免费微信小程序作答:
要在Android Studio中访问data/themes/0/descriptions.xml文件并截取其中的内容,你需要执行以下步骤:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
private static final int REQUEST_READ_EXTERNAL_STORAGE = 1;
private void requestReadExternalStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_READ_EXTERNAL_STORAGE);
} else {
readDescriptionsFile();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_EXTERNAL_STORAGE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
readDescriptionsFile();
} else {
Toast.makeText(this, "需要读取外部存储权限", Toast.LENGTH_SHORT).show();
}
}
}
private void readDescriptionsFile() {
try {
File file = new File(Environment.getExternalStorageDirectory(), "data/themes/0/descriptions.xml");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
InputStream inputStream = new FileInputStream(file);
parser.setInput(inputStream, null);
StringBuilder titleBuilder = new StringBuilder();
StringBuilder titleCnBuilder = new StringBuilder();
StringBuilder authorBuilder = new StringBuilder();
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagName = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagName.equals("title")) {
titleBuilder.append(parser.nextText());
} else if (tagName.equals("title-cn")) {
titleCnBuilder.append(parser.nextText());
} else if (tagName.equals("author")) {
authorBuilder.append(parser.nextText());
}
break;
}
eventType = parser.next();
}
String title = titleBuilder.toString().trim();
String titleCn = titleCnBuilder.toString().trim();
String author = authorBuilder.toString().trim();
// 在这里处理截取到的文本内容,例如显示在TextView中
TextView titleTextView = findViewById(R.id.titleTextView);
TextView titleCnTextView = findViewById(R.id.titleCnTextView);
TextView authorTextView = findViewById(R.id.authorTextView);
titleTextView.setText(title);
titleCnTextView.setText(titleCn);
authorTextView.setText(author);
} catch (IOException | XmlPullParserException e) {
e.printStackTrace();
}
}
requestReadExternalStoragePermission()方法,例如在onCreate()方法中或者在用户点击某个按钮时。