ฉันกำลังพยายามเปิดไฟล์โดยใช้แอปอื่น เช่น เปิด .jpg ด้วย Gallery, .pdf ด้วย Acrobat เป็นต้น
ปัญหาที่ฉันมีคือเมื่อฉันพยายามเปิดไฟล์ในแอป มันเปิดเฉพาะแอปที่เลือก แทนที่จะเปิดไฟล์ภายในแอป ฉันลองติดตาม ไฟล์ PDF แบบเปิดของ Android ผ่าน Intent แต่ฉันต้องขาดอะไรบางอย่างไป
public String get_mime_type(String url) {
String ext = MimeTypeMap.getFileExtensionFromUrl(url);
String mime = null;
if (ext != null) {
mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
}
return mime;
}
public void open_file(String filename) {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), filename);
// Get URI and MIME type of file
Uri uri = Uri.fromFile(file).normalizeScheme();
String mime = get_mime_type(uri.toString());
// Open file with user selected app
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
intent.setType(mime);
context.startActivity(Intent.createChooser(intent, "Open file with"));
}
เท่าที่ฉันสามารถบอกได้ มันจะส่งคืนประเภท URI และ MIME ที่ถูกต้อง:
URI: file:///storage/emulated/0/Download/Katamari-ringtone-985279.mp3
MIME: audio/mpeg
setType()
หลังจากsetData()
ล้างข้อมูล ดังนั้นจึงควรใช้setDataAndType()
- person KaosXIV   schedule 03.06.2020