注册自己的Activity
通过mimeType和scheme,可以将自己的Activity与特定格式的内容和协议关联起来,从而用自己的Activity去打开这些内容
mimeType指的是内容格式,比如是txt,还是doc,还是ppt等
scheme指的是协议格式,比如是file,还是http等
<activity
android:name=".view_window.kml.KmlPreviewActivity"
android:label="KML查看器">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data
android:mimeType="application/vnd.google-earth.kml+xml"
android:scheme="content" />
</intent-filter>
</activity>
获得资源URI
在Activity中通过以下代码,就可以获得打开的资源对应的URI
Uri uri = getIntent().getData();
微信URI转文件路径
微信文件的URI,是通过FileProvider分享出去的,我们通过URI,可以获得实际对应的文件位置
但从Android11开始,由于系统权限管理的力度加强,微信的文件已经存放到私有目录
所以我们就算能通过URI拿到文件路径,也不能读取这个文件
只有通过ContentResolver,才能正常访问FileProvider提供的资源
public static String uriToFile(Context context, Uri uri) {
ContentResolver resolver = context.getContentResolver();
String pathUri = uri.getPath().toLowerCase();
if (uri.toString().toLowerCase().startsWith("content://com.tencent.mm.external.fileprovider/external/")) {
String file = ProjectFile.getProjectFile("cache/" + Files.getFileName(pathUri));
InputStream is = resolver.openInputStream(uri);
OutputStream os = new FileOutputStream(file);
Streams.write(is, os);
return file;
}
return null;
}
public static void write(InputStream is, OutputStream os) {
byte[] buffer = new byte[1024 * 1024];
while (true) {
int len = is.read(buffer);
if (len < 0) break;
os.write(buffer, 0, len);
}
os.flush();
is.close();
os.close();
}
|